// add the dependency for the Google AI client SDK for Android implementation("com.google.ai.client.generativeai:generativeai:0.9.0") }
3.2 初始化生成模型
1 2 3 4 5 6
val generativeModel = GenerativeModel( // The Gemini 1.5 models are versatile and work with most use cases modelName = "gemini-1.5-flash", // Access your API key as a Build Configuration variable (see "Set up your API key" above) apiKey = BuildConfig.apiKey )
3.3 使用场景
1-根据纯文本输入生成文本
1 2 3 4 5 6 7 8 9 10
val generativeModel = GenerativeModel( // The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts modelName = "gemini-1.5-flash", // Access your API key as a Build Configuration variable (see "Set up your API key" above) apiKey = BuildConfig.apiKey )
val prompt = "Write a story about a magic backpack." val response = generativeModel.generateContent(prompt) print(response.text)
2-根据文本和图片输入生成文本(多模态)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
val generativeModel = GenerativeModel( // The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts modelName = "gemini-1.5-flash", // Access your API key as a Build Configuration variable (see "Set up your API key" above) apiKey = BuildConfig.apiKey )
val image1: Bitmap = // ... val image2: Bitmap = // ...
val inputContent = content { image(image1) image(image2) text("What's different between these pictures?") }
val response = generativeModel.generateContent(inputContent) print(response.text)
3-建立多轮对话(聊天)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
val generativeModel = GenerativeModel( // The Gemini 1.5 models are versatile and work with multi-turn conversations (like chat) modelName = "gemini-1.5-flash", // Access your API key as a Build Configuration variable (see "Set up your API key" above) apiKey = BuildConfig.apiKey )
val chat = generativeModel.startChat( history = listOf( content(role = "user") { text("Hello, I have 2 dogs in my house.") }, content(role = "model") { text("Great to meet you. What would you like to know?") } ) )
chat.sendMessage("How many paws are in my house?")