Build Your Own Chatbot in Kotlin with GPT: A Step-by-Step Guide
Tags: ai, gpt3, kotlin
Published: 2024-06-12 20:47:34

In this post, I'll guide you through a practical example of how to integrate GPT (Generative Pre-trained Transformer) into a Kotlin application to create a basic chatbot. This chatbot will be able to respond to user queries naturally and efficiently.

### Setting Up the Project

**Step 1: Set Up Dependencies**
First, make sure you have the necessary dependencies in your project. We'll use OkHttp to handle HTTP requests and org.json to work with JSON.

Add the following dependencies to your build.gradle.kts file:

```
 dependencies {
    implementation("org.jetbrains.kotlin:kotlin-stdlib")
    implementation("com.squareup.okhttp3:okhttp:4.9.1")
    implementation("org.json:json:20210307")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")
 }
```
### Folder structure:

```
ChatbotKotlinGPT/
├── build.gradle.kts
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle.kts
└── src/
    ├── main/
    │   ├── kotlin/
    │   │   ├── Chatbot.kt
    │   │   ├── GPTClient.kt
    │   │   └── ConversationHandler.kt
    │   └── resources/
    └── test/
        ├── kotlin/
        └── resources/

```
**Step 2: Configure the GPT Request**

Create a class  `GPTClient.kt` to handle requests to the GPT API:


function to send requests to the GPT API and receive responses. You'll need an API key from OpenAI, which you can obtain by signing up on their platform.

```
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import org.json.JSONObject

class GPTClient(private val apiKey: String) {
    private val client = OkHttpClient()

    fun getResponse(prompt: String): String? {
        val requestBody = JSONObject()
            .put("model", "gpt-3.5-turbo")
            .put("messages", listOf(
                mapOf("role" to "user", "content" to prompt)
            ))
            .put("max_tokens", 100)
            .toString()

        val request = Request.Builder()
            .url("https://api.openai.com/v1/chat/completions")
            .post(RequestBody.create("application/json".toMediaTypeOrNull(), requestBody))
            .addHeader("Authorization", "Bearer $apiKey")
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                println("Error: ${response.code}")
                println("Error Body: ${response.body?.string()}")
                return null
            } else {
                val responseBody = response.body?.string()
                return JSONObject(responseBody)
                    .getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content")
            }
        }
    }

    fun getResponseSafely(prompt: String): String {
        return try {
            val response = getResponse(prompt)
            response ?: "Error: No response from GPT."
        } catch (e: Exception) {
            "Exception: ${e.message}"
        }
    }
}

```

**Step 3: Handle Exceptions**

It's important to handle exceptions properly to ensure your application is robust.

```
fun getResponseSafely(prompt: String): String {
        return try {
            val response = getResponse(prompt)
            response ?: "Error: No response from GPT."
        } catch (e: Exception) {
            "Exception: ${e.message}"
        }
    }
```
### Using Coroutines for Asynchronous Calls

To improve the efficiency and responsiveness of your application, use Kotlin coroutines to handle GPT API calls asynchronously, Create a class to handle the conversation: `ConversationHandler.kt`, To improve the user experience, you can store the conversation history and provide it to GPT to maintain context.

```
import kotlinx.coroutines.*

class ConversationHandler(private val gptClient: GPTClient) {
    private val conversationHistory = mutableListOf<String>()

    fun start() = runBlocking {
        while (true) {
            print("You: ")
            val userInput = readLine()
            if (userInput.isNullOrEmpty()) break
            conversationHistory.add("You: $userInput")
            val context = conversationHistory.joinToString("\n")
            val gptResponse = async { gptClient.getResponseSafely("Context: $context\nResponse:") }
            val response = gptResponse.await()
            println("Chatbot: $response")
            conversationHistory.add("Chatbot: $response")
        }
    }
}

```
###Implementing the Chatbot

**Step 1: Create a Simple Interface**

For this example, we'll use a basic console interface to demonstrate interaction with the chatbot. `Chatbot.kt`.

```
fun main() {
    val apiKey = "YOUR_API_KEY" // replace with you API_KEY
    val gptClient = GPTClient(apiKey)
    val conversationHandler = ConversationHandler(gptClient)
    conversationHandler.start()
}

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/10a4ercx8dl2x64di1g5.png)


### Repository

https://github.com/josmel/ChatbotKotlinGPT
### Conclusion

Integrating GPT into a Kotlin application to create a basic chatbot is an excellent way to enhance user interaction. This example provides a solid foundation upon which you can build and add more features as needed. Explore and experiment with these tools to discover their full potential!