Skip to content

Trying to Pass in my prompts to Lambda Function.

0

From Android Studio in Kotlin, im trying to pass my prompts over to my lambda function in aws. Im getting an exception that doesnt really matter. i will point out where in a moment. i want to by pass this exception and keep running my code, as the exception doesnt matter, and i think everything will be working just fine.

Here is part of my code:

findViewById<Button>(R.id.vcsendButton).setOnClickListener {

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

                val userPromptvcTwo = inputFieldvcTwo.text.toString()
                val userPromptvcThree = inputFieldvcThree.text.toString()
                val userPromptvcFour = inputFieldvcFour.text.toString()
                val userPromptvcFive = inputFieldvcFive.text.toString()
                val userPromptvcSix = inputFieldvcSix.text.toString()





                // below is letting our Lambda Function Env Var take a second to update

                // 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(30000, TimeUnit.SECONDS)
                    .readTimeout(30000, TimeUnit.SECONDS)
                    .writeTimeout(30000, TimeUnit.SECONDS)
                    .build()
                Log.d("LambdaInvokeNova", "OkHttpClient created")

                //Below is myNovaReelFunction function URL
               // val url = "https://[lambdafunctionurl].lambda-url.us-east-1.on.aws/"

                //Below is myNovaReelFunctionTwo function URL
                val url = "https://[lambdafunctionurl].lambda-url.us-east-1.on.aws/"




                // temp changing
                //val jsonPayload = "{\"prompt\":\"$userPromptvc\"}"

                //Log.d("LambdaInvokeNova", "Payload prepared: $jsonPayload")

                val jsonPayload = """
{
    "prompt": "$userPromptvc",
    "prompt2": "$userPromptvcTwo"
}

""".trimIndent()

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

                Log.d("LambdaInvokeNova", "Request body created")

                //inputFieldvc.setText("")




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

                client.newCall(request).enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        Log.e("LambdaInvokeNova", "Failed to hit API: ${e.message}", e)
                    }

                    override fun onResponse(call: Call, response: Response) {

                        Log.d("LambdaInvokeNova", "Received response from API")

                        // Ensure response body is not null
                        val responseBody = response.body?.string()
                        if (responseBody == null) {
                            Log.w("LambdaInvokeNova", "Response body is null")
                            return // Exit if no body
                        }
                        Log.d("LambdaInvokeNova", "Response body: $responseBody") // Log the body


                        if (response.isSuccessful) {
                            Log.d("LambdaInvokeNova", "Success: $responseBody")

                            try {

                                // New and improved. WORKS for futureObjectKey
                                // Parse the JSON response
                                val jsonResponse = JSONObject(responseBody)
                                
                                

                                // Extract the body string and parse it as JSON
                                val bodyString = jsonResponse.getString("body")

                                val bodyJson = JSONObject(bodyString)

                                // Now extract the futureObjectKey from the body JSON
                                if (bodyJson.has("futureObjectKey")) {
                                    val futureObjectKey = bodyJson.getString("futureObjectKey")
                                   // Log.d(
                                     //   "LambdaInvokeNova",
                                       // "futureObjectKey: $futureObjectKey"
                                    //)

                                    // below is letting our video get created
                                    try {
                                        //Log.d(
                                          //  "LambdaInvokeNova",
                                            //"Zzzz... started sleeping. Will wake up in 2 1/2 minutes when video is ready..Zzz"
                                        //)
                                        //Thread.sleep(240000) // Sleep (block) the current thread for 4 minutes.
                                        Thread.sleep(150000) // Sleep (block) the current thread for 2 minutes 30 seconds.
                                    } catch (e: InterruptedException) {
                                        e.printStackTrace() // Handle potential interruption
                                    }




                                   // Log.d("LambdaInvokeNova", "Time to wake up!")
                                    //Log.d("LambdaInvokeNova", "Video should be made.")
                                    //Log.d("LambdaInvokeNova", "We have the correct Object Key.")
                                    //Log.d("LambdaInvokeNovaAWAKE","Rise and shine! Lets start grabbing the video..!")
                                    //Log.d("LambdaInvokeNova", "Can we successfully get the presigned URL?... lets see.")





                                    val credentials = AwsBasicCredentials.create(
                                   )

                                    val presigner = S3Presigner.builder()
                                        .region(Region.US_EAST_1) // Or your desired region
                                        .credentialsProvider(StaticCredentialsProvider.create(credentials))
                                        .build()
                                    //Log.d("LambdaInvokeNova", "Presigner client built..")


                                    val getObjectRequest = GetObjectRequest.builder()
                                        .bucket("novabucket")
                                        .key(futureObjectKey)
                                        .build()
                                    //Log.d("LambdaInvokeNova", "GetObject request built..")


                                    val getObjectPresignRequest = GetObjectPresignRequest.builder()
                                        .signatureDuration(Duration.ofHours(12)) // Adjust duration as needed
                                        .getObjectRequest(getObjectRequest)
                                        .build()
                                    //Log.d("LambdaInvokeNova", "GetObject presigned request built..")


                                    val presignedRequest = presigner.presignGetObject(getObjectPresignRequest)

                                    val presignedUrlString: String = presignedRequest.url().toString()

                                    // Print the URL to the log
                                    //Log.d("PresignedUrl", "Generated presigned URL: $presignedUrlString")

                                    runOnUiThread {
                                    //Now we will try and display the video..
                                     val videoViewvc: VideoView = findViewById(R.id.vcvideoView)
                                    val videoUri: Uri = Uri.parse(presignedUrlString)
                                     videoViewvc.setVideoURI(videoUri)

                                     videoViewvc.setOnPreparedListener { mediaPlayer ->
                                      mediaPlayer.isLooping = true // Loop the video
                                    //dont use    // Optional: Adjust video volume
                                    // mediaPlayer.setVolume(0f, 0f) // Mute
                                      mediaPlayer.start()
                                         Log.d("LambdaInvokeNova", "Video should be showing. We put the presigned URL value inside the video view.")
                                       }

                                        // ----> Setting the link so the user can download their video.

                                        // Assuming you have a TextView in your layout with the ID 'linkTextView'
                                        val linkTextView: TextView = findViewById(R.id.hyperlinkTextView)
                                            linkTextView.visibility = TextView.VISIBLE
                                        // The link you want to display and make clickable
                                        val actualLink = presignedUrlString // <-- Replace with your link

                                        // Create the HTML string with the hyperlink
                                        val htmlLink = "<a href=\"$actualLink\">Click here to download your video!</a>"

                                        // Set the text to the TextView, interpreting the HTML
                                        // Use HtmlCompat.fromHtml for better compatibility across Android versions
                                        @Suppress("DEPRECATION") // For older versions of Android
                                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                                            linkTextView.text = Html.fromHtml(htmlLink, Html.FROM_HTML_MODE_COMPACT)
                                        } else {
                                            linkTextView.text = Html.fromHtml(htmlLink)
                                        }

                                        // Make the links within the TextView clickable
                                        linkTextView.movementMethod = LinkMovementMethod.getInstance()

                                }

                                } else {
                                    Log.w("JSONParsing", "Missing key: futureObjectKey")
                                }
                            } catch (e: org.json.JSONException) {
                                Log.e("LambdaInvokeNova", "Error parsing JSON: ${e.message}", e)
                            }
                        } else {
                            Log.e("LambdaInvokeNova", "HTTP error: ${response.code} - ${response.message}")
                        }

                      }
                    })
            }.start()
        }

