Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using OpenAI API with Kotlin

Introduction

This tutorial demonstrates how to integrate and use the OpenAI API with Kotlin to leverage advanced AI capabilities in your applications.

1. Setting Up Your OpenAI API Key

Before starting, make sure you have your OpenAI API key ready. You can obtain it from the OpenAI website after signing up for an account.

2. Adding Dependencies

To use the OpenAI API in your Kotlin project, you will need to add the necessary dependencies to your build.gradle file.

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2")
implementation("com.squareup.okhttp3:okhttp:4.9.1")
                    

3. Making API Requests

To make requests to the OpenAI API using Kotlin, you'll use the OkHttp library for HTTP requests.

Text Completion

Here’s an example of making a request for text completion:

import okhttp3.*
import org.json.JSONObject

val client = OkHttpClient()

fun fetchCompletion(apiKey: String, prompt: String): String? {
    val url = "https://api.openai.com/v1/completions"
    val json = JSONObject()
    json.put("model", "text-davinci-003")
    json.put("prompt", prompt)
    json.put("max_tokens", 50)

    val body = RequestBody.create(
        MediaType.parse("application/json; charset=utf-8"),
        json.toString()
    )

    val request = Request.Builder()
        .url(url)
        .post(body)
        .addHeader("Authorization", "Bearer $apiKey")
        .build()

    val response = client.newCall(request).execute()
    return if (response.isSuccessful) {
        val responseBody = response.body()?.string()
        val jsonResponse = JSONObject(responseBody)
        val choices = jsonResponse.getJSONArray("choices")
        choices.getJSONObject(0).getString("text").trim()
    } else {
        null
    }
}

fun main() {
    val apiKey = "YOUR_API_KEY_HERE"
    val prompt = "Translate English to French: Hello, how are you?"
    val completion = fetchCompletion(apiKey, prompt)
    println("Translated Text: $completion")
}
                    

Output: Translated Text: Bonjour, comment ça va?

This Kotlin code sends a POST request to the OpenAI API for text completion and prints the API response.

Code Generation

Here’s an example of making a request for code generation:

import okhttp3.*
import org.json.JSONObject

val client = OkHttpClient()

fun fetchCodeGeneration(apiKey: String, prompt: String): String? {
    val url = "https://api.openai.com/v1/engines/davinci-codex/completions"
    val json = JSONObject()
    json.put("prompt", prompt)
    json.put("max_tokens", 150)
    json.put("stop", arrayOf("\n"))

    val body = RequestBody.create(
        MediaType.parse("application/json; charset=utf-8"),
        json.toString()
    )

    val request = Request.Builder()
        .url(url)
        .post(body)
        .addHeader("Authorization", "Bearer $apiKey")
        .build()

    val response = client.newCall(request).execute()
    return if (response.isSuccessful) {
        val responseBody = response.body()?.string()
        val jsonResponse = JSONObject(responseBody)
        val choices = jsonResponse.getJSONArray("choices")
        choices.getJSONObject(0).getString("text").trim()
    } else {
        null
    }
}

fun main() {
    val apiKey = "YOUR_API_KEY_HERE"
    val prompt = "Generate Python code to sort an array using bubble sort"
    val code = fetchCodeGeneration(apiKey, prompt)
    println("Generated Code: $code")
}
                    
Output: 
    ```python
    def bubble_sort(arr):
        n = len(arr)
        for i in range(n):
            for j in range(0, n-i-1):
                if arr[j] > arr[j+1]:
                    arr[j], arr[j+1] = arr[j+1], arr[j]
        return arr
    ```
                    

This Kotlin code sends a POST request to the OpenAI Codex engine for code generation and prints the generated code.

4. Handling Responses

Once you receive a response from the API, you can handle it in your Kotlin code.

Text Completion

Here’s how you might handle the completion response:

// Assuming `response` contains the API response
val responseBody = response.body()?.string()
val jsonResponse = JSONObject(responseBody)
val choices = jsonResponse.getJSONArray("choices")
val text = choices.getJSONObject(0).getString("text").trim()
println("Translated Text: $text")
                    

In this example, `response` contains the JSON response from the OpenAI API.

Code Generation

Here’s how you might handle the code generation response:

// Assuming `response` contains the API response
val responseBody = response.body()?.string()
val jsonResponse = JSONObject(responseBody)
val choices = jsonResponse.getJSONArray("choices")
val code = choices.getJSONObject(0).getString("text").trim()
println("Generated Code: $code")
                    

In this example, `response` contains the JSON response from the OpenAI API with the generated code.

Conclusion

Integrating the OpenAI API with Kotlin allows you to enhance your applications with powerful AI capabilities. Explore more API endpoints and functionalities to innovate further.