Skip to content

Commit

Permalink
Controlled generation in Kotlin
Browse files Browse the repository at this point in the history
  • Loading branch information
rlazo committed Jul 15, 2024
1 parent cd5c269 commit 37a3eb5
Showing 1 changed file with 59 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@

package com.google.ai.client.generative.samples

import com.google.ai.client.generativeai.GenerativeModel
import com.google.ai.client.generativeai.type.FunctionType
import com.google.ai.client.generativeai.type.Schema
import com.google.ai.client.generativeai.type.generationConfig

// Set up your API Key
// ====================
//
Expand All @@ -25,10 +30,64 @@ package com.google.ai.client.generative.samples

suspend fun json_controlled_generation() {
// [START json_controlled_generation]
val jsonSchema = Schema(
name = "recipes",
description = "List of recipes",
type = FunctionType.ARRAY,
items = Schema(
name = "recipe",
description = "A recipe",
type = FunctionType.OBJECT,
properties = mapOf(
"recipeName" to Schema(
name = "recipeName",
description = "Name of the recipe",
type = FunctionType.STRING,
nullable = false
),
),
required = listOf("recipeName")
),
)

val generativeModel =
GenerativeModel(
// Specify a Gemini model appropriate for your use case
modelName = "gemini-1.5-pro",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
apiKey = BuildConfig.apiKey,
generationConfig = generationConfig {
responseMimeType = "application/json"
responseSchema = jsonSchema
})

val prompt = "List a few popular cookie recipes."
val response = generativeModel.generateContent(prompt)
print(response.text)

// [END json_controlled_generation]
}

suspend fun json_no_schema() {
// [START json_no_schema]

val generativeModel =
GenerativeModel(
// Specify a Gemini model appropriate for your use case
modelName = "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
apiKey = BuildConfig.apiKey,
generationConfig = generationConfig {
responseMimeType = "application/json"
})

val prompt = """
List a few popular cookie recipes using this JSON schema:
Recipe = {'recipeName': string}
Return: Array<Recipe>
""".trimIndent()
val response = generativeModel.generateContent(prompt)
print(response.text)

// [END json_no_schema]
}

0 comments on commit 37a3eb5

Please sign in to comment.