I’m getting the following error :
{
“error”: {
“message”: “You didn’t provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you’re accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.”,
“type”: “invalid_request_error”,
“param”: null,
“code”: null
}
}
this is theChatRepository class that interacts with OpenAI API using Retrofit:
class ChatRepository {
private val apiClient = ApiClient.retrofitService
fun createChatCompletion(message : String){
/* CoroutineScope(Dispatchers.IO)
.launch {*/
try{
val chatRequest = ChatRequest(arrayListOf(
Message("Introduce your self and Lets ask me what topic I want to discuss"
,"system"),
Message(message,"user"),
),
CHAT_GPT_MODEL
)
apiClient.createChatCompletion(chatRequest).enqueue(object : Callback<ChatResponse>{
override fun onResponse(
call: Call<ChatResponse>,
response: Response<ChatResponse>
) {
val code = response.code()
println("chat request : $chatRequest")
println("chat resp : $response")
if(response.isSuccessful){
val msg = response.body()?.choices?.get(0)?.message
if (msg != null)
{println("message $msg" )}
else {
println("msg null")
}
val message = response.body()?.choices?.get(0)?.message
Log.d("message", message?.toString() ?: "Message is null")
}
else {
Log.d("Error",response.errorBody().toString())
}
}
override fun onFailure(call: Call<ChatResponse>, t: Throwable) {
t.printStackTrace()
}
})
}
catch (e: Exception){
e.printStackTrace()
}
}
}
this is ApiClient object that configures a Retrofit instance for making API requests :
object ApiClient {
private val retrofit = Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
// we need to add converter factory to
// convert JSON object to Java object
.build()
/**
* A public Api object that exposes the lazy-initialized Retrofit service
*/
val retrofitService : ApiInterface by lazy { retrofit.create(ApiInterface::class.java) }
/*fun getInstance (): ApiInterface{
synchronized(this){
return retrofitService
}*/
}
this is the ApiInterface that defines a Retrofit interface for making API requests. It sends a POST request to OpenAI GPT-3 chat completion API :
interface ApiInterface {
@POST("chat/completions?Content-Type=application/json&Authorization=Bearer $OPENAI_API_KEY")
//@POST("chat/completions")
fun createChatCompletion(
@Body chatRequest : ChatRequest,
) : Call<ChatResponse>
}
Please I need your help , I’ve been stuck on this error for too long