Skip to content

i need to pass an event with my string, to my AWS Lambda function, to use as the prompt to communicate with amazon bedrock.

0

In Android Studio im writing in Kotlin, and i have a string which is the users input. its called userPromptvc. I am calling my function URL with my http client and i have a json payload that is not being used. id like to pass this string as an event and retrieve it in my aws lambda function to use the userPromptvc as my prompt. Please help update my code in order to do this.

Here is my Android studio code in Kotlin:

Thread { // taking user input, and changing the lambda function to process it val userPromptvc = inputFieldvc.text.toString()

                // 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")

                val requestBody = jsonPayload.toRequestBody("application/json".toMediaType())
                Log.d("LambdaInvokeNova", "Request body created")

                val request = Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build()
                Log.d("LambdaInvokeNova", "Request built: $request")

Here is my AWS Lambda Function code:

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 a year ago260 views

1 Answer
1
Accepted Answer

Update your Kotlin code to include the user's input in the JSON payload:

val userPromptvc = inputFieldvc.text.toString()

val jsonPayload = "{\"prompt\":\"$userPromptvc\"}"

val requestBody = jsonPayload.toRequestBody("application/json".toMediaType())

val request = Request.Builder()
    .url(url)
    .post(requestBody)
    .build()

This change will send the user's input as part of the JSON payload to your Lambda function.

  1. In your AWS Lambda function:

Modify your Lambda function to extract the prompt from the event:

def lambda_handler(event, context):
    # Extract the prompt from the event
    user_prompt = json.loads(event['body'])['prompt']

    model_input = {
        "taskType": "TEXT_VIDEO",
        "textToVideoParams": {
            "text": user_prompt  # Use the user's prompt here
        },
        "videoGenerationConfig": {
            "durationSeconds": 6,
            "fps": 24,
            "dimension": "1280x720",
            "seed": 33,
        },
    }

    # Rest of your Lambda function code...

These changes will allow you to pass the user's input from your Android app to your Lambda function and use it as the prompt for Amazon Bedrock. The Lambda function now extracts the prompt from the event body instead of using an environment variable.

Remember to handle potential errors, such as missing prompt in the event, and ensure your Lambda function has the necessary permissions to access Amazon Bedrock and S3.

Sources
Task 3: Build a Serverless Backend
Configure Lambda functions to send information that an Amazon Bedrock agent elicits from the user - Amazon Bedrock
How to build a multilingual document summarization application using Amazon Bedrock | AWS Public Sector Blog

answered a year ago

EXPERT

reviewed a year 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.