How to create a REST API call equivalent programmatically in Kotlin, specifically the formatting of contents, parts and text?

Hi,

I’m trying to use GenerateContentRequest() as part of the input for text generation POST API call providing a text prompt like “Could you summarize the following text?” and the text which I want to summarize. Basically the equivalent of this:

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=apiKey" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[{"text": "Could you summarize the following text?"},{"text": "Some text here"}]
        }]
       }' 2> /dev/null

The reason I’m trying to use the equivalent REST API call instead of the GenerativeModel.generateContent() function directly is because I need to add a couple of headers. Here’s where I need help:

val parts: List<Part> = listOf(Part("Could you summarize the following text?"), Part("Some text here")) // <- Trying to initialize Part
val content = Content (parts = parts)
val contents = listOf(content)
val newRequest = GenerateContentRequest(contents = contents)

I’m not sure how to initialize Part (com.google.ai.client.generativeai.type.Part) as I’m getting an error saying “Interface Part does not have constructors”. I have also tried creating a new class that extends Part, but I don’t see anything that I can use from there. There’s less documentation on the library than is typically available for other Google libraries. Some have suggested using TextPart() instead but the Content() function does not accept the TextPart type as an input. It would be great if someone has more insights on this.

Hi!, there’s a convenient extension function called content that makes prompt creation simple. Here’s how your code would look like when using it:

 val prompt = content {
                text("Could you summarize the following text?")
                text("Some text here")
            }

You can then use prompt as the parameter when calling model.generateContent()