Skip to content

Changing AWS Lambda Function prompt value with an event instead of changing environment variable.

0

In Android Studio i have my aws Lambda functions environment variable being changed in Kotlin. I am doing this to change the prompt in my Lambda function. I need to do this by passing user input as an event to my aws lambda function. I am not sure what the code should look like. Can you please provide code snippets so i can see how this is done?

Android Studio - Kotlin

  • import software.amazon.awssdk.

Thread { // taking user input, and changing the lambda function to process it val userPromptvc = inputFieldvc.text.toString() val userPromptvcQuoted = ""$userPromptvc"" // Wrap in double quotes updateLambdaEnvironmentVariable("myNovaReelFunction", "NOVAPROMPT", userPromptvcQuoted)

            inputFieldvc.setText("")


            // below is letting our Lambda Function Env Var take a second to update
            try {
                Thread.sleep(1000)  // Sleep (block) the current thread for 3 seconds
            } catch (e: InterruptedException) {
                e.printStackTrace()  // Handle potential interruption
            }

            // then we will go ahead and invoke it now that its done updating with user input.
           // invokeLambdaNova()
            // invoke lambda actual function code below for testing
            //Log.d("LambdaInvokeNova", "Starting invokeLambda()")

            val client = OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build()
            Log.d("LambdaInvokeNova", "OkHttpClient created")

            val url = "https://dwyrc3i6pgmugzzdqtkczq2lza0ohpek.lambda-url.us-east-1.on.aws/"
            val jsonPayload = "{\"key1\":\"value1\", \"key2\":\"value2\"}"
            Log.d("LambdaInvokeNova", "Payload prepared: $jsonPayload")

Here is my AWS Lambda Function:

import json import boto3 import os

Create the Bedrock Runtime client. bedrock_runtime = boto3.client("bedrock-runtime")

def lambda_handler(event, context): model_input = { "taskType": "TEXT_VIDEO", "textToVideoParams": { "text": json.loads(os.environ['NOVAPROMPT']) }, "videoGenerationConfig": { "durationSeconds": 6, "fps": 24, "dimension": "1280x720", "seed": 33, # Change the seed to get a different result }, } try: # Start the asynchronous video generation job. invocation = bedrock_runtime.start_async_invoke( modelId="amazon.nova-reel-v1:1", modelInput=model_input, outputDataConfig={ "s3OutputDataConfig": { "s3Uri": "s3://novabucket" } } )

# Extract the S3 object key from the response.

s3_object_key = invocation.get('outputDataConfig', {}).get('s3OutputDataConfig', {}).get('s3Uri', '').split('/')[-1]

 # Extract the invocation ID from the invocationArn
invocation_id = invocation['invocationArn'].split('/')[-1]

# Construct the future object key
future_object_key = f"{invocation_id}/output.mp4"


# Return the object key along with other details.
return {
    "statusCode": 200,
    "body": json.dumps({
        "invocationArn": invocation.get('invocationArn'),
        "requestId": invocation.get('requestId'),
        "futureObjectKey": f"{invocation_id}/output.mp4"
        #future_object_key
    })
}

except Exception as e: # Implement error handling here. message = e.response["Error"]["Message"] return { "statusCode": 500, "body": json.dumps({"error": message}) }

asked 9 months ago106 views
1 Answer
1
import com.amazonaws.services.lambda.AWSLambdaClientBuilder
import com.amazonaws.services.lambda.model.InvokeRequest
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain
import org.json.JSONObject

// ... (in your activity or fragment)

fun invokeLambdaWithUserInput(userPrompt: String) {
    Thread {
        try {
            val lambdaClient = AWSLambdaClientBuilder.standard()
                .withCredentials(DefaultAWSCredentialsProviderChain())
                .withRegion("us-east-1")  // replace with your Lambda's region
                .build()

            val payload = JSONObject()
            payload.put("userPrompt", userPrompt)

            val invokeRequest = InvokeRequest()
                .withFunctionName("myNovaReelFunction")
                .withPayload(payload.toString())

            val invokeResult = lambdaClient.invoke(invokeRequest)

            // Handle the result
            val resultJson = JSONObject(String(invokeResult.payload.array()))
            // Process the result as needed
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }.start()
}

// Usage
val userPrompt = inputFieldvc.text.toString()
invokeLambdaWithUserInput(userPrompt)

This code creates a Lambda client, constructs a JSON payload with the user's input, and invokes the Lambda function with this payload.

  1. AWS Lambda Function:

Modify your Lambda function to expect the user input in the event parameter instead of reading from environment variables:

import json
import boto3

bedrock_runtime = boto3.client("bedrock-runtime")

def lambda_handler(event, context):
    # Extract user prompt from the event
    user_prompt = event.get('userPrompt', '')

    model_input = {
        "taskType": "TEXT_VIDEO",
        "textToVideoParams": {
            "text": user_prompt
        },
        "videoGenerationConfig": {
            "durationSeconds": 6,
            "fps": 24,
            "dimension": "1280x720",
            "seed": 33,
        },
    }

    try:
        invocation = bedrock_runtime.start_async_invoke(
            modelId="amazon.nova-reel-v1:1",
            modelInput=model_input,
            outputDataConfig={
                "s3OutputDataConfig": {
                    "s3Uri": "s3://novabucket"
                }
            }
        )

        invocation_id = invocation['invocationArn'].split('/')[-1]
        future_object_key = f"{invocation_id}/output.mp4"

        return {
            "statusCode": 200,
            "body": json.dumps({
                "invocationArn": invocation.get('invocationArn'),
                "requestId": invocation.get('requestId'),
                "futureObjectKey": future_object_key
            })
        }

    except Exception as e:
        message = str(e)
        return {
            "statusCode": 500,
            "body": json.dumps({"error": message})
        }

This approach allows you to pass the user's input directly to the Lambda function as part of the event, eliminating the need to update environment variables. The Lambda function now extracts the user's prompt from the event parameter instead of reading it from an environment variable.

Remember to update your Lambda function's IAM role to ensure it has the necessary permissions to interact with Amazon Bedrock and S3.

Sources
AWS Lambda env. var. change. | AWS re:Post
Define Lambda function handler in Java - AWS Lambda
Define Lambda function handler in Python - AWS Lambda

answered 9 months ago
EXPERT
reviewed 9 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.