|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Deploy the Bedrock Embedding Proxy (Lambda + API Gateway). |
| 4 | +This creates the serverless translation layer that allows SQL Server |
| 5 | +to call Bedrock via CREATE EXTERNAL MODEL + AI_GENERATE_EMBEDDINGS. |
| 6 | +
|
| 7 | +Usage: |
| 8 | + python3 03_deploy_embedding_proxy.py |
| 9 | +""" |
| 10 | +import boto3 |
| 11 | +import json |
| 12 | +import os |
| 13 | +import time |
| 14 | +import zipfile |
| 15 | +import tempfile |
| 16 | + |
| 17 | +region = os.environ.get('AWS_REGION', 'us-west-2') |
| 18 | +account_id = boto3.client('sts').get_caller_identity()['Account'] |
| 19 | + |
| 20 | +print("Deploying Bedrock Embedding Proxy...") |
| 21 | +print(f" Region: {region}") |
| 22 | +print(f" Account: {account_id}") |
| 23 | + |
| 24 | +iam = boto3.client('iam') |
| 25 | +lam = boto3.client('lambda', region_name=region) |
| 26 | +apigw = boto3.client('apigateway', region_name=region) |
| 27 | + |
| 28 | +# Step 1: Create IAM Role |
| 29 | +ROLE_NAME = 'bedrock-embedding-lambda-role' |
| 30 | +print("\n1. Creating IAM role...") |
| 31 | +try: |
| 32 | + role = iam.create_role( |
| 33 | + RoleName=ROLE_NAME, |
| 34 | + AssumeRolePolicyDocument=json.dumps({ |
| 35 | + "Version": "2012-10-17", |
| 36 | + "Statement": [{"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}] |
| 37 | + }) |
| 38 | + ) |
| 39 | + iam.put_role_policy(RoleName=ROLE_NAME, PolicyName='BedrockAccess', PolicyDocument=json.dumps({ |
| 40 | + "Version": "2012-10-17", |
| 41 | + "Statement": [ |
| 42 | + {"Effect": "Allow", "Action": ["bedrock:InvokeModel"], "Resource": "*"}, |
| 43 | + {"Effect": "Allow", "Action": ["logs:*"], "Resource": "*"} |
| 44 | + ] |
| 45 | + })) |
| 46 | + print(f" Role created: {role['Role']['Arn']}") |
| 47 | + time.sleep(10) # Wait for role propagation |
| 48 | +except iam.exceptions.EntityAlreadyExistsException: |
| 49 | + print(f" Role already exists") |
| 50 | + role = iam.get_role(RoleName=ROLE_NAME) |
| 51 | + |
| 52 | +role_arn = f"arn:aws:iam::{account_id}:role/{ROLE_NAME}" |
| 53 | + |
| 54 | +# Step 2: Create Lambda Function |
| 55 | +FUNCTION_NAME = 'bedrock-embedding-proxy' |
| 56 | +print("\n2. Creating Lambda function...") |
| 57 | + |
| 58 | +lambda_code = ''' |
| 59 | +import json |
| 60 | +import boto3 |
| 61 | +
|
| 62 | +bedrock = boto3.client('bedrock-runtime', region_name='us-west-2') |
| 63 | +
|
| 64 | +def lambda_handler(event, context): |
| 65 | + try: |
| 66 | + body = json.loads(event.get('body', '{}')) |
| 67 | + input_text = body.get('input', body.get('inputText', '')) |
| 68 | + if isinstance(input_text, list): |
| 69 | + input_text = input_text[0] |
| 70 | + dimensions = body.get('dimensions', 1024) |
| 71 | + |
| 72 | + response = bedrock.invoke_model( |
| 73 | + modelId='amazon.titan-embed-text-v2:0', |
| 74 | + contentType='application/json', |
| 75 | + accept='application/json', |
| 76 | + body=json.dumps({'inputText': input_text[:8000], 'dimensions': dimensions}) |
| 77 | + ) |
| 78 | + |
| 79 | + result = json.loads(response['body'].read()) |
| 80 | + embedding = result['embedding'] |
| 81 | + |
| 82 | + return { |
| 83 | + 'statusCode': 200, |
| 84 | + 'headers': {'Content-Type': 'application/json'}, |
| 85 | + 'body': json.dumps({ |
| 86 | + 'object': 'list', |
| 87 | + 'data': [{'object': 'embedding', 'embedding': embedding, 'index': 0}], |
| 88 | + 'model': 'amazon.titan-embed-text-v2', |
| 89 | + 'usage': {'prompt_tokens': len(input_text.split()), 'total_tokens': len(input_text.split())} |
| 90 | + }) |
| 91 | + } |
| 92 | + except Exception as e: |
| 93 | + return { |
| 94 | + 'statusCode': 500, |
| 95 | + 'headers': {'Content-Type': 'application/json'}, |
| 96 | + 'body': json.dumps({'error': {'message': str(e), 'type': 'server_error'}}) |
| 97 | + } |
| 98 | +''' |
| 99 | + |
| 100 | +# Create zip |
| 101 | +with tempfile.NamedTemporaryFile(suffix='.zip', delete=False) as tmp: |
| 102 | + zip_path = tmp.name |
| 103 | + with zipfile.ZipFile(zip_path, 'w') as zf: |
| 104 | + zf.writestr('lambda_function.py', lambda_code) |
| 105 | + |
| 106 | +with open(zip_path, 'rb') as f: |
| 107 | + zip_bytes = f.read() |
| 108 | + |
| 109 | +try: |
| 110 | + lam.create_function( |
| 111 | + FunctionName=FUNCTION_NAME, Runtime='python3.12', |
| 112 | + Role=role_arn, Handler='lambda_function.lambda_handler', |
| 113 | + Code={'ZipFile': zip_bytes}, Timeout=30, MemorySize=256 |
| 114 | + ) |
| 115 | + print(f" Function created: {FUNCTION_NAME}") |
| 116 | +except lam.exceptions.ResourceConflictException: |
| 117 | + lam.update_function_code(FunctionName=FUNCTION_NAME, ZipFile=zip_bytes) |
| 118 | + lam.update_function_configuration(FunctionName=FUNCTION_NAME, Handler='lambda_function.lambda_handler') |
| 119 | + print(f" Function updated: {FUNCTION_NAME}") |
| 120 | + |
| 121 | +time.sleep(5) |
| 122 | + |
| 123 | +# Step 3: Create API Gateway |
| 124 | +print("\n3. Creating API Gateway...") |
| 125 | +apis = apigw.get_rest_apis()['items'] |
| 126 | +existing = [a for a in apis if a['name'] == 'bedrock-embedding-api'] |
| 127 | + |
| 128 | +if existing: |
| 129 | + api_id = existing[0]['id'] |
| 130 | + print(f" API already exists: {api_id}") |
| 131 | +else: |
| 132 | + api = apigw.create_rest_api(name='bedrock-embedding-api', endpointConfiguration={'types': ['REGIONAL']}) |
| 133 | + api_id = api['id'] |
| 134 | + print(f" API created: {api_id}") |
| 135 | + |
| 136 | +# Get root resource |
| 137 | +resources = apigw.get_resources(restApiId=api_id)['items'] |
| 138 | +root_id = [r for r in resources if r['path'] == '/'][0]['id'] |
| 139 | + |
| 140 | +# Create /embed resource if not exists |
| 141 | +embed_resources = [r for r in resources if r.get('pathPart') == 'embed'] |
| 142 | +if embed_resources: |
| 143 | + resource_id = embed_resources[0]['id'] |
| 144 | +else: |
| 145 | + resource = apigw.create_resource(restApiId=api_id, parentId=root_id, pathPart='embed') |
| 146 | + resource_id = resource['id'] |
| 147 | + |
| 148 | +# Create POST method |
| 149 | +try: |
| 150 | + apigw.put_method(restApiId=api_id, resourceId=resource_id, httpMethod='POST', authorizationType='NONE') |
| 151 | +except: |
| 152 | + pass |
| 153 | + |
| 154 | +# Create Lambda integration |
| 155 | +lambda_uri = f"arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/arn:aws:lambda:{region}:{account_id}:function:{FUNCTION_NAME}/invocations" |
| 156 | +try: |
| 157 | + apigw.put_integration(restApiId=api_id, resourceId=resource_id, httpMethod='POST', type='AWS_PROXY', integrationHttpMethod='POST', uri=lambda_uri) |
| 158 | +except: |
| 159 | + pass |
| 160 | + |
| 161 | +# Add Lambda permission |
| 162 | +try: |
| 163 | + lam.add_permission(FunctionName=FUNCTION_NAME, StatementId='apigateway-invoke', Action='lambda:InvokeFunction', Principal='apigateway.amazonaws.com') |
| 164 | +except: |
| 165 | + pass |
| 166 | + |
| 167 | +# Deploy |
| 168 | +apigw.create_deployment(restApiId=api_id, stageName='prod') |
| 169 | + |
| 170 | +endpoint = f"https://{api_id}.execute-api.{region}.amazonaws.com/prod/embed" |
| 171 | +print(f"\n Endpoint: {endpoint}") |
| 172 | + |
| 173 | +# Step 4: Save endpoint for SQL scripts |
| 174 | +env_file = '/tmp/embedding_endpoint.txt' |
| 175 | +with open(env_file, 'w') as f: |
| 176 | + f.write(endpoint) |
| 177 | + |
| 178 | +print(f"\n{'='*60}") |
| 179 | +print(f"DONE! Embedding proxy deployed.") |
| 180 | +print(f"Endpoint: {endpoint}") |
| 181 | +print(f"\nNext: python3.11 run_sql_file.py load_generator/04_register_model.sql") |
| 182 | +print(f"{'='*60}") |
0 commit comments