1월 2주차에는 Gemini를 이용한 채팅을 구현한 내용입니다.
https://github.com/yveskalume/gemini-chat
GitHub - yveskalume/gemini-chat: a sample project using Gemini, the Google's latest family of large language models.
a sample project using Gemini, the Google's latest family of large language models. - GitHub - yveskalume/gemini-chat: a sample project using Gemini, the Google's latest family of large lan...
github.com
소개
gpt의 월 구독자로써 1달전 구글의 Gemini 1.0 발표후 계속 관심을 가졌는데 관련 글들이 하나씩 올라오다 채팅을 구현한 라이브러리에 대한 글이 올라왔습니다. 코드를 열어보고 따라 적어보니 gemini api의 사용법이 gpt api와 약간의 차이점이 느껴졌습니다.
내용
package com.yveskalume.geminichat
import android.graphics.Bitmap
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.ai.client.generativeai.GenerativeModel
import com.google.ai.client.generativeai.type.content
import kotlinx.coroutines.launch
class MainViewModel : ViewModel() {
// set your API key here
private val apiKey = ""
private val geneminiProModel by lazy {
GenerativeModel(
modelName = "gemini-pro",
apiKey = apiKey
).apply {
startChat()
}
}
private val geneminiProVisionModel by lazy {
GenerativeModel(
modelName = "gemini-pro-vision",
apiKey = apiKey
).apply {
startChat()
}
}
val isGenerating = mutableStateOf(false)
val conversations = mutableStateListOf<Triple<String, String, List<Bitmap>?>>()
fun sendText(textPrompt: String, images: SnapshotStateList<Bitmap>) {
isGenerating.value = true
conversations.add(Triple("sent", textPrompt, images.toList()))
conversations.add(Triple("received", "", null))
val generativeModel = if (images.isNotEmpty()) geneminiProVisionModel else geneminiProModel
val inputContent = content {
images.forEach { imageBitmap ->
image(imageBitmap)
}
text(textPrompt)
}
viewModelScope.launch {
generativeModel.generateContentStream(inputContent)
.collect { chunk ->
conversations[conversations.lastIndex] = Triple(
"received",
conversations.last().second + chunk.text,
null
)
}
isGenerating.value = false
}
}
}
뷰모델의 일부입니다.
사진 유무에 따라 모델을 설정하고 코루틴과 collect 함수를 이용해서 수신된 메세지를 반영하는 구조입니다.
Build with the Gemini API | Google AI for Developers
Integrate the Gemini API, quickly develop prompts, and transform ideas into code to build AI apps.
ai.google.dev
여기서 api키를 받아서 api키를 넣으면 그대로 작동하는 코드입니다.
정리
Gemini의 챗봇을 깔끔하게 구현한 라이브러리였습니다. 저장해두고 필요할때 사용하면 좋을 것 같습니다.
** Kotlin Weekly **
kotlinweekly.net
'Kotlin Weekly' 카테고리의 다른 글
Kotlin Weekly # -387 "Kotlin 꼬리 재귀의 최적화" (0) | 2024.01.01 |
---|---|
Kotlin Weekly # -386 "Koin 2023: 성장과 미래 계획 " (0) | 2023.12.25 |
Kotlin Weekly # -385 "Kotlin Compiler Plugins" (0) | 2023.12.18 |
Kotlin Weekly # -384 "Jetpack Compose의 Modifiers" (0) | 2023.12.13 |
Kotlin Weekly # -383 "Kotlin 사용 주의점" (0) | 2023.12.13 |