前言
因?yàn)?GPT 流式請(qǐng)求的出色交互體驗(yàn),我們打算做一個(gè)開源基礎(chǔ)應(yīng)用,方便開發(fā)者快速集成項(xiàng)目。
本應(yīng)用集成 ChatGPT API,使用模型為 gpt-3.5-turbo,項(xiàng)目代碼為 Kotlin 語言開發(fā)的安卓應(yīng)用。
人機(jī)交互的趨勢已經(jīng)到來,本應(yīng)用框架也希望能幫助更多開發(fā)者快速集成 ChatGPT 體驗(yàn)到人機(jī)交互的樂趣!
正文
我們根據(jù)流式請(qǐng)求 Chat API 開源一個(gè)安卓項(xiàng)目,可方便開發(fā)者快速上手使用 開源地址
直接上核心代碼,由 kotlin 編寫文章來源:http://www.zghlxwxcb.cn/news/detail-514660.html
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.JsonObject
import okhttp3.*
import org.yameida.asrassistant.config.Config
import org.yameida.asrassistant.model.Message
import org.yameida.asrassistant.model.StreamAiAnswer
import java.io.BufferedReader
import java.io.IOException
import java.lang.Exception
object HttpUtil {
/**
* ChatGPT
*/
fun chat(send: String, callback: CallBack) {
val url = "https://api.openai.com/v1/chat/completions"
val apiKey = "Bearer ${Config.apiKey}"
val jsonObject = JsonObject()
jsonObject.addProperty("model", "gpt-3.5-turbo")
val body = RequestBody.create(MediaType.parse("application/json"), "{\n" +
" \"model\": \"gpt-3.5-turbo\",\n" +
" \"stream\": true,\n" +
" \"messages\": [{\"role\": \"user\", \"content\": \"$send!\"}]\n" +
"}")
val request: Request = Request.Builder().url(url).method("POST", body)
.addHeader("Authorization", apiKey)
.build()
OkHttpUtil.okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
ToastUtils.showLong("網(wǎng)絡(luò)請(qǐng)求出錯(cuò) 請(qǐng)檢查網(wǎng)絡(luò)")
}
override fun onResponse(call: Call, response: Response) {
try {
val responseBody = response.body()
if (responseBody != null) {
val bufferedReader = BufferedReader(responseBody.charStream())
var line = bufferedReader.readLine()
var index = 0
val sb = StringBuilder()
while (line != null) {
val msg = convert(line, "1", index++)
if (msg != null) {
sb.append(msg.content)
callback.onCallBack(sb.toString(), false)
}
line = bufferedReader.readLine()
}
callback.onCallBack(sb.toString(), true)
}
} catch (e: Exception) {
e.printStackTrace()
ToastUtils.showLong("網(wǎng)絡(luò)請(qǐng)求出錯(cuò) 請(qǐng)檢查配置")
}
}
})
}
fun convert(answer: String, questionId: String, index: Int): Message? {
val msg = Message()
msg.content = ""
msg.messageType = "normal"
msg.id = questionId
if ("data: [DONE]" != answer) {
val beanStr = answer.replaceFirst("data: ", "", false)
val aiAnswer = GsonUtils.fromJson(beanStr, StreamAiAnswer::class.java) ?: return null
val choices = aiAnswer.choices
if (choices.isEmpty()) {
return null
}
val stringBuffer = StringBuffer()
for (choice in choices) {
if (choice.finish_reason != "stop") {
if (choice.delta.content != null) {
stringBuffer.append(choice.delta.content)
} else {
return null
}
}
}
msg.content = stringBuffer.toString()
if (index == 0) {
if (msg.content == "\n\n") {
LogUtils.e("發(fā)現(xiàn)開頭有兩次換行,移除兩次換行")
return null
}
}
} else {
msg.type = "stop"
}
msg.index = index
return msg
}
interface CallBack {
fun onCallBack(result: String, isLast: Boolean)
}
}
// 使用方法
HttpUtil.chat(result, object : HttpUtil.CallBack {
override fun onCallBack(result: String, isLast: Boolean) {
runOnUiThread {
//更新數(shù)據(jù)或UI
updateData()
}
}
})
總結(jié)
至此,你應(yīng)該已經(jīng)完成了Chat機(jī)器人智能問答對(duì)接,一個(gè)智能QA機(jī)器人就實(shí)現(xiàn)了,后續(xù)我會(huì)繼續(xù)進(jìn)行AI能力的擴(kuò)展,如多模態(tài)等。喜歡本文可以給開源項(xiàng)目一個(gè) star~有問題可以留言或私信我。文章來源地址http://www.zghlxwxcb.cn/news/detail-514660.html
到了這里,關(guān)于使用OkHttp流式請(qǐng)求OpenAI API(GPT API)接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!