This is the line giving me the exception:

                                val bodyString = jsonResponse.getString("body")

If you provide code, please update my existing code so it works please. Thank you!

asked a year ago191 views

1 Answer
0

To bypass the exception and continue running your code, you can wrap the JSON parsing in a try-catch block. This will allow your code to continue executing even if there's an issue with parsing the "body" field. Here's how you can modify your code:

try {
    // Parse the JSON response
    val jsonResponse = JSONObject(responseBody)
    
    // Try to get the body string, but provide a default if it's not found
    val bodyString = try {
        jsonResponse.getString("body")
    } catch (e: JSONException) {
        // Log the error, but provide a default JSON string
        Log.e("LambdaInvokeNova", "Error getting 'body' from response: ${e.message}")
        "{}"  // Default empty JSON object
    }

    val bodyJson = JSONObject(bodyString)

    // Now extract the futureObjectKey from the body JSON
    if (bodyJson.has("futureObjectKey")) {
        val futureObjectKey = bodyJson.getString("futureObjectKey")
        // ... rest of your code ...
    } else {
        Log.w("JSONParsing", "Missing key: futureObjectKey")
    }
} catch (e: JSONException) {
    Log.e("LambdaInvokeNova", "Error parsing JSON: ${e.message}", e)
}

// Continue with the rest of your code here

This modification does the following:

  1. It wraps the entire JSON parsing block in a try-catch for JSONException.
  2. It specifically handles the case where "body" might not be present in the response.
  3. If "body" is not found, it logs the error and provides a default empty JSON object to continue execution.
  4. The rest of your code remains the same, allowing it to proceed even if there were issues with parsing.

This approach allows your code to continue running even if there's an issue with the JSON structure or missing fields. It also provides more detailed logging, which can help you diagnose issues in the future. Remember to handle potential null or empty values appropriately in the rest of your code.
Sources
Changing AWS Lambda Function prompt value with an event instead of changing environment variable. | AWS re:Post
i need to pass an event with my string, to my AWS Lambda function, to use as the prompt to communicate with amazon bedrock. | AWS re:Post

answered a year ago

AWS
SUPPORT ENGINEER

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.