Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Build a Claude Coding Assistant with Lambda & Bedrock

· 5 min read · Smart Home

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks you through building a serverless coding assistant that uses Anthropic's Claude on Amazon Bedrock, triggered by AWS Lambda. You'll create an API that accepts a coding question and returns a Claude-generated answer, all without managing servers. You'll need an AWS account with Bedrock access, the AWS CLI configured, and basic familiarity with Python and AWS services.

What You'll Need

  • An AWS account with access to Amazon Bedrock (Claude models must be enabled in the us-east-1 or us-west-2 region)
  • AWS CLI installed and configured with credentials that have permissions for Lambda, IAM, and Bedrock
  • Python 3.9+ installed locally (for writing the Lambda function)
  • Basic knowledge of AWS Lambda, IAM roles, and API Gateway (optional but helpful)

Step-by-Step

  1. Enable Bedrock model access – In the AWS Console, go to Amazon Bedrock, then "Model access". Request access to Anthropic Claude (e.g., Claude 3 Sonnet or Haiku). This can take a few minutes.
  2. Create an IAM role for Lambda – In IAM, create a new role with the following trust policy: {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}. Attach the AWS managed policy AWSLambdaBasicExecutionRole and a custom inline policy that allows bedrock:InvokeModel on the Claude model ARN (e.g., arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-sonnet-20240229-v1:0).
  3. Write the Lambda function code – Create a file named lambda_function.py with the following content (adjust the model ID to the one you enabled):
    import json
    import boto3
    
    bedrock = boto3.client('bedrock-runtime', region_name='us-east-1')
    MODEL_ID = 'anthropic.claude-3-sonnet-20240229-v1:0'
    
    def lambda_handler(event, context):
        # Parse the prompt from the API request
        try:
            body = json.loads(event.get('body', '{}'))
            prompt = body.get('prompt', '')
        except json.JSONDecodeError:
            return {'statusCode': 400, 'body': json.dumps({'error': 'Invalid JSON'})}
    
        if not prompt:
            return {'statusCode': 400, 'body': json.dumps({'error': 'Missing prompt'})}
    
        # Prepare the request payload for Claude
        payload = {
            'anthropic_version': 'bedrock-2023-05-31',
            'max_tokens': 1024,
            'messages': [{'role': 'user', 'content': prompt}]
        }
    
        try:
            response = bedrock.invoke_model(
                modelId=MODEL_ID,
                contentType='application/json',
                accept='application/json',
                body=json.dumps(payload)
            )
            response_body = json.loads(response['body'].read())
            answer = response_body['content'][0]['text']
            return {'statusCode': 200, 'body': json.dumps({'answer': answer})}
        except Exception as e:
            return {'statusCode': 500, 'body': json.dumps({'error': str(e)})}
    
  4. Package the function – Install the AWS SDK (boto3) into a local folder and zip it with your code. Run:
    mkdir package
    pip install boto3 --target package
    cp lambda_function.py package/
    cd package
    zip -r ../lambda.zip .
  5. Create the Lambda function – In the AWS Console, go to Lambda, click "Create function", choose "Author from scratch", name it (e.g., claude-coding-assistant), set Runtime to Python 3.12, and choose the IAM role you created. After creation, upload the lambda.zip file via the "Upload from" button in the Code tab.
  6. Test the function – Create a test event with a JSON body like {"body": "{\"prompt\": \"Write a Python function to reverse a string.\"}"}. Invoke the test and verify you get a response with an answer field.
  7. Expose it via API Gateway – Create a new REST API in API Gateway. Create a resource (e.g., /ask) with a POST method. Set the integration type to Lambda, point it to your function, and deploy the API to a stage (e.g., prod). Note the invoke URL.
  8. Test the API – Use curl or Postman to send a POST request to the invoke URL with a JSON body: {"prompt": "Explain recursion in simple terms."}. You should get a JSON response with the answer.

Common Mistakes

  • Not enabling Bedrock model access – you'll get an AccessDeniedException.
  • Using the wrong model ID – check the exact ID in the Bedrock console, as it varies by region and model.
  • Forgetting to attach the Bedrock permission to the IAM role – Lambda will time out or throw an error.
  • Misparsing the API Gateway event – API Gateway wraps the body as a string, so you must json.loads it first.
  • Using the wrong payload format for Claude – the anthropic_version and messages structure are required.

Tips

  • Use Claude 3 Haiku for faster responses and lower cost if your prompts are short.
  • Add error handling for empty prompts and invalid JSON to return clear error messages.
  • Set a reasonable timeout (e.g., 30 seconds) in Lambda configuration, as Claude can take a few seconds to respond.
  • Consider using environment variables for the model ID so you can change it without redeploying the code.
  • Enable CloudWatch logging to debug invocation errors.

Troubleshooting

  • AccessDeniedException – Check that your IAM role has bedrock:InvokeModel permission and that the model ARN is correct. Also verify model access is enabled in the Bedrock console.
  • Lambda times out – Increase the timeout in the Lambda configuration (try 30 seconds). Also check that the function has network access to Bedrock (it should by default, as Bedrock is an AWS service).
  • API Gateway returns 502 – Check CloudWatch logs for the Lambda function. The most common cause is malformed JSON in the event body.
  • Claude returns an error about the request format – Ensure the payload matches the exact structure for the Claude 3 API on Bedrock, including anthropic_version.
  • Function works in test but not via API – Remember that API Gateway sends the body as a string, so you need to parse it as JSON twice (once for the outer event, once for the body).

Frequently Asked Questions

  1. Can I use a different Claude model? – Yes, you can change the MODEL_ID to any Claude model you have access to, such as Claude 3 Haiku or Claude 3.5 Sonnet. Update the model ID in the code and ensure your IAM policy includes the new ARN.
  2. How do I secure the API? – You can add an API key in API Gateway, or use AWS Cognito for authentication. For simple use, you can also restrict access by IP.
  3. Can I make the assistant remember conversation history? – Not with this simple setup. Each request is stateless. To maintain context, you'd need to store conversation history in DynamoDB and pass it in the messages array.
  4. What is the cost? – You pay for Lambda invocations, API Gateway requests, and Bedrock tokens. Claude 3 Haiku is the cheapest, while Sonnet is more expensive. See AWS pricing pages for current rates.
  5. Can I use this with other AWS regions? – Yes, but you need to enable Bedrock model access in that region and update the region in the boto3 client and the model ARN.
  6. How do I add a system prompt? – You can add a system field in the payload to set the assistant's behavior, e.g., "You are a helpful coding assistant."