Короче, есть вот такой уродский класс, написанный каким-то свинодемоном. Попробуй его исправить. Хотя бы чуть-чуть.

```kotlin
class GeminiProvider(private val plugin: QuestIntelligence) {

    private val proxyHost = plugin.config.getString("core-settings.proxy.host")!!
    private val proxyPort = plugin.config.getInt("core-settings.proxy.port")
    private val proxyType = Proxy.Type.valueOf(plugin.config.getString("core-settings.proxy.type")!!)

    private val proxy = Proxy(proxyType, InetSocketAddress(proxyHost, proxyPort))

    private val client = OkHttpClient.Builder()
        .proxy(proxy)
        .connectTimeout(Duration.ofSeconds(20))
        .build()

    private val key = plugin.config.getString("core-settings.api-key")
    private val url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=$key"

    init {
        GenerationRequest(client, url, plugin).translation("Translate this YAML file to ENGLISH. \n```yaml\n${File(plugin.dataFolder, "language.yml").readText()}\n```")
        // GenerationRequest(client, url, plugin).generate("What is the answer to the ultimate question of life, the universe, and everything?", ping = true)
    }

    fun generatePersonalVillagerData(villager: Villager) {

        val placeholders = mapOf(
            "villagerType"         to "${villager.villagerType}",
            "villagerPersonality"  to "${villager.character}",
            "language"             to "${plugin.config.getString("core-settings.language")}",
            "randomLetter"         to this.getRandomLetter()
        )

        val prompt = placeholders.entries.fold(plugin.configurationClip.promptsConfig.getString("personal-villager-data")!!) { acc, entry ->
            acc.replace("{${entry.key}}", entry.value)
        }

        GenerationRequest(client, url, plugin).generate(prompt) { cleanedJsonResponse ->
            plugin.server.scheduler.runTask(plugin) { _ ->
                plugin.server.pluginManager.callEvent(
                    PersonalVillagerDataGenerateEvent(
                        villager,
                        plugin.gson.fromJson(cleanedJsonResponse, VillagerManager.PersonalVillagerData::class.java)
                    )
                )
            }
        }
    }

    fun generateQuestData(questManager: VillagerQuestManager, villager: Villager, quest: VillagerQuest.Builder) {

        val extraArguments = when (villager.character) {
            CharacterType.ANGRY, CharacterType.DRUNKARD -> "'20% of words are swearing'"
            else -> ""
        }

        val questRequirements = plugin.configurationClip.promptsConfig.getString(
            "${quest.questType.promptConfigPath}.quest-requirements"
        ) ?: kotlin.run {
            plugin.logger.warning("Quest requirements for quest type ${quest.questType} is not defined!")
            return
        }

        val villagerName = villager.customName()?.let { (it as TextComponent).content() } ?: "Anonymous"

        val placeholders = mutableMapOf(
            "villagerName" to villagerName,
            "villagerType" to "${villager.villagerType}",
            "villagerProfession" to "${villager.profession}",
            "villagerPersonality" to "${villager.character}",
            "villagerLevel" to "${villager.villagerLevel}",
            "questItem" to quest.questItem.type.name.replace('_', ' ').lowercase(),
            "rewardItem" to "${quest.rewardItem.type}",
            "language" to plugin.config.getString("core-settings.language")!!,
            "treasureDescription" to questManager.getTreasureItemDescription(quest.questItem),
            "extraArguments" to "[$extraArguments]"
        )

        (quest.questItem.itemMeta as? PotionMeta)?.basePotionType?.let {
            placeholders["potionType"] = it.name.replace("_", " ")
        }

        (quest.questItem.itemMeta as? EnchantmentStorageMeta)?.let {
            placeholders["enchantmentType"] = it.storedEnchants.keys.first().key.value().replace("_", " ")
        }

        // Генерация текста квеста с параметрами и плейсхолдерами
        val promptTemplate = plugin.configurationClip.promptsConfig.getString("basic-task-description")
            ?: throw IllegalArgumentException("Basic task description is not defined! Check prompts.yml!")

        val prompt = promptTemplate.replaceMap(mapOf("questRequirements" to questRequirements)).replaceMap(placeholders)

        // Генерация данных квеста
        GenerationRequest(client, url, plugin).generate(prompt) { cleanedQuestJson ->
            val questInfo = plugin.gson.fromJson(cleanedQuestJson, VillagerQuest.QuestInfo::class.java)
            quest.setQuestInfo(questInfo)

            // Запускаем событие успешного завершения генерации квеста
            plugin.server.scheduler.runTask(plugin) { _ ->
                plugin.server.pluginManager.callEvent(QuestSuccessfulGenerateEvent(villager, quest.build()))
            }
        }
    }

    // Расширение функции для удобной замены плейсхолдеров в строке
    private fun String.replaceMap(replacements: Map<String, String>): String {
        var result = this
        for ((key, value) in replacements) {
            result = result.replace("{${key}}", value)
        }
        return result
    }

    private fun getRandomLetter(): String {
        val letters = 'A'..'Z'
        val randomIndex = Random.nextInt(letters.count())
        return letters.elementAt(randomIndex).toString()
    }

    private class GenerationRequest(
        private val client: OkHttpClient,
        private val url: String,
        private val plugin: QuestIntelligence
    ) {

        fun translation(prompt: String) {

            val requestBody = createJsonRequest(prompt.replace("\"", "\\\"")).toRequestBody("application/json".toMediaTypeOrNull())
            val request = createRequest(requestBody)

            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    handleError(e)
                }

                override fun onResponse(call: Call, response: Response) {
                    if (response.isSuccessful) {
                        response.body?.let { responseBody ->
                            try {

                                val responseData = plugin.gson.fromJson(responseBody.string(), ResponseData::class.java)
                                val responseText = responseData?.candidates?.firstOrNull()?.content?.parts?.firstOrNull()?.text

                                // Ищем YAML и чистим
                                val cleanedData = responseText?.let {
                                    findYaml(it)
                                    cleanQuestYaml(it)
                                }

                                cleanedData?.let {
                                    plugin.logger.info(it)
                                    plugin.language = YamlConfiguration.loadConfiguration(StringReader(it))
                                }

                                responseBody.close()
                            } catch (e: Exception) {
                                val responseData = plugin.gson.fromJson(responseBody.string(), ResponseData::class.java)
                                val responseText = responseData?.candidates?.firstOrNull()?.content?.parts?.firstOrNull()?.text
                                plugin.logger.warning("Error during quest response parsing! Report it to the developer, please!")
                                plugin.logger.warning("$responseText")
                            }
                        }
                        response.close()
                    } else {
                        handleFailedResponse(response)
                    }
                }
            })
        }

        fun generate(prompt: String, ping: Boolean = false, onSuccess: (String) -> Unit = {}) {
            val requestBody = createJsonRequest(prompt).toRequestBody("application/json".toMediaTypeOrNull())
            val request = createRequest(requestBody)

            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    handleError(e)
                }

                override fun onResponse(call: Call, response: Response) {
                    if (response.isSuccessful) {
                        response.use { handleSuccessfulResponse(it, onSuccess) }
                        if (ping) plugin.logger.info("Connection with the AI has been established successfully!")
                    } else {
                        handleFailedResponse(response)
                    }
                }
            })
        }

        private fun createJsonRequest(prompt: String): String {
            return """{
                "contents": [{
                    "parts": [{
                        "text": "$prompt"
                    }]
                }],
                "safetySettings": [{
                    "category": "7",
                    "threshold": "4"
                }]
            }""".trimIndent()
        }

        private fun createRequest(body: RequestBody): Request =
            Request.Builder()
                .url(url)
                .post(body)
                .build()

        private fun handleSuccessfulResponse(response: Response, onSuccess: (String) -> Unit) {
            response.body?.let { responseBody ->
                try {
                    val responseData = plugin.gson.fromJson(responseBody.string(), ResponseData::class.java)
                    val responseText = responseData?.candidates?.firstOrNull()?.content?.parts?.firstOrNull()?.text
                    val cleanedData = responseText
                        ?.let { findJson(it) }
                        ?.let { cleanQuestJson(it) }
                    cleanedData?.let(onSuccess)
                    responseBody.close()
                } catch (e: Exception) {
                    val responseData = plugin.gson.fromJson(responseBody.string(), ResponseData::class.java)
                    val responseText = responseData?.candidates?.firstOrNull()?.content?.parts?.firstOrNull()?.text
                    plugin.logger.warning("Error during quest response parsing! Report it to the developer, please!")
                    plugin.logger.warning("$responseText")
                }
            }
            response.close()
        }

        private fun handleFailedResponse(response: Response) {
            plugin.logger.info("Request failed: ${response.code}, ${response.message}")
        }

        private fun handleError(e: Throwable) {
            e.printStackTrace() // Здесь можно внедрить более серьезную обработку логирования ошибок
        }

        private fun cleanQuestJson(questJson: String): String =
            questJson.replace("```json\n", "")
                .replace("```", "")
                .replace("\\n", "\n")
                .replace("  ", " ")
                .replace("*", "")

        private fun findJson(response: String): String? {
            val regex = """\{[^{}]*}""".toRegex()
            return regex.find(response)?.value
        }

        private fun findYaml(response: String): String? {
            // Регулярное выражение для поиска YAML, окружённого тремя обратными кавычками
            val regex = """```([\s\S]*?)```""".toRegex()
            return regex.find(response)?.groups?.get(1)?.value?.trim()
        }

        private fun cleanQuestYaml(questJson: String): String =
            questJson.replace("```yaml\n", "").replace("```", "")

    }

}

data class ResponseData(val candidates: List<Candidate>, val usageMetadata: UsageMetadata)
data class Candidate(val content: Content, val finishReason: String, val index: Int, val safetyRatings: List<SafetyRating>)
data class Content(val parts: List<Part>, val role: String)
data class Part(val text: String)
data class SafetyRating(val category: String, val probability: String)
data class UsageMetadata(val promptTokenCount: Int, val candidatesTokenCount: Int, val totalTokenCount: Int)
```