我目前正在开发一款使用 ChatGPT OpenAI API 提供对话式 AI 功能的应用程序。每当我尝试发送消息时,机器人都会发送此错误\'okhttp3.responsebody$
我目前正在开发一款使用 ChatGPT OpenAI API 提供对话式 AI 功能的应用程序。
每当我尝试发送消息时,机器人都会发送此错误“okhttp3.responsebody$Companion$asresponsebody$1@8d63711d.\”
有人能告诉我如何解决这个错误吗?
这是我的代码:
class ChatviewModel : ViewModel() {
private val _messageList = MutableLiveData<MutableList<Message>>()
val messageList: LiveData<MutableList<Message>> get() = _messageList
init {
_messageList.value = mutableListOf()
}
fun addToChat(message: String, sentBy: String, timeStamp: String) {
val currentList = _messageList.value ?: mutableListOf()
currentList.add(Message(message, sentBy, timeStamp))
_messageList.postValue(currentList)
}
fun getCurrentTimestamp() : String{
return SimpleDateFormat("hh mm a", Locale.getDefault()).format(Date())
}
private fun addResponse(response: String) {
_messageList.value?.removeAt(_messageList.value?.size?.minus(1) ?: 0)
addToChat(response, Message.SENT_BY_BOT, getCurrentTimestamp())
}
private suspend fun handleApiResponse(response :
Response<CompletionResponse>){
withContext(Dispatchers.Main){
if (response.isSuccessful){
response.body()?.let {
completionResponse ->
val result = completionResponse.choices.firstOrNull()?.text
if (result != null){
addResponse(result.trim())
}else{
addResponse("No Choices found")
}
}
}else{
addResponse("Failed to get response ${response.errorBody()}")
}
}
}
fun callApi(question: String) {
addToChat("Typing....", Message.SENT_BY_BOT, getCurrentTimestamp())
val completionRequest = OnCompletion(
model = "text-davinci-003",
prompt = question,
maxToken = 4000
)
viewModelScope.launch {
try {
val response = ApiClientClass.apiService.getCompletions(completionRequest)
handleApiResponse(response)
} catch (e: SocketTimeoutException) {
addResponse("Timeout : $e")
}
}
}
}
interface OpenAi {
// https://api.openai.com/v1/completions
@Headers("Authorization:Bearer$MY_API_KEY")
@POST("v1/completions")
suspend fun getCompletions(@Body completionResponse : OnCompletion)
: Response<CompletionResponse>
}