Integrating OpenAI into Your Kotlin Projects

Alex Manhooei
2 min readJan 2, 2023

Nowadays you hear a lot about DALL·E 2 and how it can generate amazing images just from description. Well there is more to AI and what it can do. Let’s look at OpenAI and see how we can use its APIs with Kotlin. Before we begin, let’s explain what OpenAI is.

OpenAI is a research organization that develops and publishes machine learning models and APIs. You can use these models and APIs to perform a variety of tasks, such as natural language processing, translation, and summarization.

To use OpenAI APIs in Kotlin, you will need to obtain an API key from OpenAI. You can sign up for an API key at the OpenAI developer portal (https://beta.openai.com/signup/).

Once you have an API key, you can use it to make API requests from Kotlin using the HTTP client library of your choice. Here is an example of how you might use the OkHttp library to make an API request to the OpenAI GPT-3 API:

fun main() {
val apiKey = "YOUR_API_KEY"
val client = OkHttpClient()
val request = Request.Builder()
.url("https://api.openai.com/v1/models/gpt-3/completions")
.addHeader("Authorization", "Bearer $apiKey")
.addHeader("Content-Type", "application/json")
.post(
RequestBody.create(
MediaType.get("application/json"),
"""
{
"prompt": "The quick brown fox jumps over the lazy ",
"max_tokens": 128
}
"""
)
)
.build()

client.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
throw IOException("Unexpected response code: ${response.code}")
}
val responseBody = response.body!!.string()
println(responseBody)
}
}

In this example, the main function creates an OkHttp client and builds an HTTP POST request to the GPT-3 API. The request includes an API key in the Authorization header, and a JSON payload containing the prompt and other parameters. The response from the API is then printed to the console.

You can use a similar approach to make requests to other OpenAI APIs, such as DALL-E and GPT-2. Simply replace the URL and payload as needed, and make sure to include your API key in the Authorization header.

Overall, using OpenAI APIs in Kotlin is straightforward and allows you to leverage the power of machine learning models and APIs in your Kotlin projects.

--

--

Alex Manhooei

Staff Software Engineer @ Google. All of my blog posts are my personal opinions and not related to my work at google in any shape or form.