为什么要在Kotlin应用中集成ChatGPT?
想象一下:你正在用Kotlin编写一个应用程序,突然发现它缺少一个“大脑”。用户提出问题,程序却卡住了。熟悉吗?集成ChatGPT API到Kotlin可以将普通应用变成一个智能助手。这不是一时的潮流,而是一个实用的工具:聊天机器人、内容生成器、翻译器、代码助手——所有这些都可以亲手实现。
在本文中,我们不会空谈理论。我将展示如何仅用15分钟,使用现代Kotlin工具(Retrofit、OkHttp、Coroutines和Gson)将ChatGPT连接到你的项目。即使你是新手,只需跟着步骤操作——代码是经过验证且可运行的。
我们需要什么?工具和准备
要使用OpenAI API Kotlin,我们需要一套基本工具。请准备好:
- OpenAI API密钥——在platform.openai.com注册,在API keys部分创建密钥。请保密!
- 开发环境——IntelliJ IDEA(Community版足够)或Android Studio(如果开发移动应用)。
- Gradle或Maven——用于添加依赖项。
我们将使用Retrofit Kotlin作为HTTP客户端,Gson Kotlin处理JSON。为什么选择它们?Retrofit提供简洁、声明式的代码,而Gson能将API响应转换为data类,无需额外操作。
步骤1. 创建项目并添加依赖项
创建一个新的Gradle项目(Kotlin/JVM)。在build.gradle.kts文件中添加:
dependencies { implementation("com.squareup.retrofit2:retrofit:2.9.0") implementation("com.squareup.retrofit2:converter-gson:2.9.0") implementation("com.squareup.okhttp3:okhttp:4.12.0") implementation("com.squareup.okhttp3:logging-interceptor:4.12.0") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0") implementation("com.google.code.gson:gson:2.10.1")}重要提示:logging-interceptor是可选的,但在调试时能救命——你可以看到实际发送到服务器和返回的内容。如果为Android开发,请额外添加implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.0")。
步骤2. 数据模型:ChatGPT如何“理解”你的请求
OpenAI API接收和返回严格的JSON格式。为了避免手动解析的麻烦,我们创建data类。这是任何Kotlin ChatGPT代码示例的基础。
// 发送给ChatGPT的请求模型data class ChatRequest( val model: String = "gpt-4o-mini", // 最便宜且最快的模型 val messages: List<Message>, val temperature: Double = 0.7)
data class Message( val role: String, // "user", "assistant", "system" val content: String)
// 来自ChatGPT的响应模型data class ChatResponse( val choices: List<Choice>?)
data class Choice( val message: Message?, val finish_reason: String?)注意:我们将model设置为gpt-4o-mini——这是OpenAI的现代模型,成本极低但效果出色。非常适合测试。
步骤3. Retrofit:配置与OpenAI通信的客户端
现在创建一个接口,描述我们唯一的端点。这是Retrofit Kotlin的经典方法。
interface OpenAiApi { @POST("v1/chat/completions") @Headers("Content-Type: application/json") suspend fun chatCompletion( @Header("Authorization") auth: String, @Body request: ChatRequest ): ChatResponse}关键点:suspend