想說玩一下 在android studio 用chatgpt
結果玩一玩一直錯@@
網路找資料也一直在修改
private lateinit var viewModel: ViewModel
改來改去還是錯@@
再拜託各位大神了
MainActivity
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.get
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: ViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProvider(this).get(ViewModel::class.java)
buttonSend.setOnClickListener {
val apiKey = "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" // 替換為您的GPT-3 API金鑰
val userMessage = editTextUserMessage.text.toString()
GlobalScope.launch(Dispatchers.IO) {
val response = viewModel.getChatCompletion(apiKey, userMessage)
runOnUiThread {
textViewBotResponse.text = response
}
}
}
}
}
ViewModel
class ViewModel {
private val apiService: ApiService
init {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.openai.com/v1/") // GPT-3 API的基本URL
.addConverterFactory(GsonConverterFactory.create())
.build()
apiService = retrofit.create(ApiService::class.java)
}
suspend fun getChatCompletion(apiKey: String, prompt: String): String {
val request = Gpt3Request(prompt)
val response = apiService.getChatCompletion("Bearer $apiKey", request)
if (response.choices.isNotEmpty()) {
return response.choices[0].text
} else {
return "No response available"
}
}
}