La petición es:
1 2 3 4 5 6 7 |
curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer sk-code" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Para qué sirve Kotlin?"}] }' |
Desde Kotlin:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import java.io.BufferedReader import java.io.DataOutputStream import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL fun main() { val apiKey = "sk-CODE" val url = URL("https://api.openai.com/v1/chat/completions") val connection = url.openConnection() as HttpURLConnection connection.requestMethod = "POST" connection.setRequestProperty("Content-Type", "application/json") connection.setRequestProperty("Authorization", "Bearer $apiKey") connection.doOutput = true val requestBody = """ { "model": "gpt-3.5-turbo", "messages": [ { "role": "user", "content": "Para qué sirve kotliln?" } ] } """.trimIndent() val outputStream = DataOutputStream(connection.outputStream) outputStream.writeBytes(requestBody) outputStream.flush() outputStream.close() val responseCode = connection.responseCode if (responseCode == HttpURLConnection.HTTP_OK) { val inputStream = BufferedReader(InputStreamReader(connection.inputStream)) val response = StringBuilder() var inputLine: String? while (inputStream.readLine().also { inputLine = it } != null) { response.append(inputLine) } inputStream.close() val jsonResponse = response.toString() println("Respuesta: $jsonResponse") } else { println("Error al realizar la solicitud: $responseCode") } connection.disconnect() } |