【ChatGPT初体验与Android的集成使用】

ChatGPT初体验与Android的集成使用

前言

ChatGPT凭借着强大的AI功能火的一塌糊涂,由于其官网在国内不能访问,很多小伙伴不能很友好的体验及使用,现在就来分享一下其简单的集成使用,最后附上在Android端的集成代码。
(温馨提示:以下部分网址需要代理访问)

创建自己的API KEY

  1. 首先打开ChatGPT的官网,在此就不在赘述其注册及登录的过程,具体步骤可以参考这里
  2. 进入账号后,点击右上角自己的头像,选择View API keys选项
  3. 点击这个按钮进行key的创建(生成的key记得复制,之后不会再显示,保存好,后面会用到)点击按钮进行key的创建

Android端的集成

  1. 打开API文档,选择查看具体的集成步骤,官方提供了三种方式:curl、python、Node.js

  2. 这里我们需要将ChatGPT的chat功能进行集成,开始项目之前,我打算用kotlin + coroutines + retorfit2进行构建

  3. 在Android studio中新建项目,列出关键的依赖库:

    //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-core:1.6.4'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
    
  4. 根据官方的Chat部分用例代码来看,需要加上两个请求头:

    curl https://api.openai.com/v1/chat/completions 
      -H 'Content-Type: application/json' 
      -H 'Authorization: Bearer YOUR_API_KEY' 
      -d '{
      "model": "gpt-3.5-turbo",
      "messages": [{"role": "user", "content": "Hello!"}]
    }'
    
    
  5. 编写我们自己的请求接口,带上请求头:

    interface ApiService {
        @POST("chat/completions")
        fun getMessage(@Header("Content-Type") type:String,@Header("Authorization") authorization:String, @Body body:SendBodyData):Call<ModelData>
    }
    
  6. viewmodel中实现具体的请求:

    private val baseUrl = "https://api.openai.com/v1/chat/completions"
    private val key = "sk-Rix2aNkoTt0NuiJQBCc4T3BlbkFJMnAdYtxTn1TfpOQ4K"
    var responseData =  MutableStateFlow(ModelData())
    
    suspend fun getMsg(info:String){
        when (val result = ApiHelper.getMsg("application/json","Bearer $key", SendBodyData(listOf(SendMessage(info,"user")),"gpt-3.5-turbo"))) {
            is Result.Success -> {
                responseData.emit(result.data)
            }
            is Result.Error -> {
                val exception = result.exception
                // 处理错误响应
                println(exception)
            }
        }
    }
    
  7. 最后在Activity中展示:

    lifecycleScope.launch {
            dataViewModel.responseData.collect{
                mBinding.idTVResponse.text = it.choices?.get(0)?.message?.content
                mBinding.idTILQuery.setText("")
            }
        }
        
    lifecycleScope.launchWhenResumed {
     	dataViewModel.getMsg(mBinding.idTILQuery.text.toString())
    }
    
    

代码

以上只是贴出了主要代码,具体的工程代码见这里

总结

过程中的踩坑:

  1. 请求头中Authorization是Bearer类型,否则返回401错误
  2. 手机运行的时候记得开启代理,否则白折腾半天…
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>