Skip to content

Latest commit

 

History

History
256 lines (187 loc) · 6.7 KB

File metadata and controls

256 lines (187 loc) · 6.7 KB

Integration Examples

This directory contains practical examples showing how to integrate the lib/ components into different types of applications.

⚠️ Important: Service-Specific Credentials

All examples use Bedrock service-specific credentials with bearer token authentication. The lib/bedrock_client.py module handles this automatically.

Parameter names: service_credential_id and service_credential_password (not standard AWS access key names). See lib/ README for details.

Examples

1. Standalone Script (standalone_bedrock_call.py)

Use Case: Running Bedrock calls from a local script or cron job

What it demonstrates:

  • Direct usage of BedrockClient without Secrets Manager
  • Hardcoded credentials (for testing/development)
  • Simple, straightforward integration

Run it:

# Install dependencies
pip install boto3

# Run the example
python examples/standalone_bedrock_call.py

Key code:

from bedrock_client import BedrockClient

# Use service-specific credentials (bearer token auth)
client = BedrockClient(
    service_credential_id="your-service-specific-credential-id",
    service_credential_password="your-service-specific-credential-password",
    region="us-east-1"
)

response = client.invoke_model(
    prompt="Your question here",
    model_id="us.anthropic.claude-sonnet-4-5-20250929-v1:0"
)

2. Lambda Integration (lambda_integration.py)

Use Case: AWS Lambda function for serverless Bedrock access

What it demonstrates:

  • Integration with AWS Lambda
  • Using CredentialManager to retrieve credentials from Secrets Manager
  • Client caching for performance
  • API Gateway request/response handling
  • Error handling patterns

Deploy it:

# This is a reference implementation
# See src/lambda/main.py for the actual deployed version

# To test locally:
python examples/lambda_integration.py

Key code:

from bedrock_client import BedrockClient
from credential_manager import CredentialManager

def get_bedrock_client():
    cred_manager = CredentialManager(secret_name, region)
    credentials = cred_manager.get_credentials()
    # credentials dict keys match BedrockClient constructor params
    return BedrockClient(
        service_credential_id=credentials['service_credential_id'],
        service_credential_password=credentials['service_credential_password'],
        region=credentials['region']
    )

def lambda_handler(event, context):
    client = get_bedrock_client()
    response = client.invoke_model(prompt, model_id)
    return {'statusCode': 200, 'body': json.dumps(response)}

Checking Credential Rotation Age

If you're using automatic credential rotation, you can check whether credentials need rotation:

from lib.credential_manager import CredentialManager

manager = CredentialManager("bedrock-demo/commercial-credentials", "us-gov-west-1")

# Check if credentials are approaching rotation age
needs_rotation, message, age_days = manager.needs_rotation(max_age_days=90)
if needs_rotation:
    print(f"Warning: {message}")
else:
    print(f"Credentials OK: {message}")

Common Integration Patterns

Pattern 1: Service-Specific Credentials (Recommended)

from lib.bedrock_client import BedrockClient

# Use Bedrock service-specific credentials (bearer token auth)
client = BedrockClient(
    service_credential_id="your-service-specific-credential-id",
    service_credential_password="your-service-specific-credential-password",
    region="us-east-1"
)

When to use:

  • ✅ Cross-partition Bedrock access

Pattern 2: Secrets Manager

from lib.bedrock_client import BedrockClient
from lib.credential_manager import CredentialManager

# Get credentials from Secrets Manager
manager = CredentialManager("my-secret", "us-gov-west-1")
credentials = manager.get_credentials()

# Create client
client = BedrockClient(**credentials)

When to use:

  • Lambda functions
  • EC2 instances with IAM roles
  • Containers

Pattern 3: Environment Variables

import os
from lib.bedrock_client import BedrockClient

client = BedrockClient(
    service_credential_id=os.environ['BEDROCK_CREDENTIAL_ID'],
    service_credential_password=os.environ['BEDROCK_CREDENTIAL_PASSWORD'],
    region=os.environ.get('AWS_REGION', 'us-east-1')
)

When to use:

  • Container deployments
  • CI/CD pipelines
  • Development environments

Pattern 4: Client Caching (Performance)

from lib.bedrock_client import BedrockClient

# Global cached client
_client = None

def get_client():
    global _client
    if _client is None:
        _client = BedrockClient(...)
    return _client

# Use cached client
client = get_client()
response = client.invoke_model(...)

When to use:

  • Lambda functions (warm starts)
  • Long-running applications
  • High-throughput scenarios

Requirements

All examples require:

pip install boto3

For Secrets Manager integration, you also need:

  • AWS credentials configured (via IAM role or AWS CLI)
  • Permissions to access Secrets Manager

Security Best Practices

  1. Never hardcode credentials in code
  2. Use Secrets Manager for credential storage
  3. Rotate credentials regularly (check with CredentialManager.needs_rotation() - see snippet above)
  4. Use IAM roles when running on AWS infrastructure

See SECURITY_CONTROLS.md for full security guidance.

Troubleshooting

"CredentialError: Secret not found"

  • Verify the secret name is correct
  • Check IAM permissions for Secrets Manager access
  • Ensure you're using the correct AWS region

"BedrockClientError: Failed to invoke model"

  • Verify credentials are valid and not expired
  • Check network connectivity to Bedrock endpoint
  • Ensure the model ID is correct and available

"ImportError: No module named 'lib'"

  • Ensure you've added lib/ to Python path:
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src', 'lib'))

Next Steps

  1. Review the examples to understand different integration patterns
  2. Copy src/lib/ to your project
  3. Choose the pattern that fits your use case
  4. Adapt the example to your specific needs
  5. Test thoroughly before deploying

Additional Resources

Questions?

These examples are designed to be self-contained and easy to understand. If you have questions:

  1. Check the inline comments in each example
  2. Review the lib/ component documentation
  3. See the main project README for architecture details