安卓ChatGPT开发入门:从零搭建智能对话应用

14次阅读
没有评论

共计 3999 个字符,预计需要花费 10 分钟才能阅读完成。

image.webp

最近在安卓应用中集成 AI 对话功能的需求越来越多,ChatGPT 的 API 提供了很好的解决方案。本文将手把手教你如何在安卓应用中集成 ChatGPT,实现智能对话功能。我们使用的是 Kotlin + Retrofit + Coroutines 这套组合方案,这也是目前安卓开发中最主流的技术栈之一。

安卓 ChatGPT 开发入门:从零搭建智能对话应用

前置准备:获取 API Key

在开始之前,你需要先获取 OpenAI 的 API Key:

  1. 登录 OpenAI 官网 (https://platform.openai.com/)
  2. 点击右上角头像,选择 ”View API Keys”
  3. 点击 ”Create new secret key” 生成 API 密钥
  4. 记下这个密钥,我们后面会用到

建议在 OpenAI 后台设置好使用配额,避免意外产生高额费用。对于开发测试阶段,可以将使用限制设置得低一些。

项目配置

首先,在项目的 build.gradle 文件中添加必要的依赖:

dependencies {
    // Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

    // Coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'

    // OkHttp
    implementation 'com.squareup.okhttp3:okhttp:4.10.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0'
}

网络层封装

接下来我们定义 Retrofit 接口和服务类。创建一个 ChatService.kt 文件:

interface ChatApiService {@Headers("Content-Type: application/json", "Authorization: Bearer YOUR_API_KEY")
    @POST("v1/chat/completions")
    suspend fun getChatResponse(@Body request: ChatRequest): ChatResponse

    @Headers("Content-Type: application/json", "Authorization: Bearer YOUR_API_KEY")
    @POST("v1/chat/completions")
    fun getChatResponseStream(@Body request: ChatRequest): Response<ResponseBody>
}

然后创建对应的数据模型类:

data class ChatRequest(
    val model: String = "gpt-3.5-turbo",
    val messages: List<Message>,
    val temperature: Float = 0.7f,
    val stream: Boolean = false
)

data class Message(
    val role: String, // "system", "user" or "assistant"
    val content: String
)

data class ChatResponse(
    val id: String,
    val choices: List<Choice>
)

data class Choice(
    val message: Message,
    val index: Int,
    val finish_reason: String
)

协程实践:流式响应处理

ChatGPT API 支持流式响应,这对于移动端应用来说非常重要,可以显著提升用户体验。下面是如何实现流式响应的代码:

class ChatService {
    private val apiService: ChatApiService by lazy {Retrofit.Builder()
            .baseUrl("https://api.openai.com/")
            .client(OkHttpClient.Builder().addInterceptor(HttpLoggingInterceptor().apply {level = HttpLoggingInterceptor.Level.BASIC}).build())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ChatApiService::class.java)
    }

    fun getStreamResponse(messages: List<Message>): Flow<String> = flow {
        val request = ChatRequest(
            messages = messages,
            stream = true
        )

        val response = apiService.getChatResponseStream(request)

        if (response.isSuccessful) {response.body()?.let { body ->
                val reader = body.source().buffer()
                while (true) {val line = reader.readUtf8Line() ?: break
                    if (line.startsWith("data:") && line != "data: [DONE]") {val json = line.substring(6)
                        try {val chatResponse = Gson().fromJson(json, ChatResponse::class.java)
                            chatResponse.choices.firstOrNull()?.message?.content?.let { content ->
                                emit(content)
                            }
                        } catch (e: Exception) {// 处理 JSON 解析错误}
                    }
                }
            }
        } else {throw IOException("API 请求失败: ${response.code()}")
        }
    }.flowOn(Dispatchers.IO)
}

ViewModel 实现

在 ViewModel 中管理状态和数据处理:

class ChatViewModel : ViewModel() {private val chatService = ChatService()

    private val _messages = MutableStateFlow<List<Message>>(emptyList())
    val messages: StateFlow<List<Message>> = _messages

    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading

    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error

    fun sendMessage(text: String) {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null

                // 添加用户消息
                val userMessage = Message("user", text)
                _messages.value = _messages.value + userMessage

                // 获取 AI 回复
                val assistantMessage = Message("assistant", "")
                _messages.value = _messages.value + assistantMessage

                val updatedMessages = _messages.value.toList()

                chatService.getStreamResponse(updatedMessages.dropLast(1))
                    .collect { chunk ->
                        _messages.value = updatedMessages.dropLast(1) + 
                            Message("assistant", updatedMessages.last().content + chunk)
                    }
            } catch (e: Exception) {_error.value = e.message ?: "发生未知错误"} finally {_isLoading.value = false}
        }
    }
}

性能优化与安全建议

  1. 缓存策略 :
  2. 可以添加简单的内存缓存,避免重复请求相同内容
  3. 对于常见问题,可以本地缓存答案

  4. 网络状态管理 :

  5. 检测网络连接状态,离线时显示适当提示
  6. 实现自动重试机制,处理短暂网络中断

  7. API 密钥安全 :

  8. 不要将 API 密钥硬编码在代码中
  9. 考虑使用 Android Keystore 存储密钥
  10. 或者通过后端服务转发请求,避免客户端直接使用 API 密钥

常见问题解决方案

  1. 处理 429 速率限制错误 :
  2. 实现指数退避重试机制
  3. 在 UI 上显示友好提示,建议用户稍后再试

  4. 安卓主线程限制 :

  5. 确保所有网络请求都在 IO 线程执行
  6. 使用协程的 flowOn 操作符指定调度器

  7. 长文本对话优化 :

  8. 监控 token 使用量,避免超过模型限制
  9. 实现对话历史摘要功能,减少 token 消耗
  10. 对于长文本,可以考虑先本地进行摘要处理

扩展功能建议

现在你已经实现了基础的 ChatGPT 集成,可以考虑添加更多增强功能:

  • 上下文记忆:保存对话历史,实现多轮对话
  • 语音交互:添加语音输入和输出功能
  • 个性化设置:允许用户调整 temperature 等参数
  • 主题定制:根据对话内容改变 UI 主题

希望这篇教程能帮助你顺利在安卓应用中集成 ChatGPT 功能。如果在实现过程中遇到任何问题,可以参考 OpenAI 的官方文档,或者在开发者社区寻求帮助。

正文完
 0
评论(没有评论)