본문 바로가기

카테고리 없음

[Android] Gemini Chat App (1)

https://ai.google.dev/tutorials/android_quickstart?hl=ko#kotlin 에서 제공하는 빠른시작을 참고하여 Gemini와 

채팅해보려고 합니다. Android Studio Giraffe, Kotlin, jetpack compose를 사용할 예정입니다.

 

먼저 구글 API를 사용해야 하니까 API key가 필요합니다.

https://aistudio.google.com/app/apikey 에서 API key를 생성합시다. 

 

친절하게도 API request, response를 처리해줄 라이브러리를 제공합니다. 어서 추가해줍시다.

추가적으로 viewmodel을 사용할 예정이라 관련 라이브러리도 추가해주겠습니다.

implementation("com.google.ai.client.generativeai:generativeai:0.1.2") 
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.5.1")
implementation("androidx.compose.runtime:runtime-livedata:1.5.4")

 

간단한 인사를 나누기 위해 기본적인 설정을 해줍니다.

class MainViewModel: ViewModel() {

    private val _text = MutableLiveData<String>()
    private val _response = MutableLiveData<String>()
    private val _generativeModel = GenerativeModel(
        modelName = "gemini-pro",
        apiKey = /* your API key */
    )
    val text: LiveData<String> = _text
    val response: LiveData<String> = _response

    val onTextChange: (String) -> Unit = { _text.value = it }

    fun buttonClickAction() {
        viewModelScope.launch(Dispatchers.IO) {
            _response.postValue(
                _generativeModel.generateContent(_text.value?: "").text?: ""
            )
        }
    }
}

 

import androidx.lifecycle.viewmodel.compose.viewModel
import ...

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ETCTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    MainComposable()
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainComposable(
    viewModel: MainViewModel = viewModel(),
) {
    Scaffold {
        Column(
            modifier = Modifier
                .padding(it)
                .fillMaxSize()
        ) {
            Row(modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp)) {
                OutlinedTextField(
                    modifier = Modifier.weight(1f),
                    value = viewModel.text.observeAsState(initial = "").value,
                    onValueChange = viewModel.onTextChange,
                    label = { Text(text = "To Gemini...") },
                    trailingIcon = {
                        IconButton(onClick = { viewModel.buttonClickAction() }) {
                            Icon(imageVector = Icons.Filled.Send, contentDescription = "")
                        }
                    }
                )
            }
            Text(
                modifier = Modifier.fillMaxWidth().padding(20.dp),
                text = viewModel.response.observeAsState(initial = "").value
            )
        }
    }
}

 

그럼 이제 실행시켜 보겠습니다.

 

 

스스로를 GPT라고 하네요...

 

일단 TextInput이 상단에 있으니 사용하기 불편하니 위치를 바꾸어 주어야 할 것 같습니다.

계속해서, 현재 포멧은 이전 대화를 기록하지 못하니 일반적인 채팅 어플 포멧으로 바꾸어 줘야 하겠네요.