新疆烏魯木齊醫(yī)院網(wǎng)站建設(shè)東莞網(wǎng)絡(luò)推廣營(yíng)銷
大家好,我是易安!
Chat GPT 是當(dāng)今著名的人工智能工具,就像聊天機(jī)器人一樣。Chat GPT會(huì)回答發(fā)送給它的所有查詢。今天,我將通過(guò)集成 OpenAI API (ChatGPT)構(gòu)建一個(gè)簡(jiǎn)單的類似 ChatGPT 的 android 應(yīng)用程序,我們可以在其中提出任何問(wèn)題并獲得答案。

詳細(xì)步驟
第 1 步:在 Android Studio 中創(chuàng)建一個(gè)新項(xiàng)目
要在 Android Studio 中創(chuàng)建新項(xiàng)目,以 Kotlin 作為編程語(yǔ)言為例。
第 2 步:在 build.gradle 文件中添加以下依賴項(xiàng)
下面是 Volley 的依賴項(xiàng),我們將使用它從 API 獲取數(shù)據(jù)。要添加此依賴項(xiàng),請(qǐng)導(dǎo)航至 app > Gradle Scripts > build.gradle(app) 并在 dependencies 部分添加以下依賴項(xiàng)。我們使用 Picasso 依賴項(xiàng)從 URL 加載圖像。
//?下一行用于?volley?庫(kù)
實(shí)現(xiàn)?'com.android.volley:volley:1.2.0'
添加此依賴項(xiàng)后,同步您的項(xiàng)目,然后轉(zhuǎn)到 AndroidManifest.xml 部分。
第三步:在AndroidManifest.xml文件中添加上網(wǎng)權(quán)限
導(dǎo)航到應(yīng)用 > AndroidManifest.xml 并向其中添加以下代碼。
-
XML
<!--permissions?for?INTERNET-->
<uses-permission?android:name="android.permission.INTERNET"/>
第 4 步:使用 activity_main.xml 文件
導(dǎo)航到 app > res > layout > activity_main.xml 并將以下代碼添加到該文件。下面是 activity_main.xml 文件的代碼。
-
XML
<?xml?version="1.0"?encoding="utf-8"?>
<RelativeLayout?xmlns:android="http://schemas.android.com/apk/res/android"
?xmlns:app="http://schemas.android.com/apk/res-auto"
?xmlns:tools="http://schemas.android.com/tools"
?android:layout_width="match_parent"
?android:layout_height="match_parent"
?android:background="@color/back_color"
?tools:context=".MainActivity">
?<ScrollView
??android:layout_width="match_parent"
??android:layout_height="match_parent"
??android:layout_above="@id/idTILQuery"
??android:layout_alignParentTop="true"
??android:layout_margin="5dp"
??android:padding="5dp">
??<LinearLayout
???android:layout_width="match_parent"
???android:layout_height="match_parent"
???android:orientation="vertical">
???<!--?text?view?for?displaying?question-->
???<TextView
????android:id="@+id/idTVQuestion"
????android:layout_width="match_parent"
????android:layout_height="match_parent"
????android:layout_marginTop="30dp"
????android:padding="4dp"
????android:text="Question"
????android:textColor="@color/white"
????android:textSize="17sp"?/>
???<!--?text?view?for?displaying?response-->
???<TextView
????android:id="@+id/idTVResponse"
????android:layout_width="match_parent"
????android:layout_height="match_parent"
????android:layout_marginTop="5dp"
????android:padding="4dp"
????android:text="Response"
????android:textColor="@color/white"
????android:textSize="15sp"?/>
??</LinearLayout>
?</ScrollView>
?<!--?text?field?for?asking?question-->
?<com.google.android.material.textfield.TextInputLayout
??android:id="@+id/idTILQuery"
??style="@style/TextInputLayoutStyle"
??android:layout_width="match_parent"
??android:layout_height="wrap_content"
??android:layout_alignParentBottom="true"
??android:layout_margin="5dp"
??android:hint="Enter?your?query"
??android:padding="5dp"
??android:textColorHint="@color/white"
??app:hintTextColor="@color/white">
??<com.google.android.material.textfield.TextInputEditText
???android:id="@+id/idEdtQuery"
???android:layout_width="match_parent"
???android:layout_height="match_parent"
???android:background="@color/edt_back_color"
???android:drawableEnd="@drawable/ic_send"
???android:drawableTint="@color/white"
???android:ems="10"
???android:imeOptions="actionSend"
???android:importantForAutofill="no"
???android:inputType="textEmailAddress"
???android:textColor="@color/white"
???android:textColorHint="@color/white"
???android:textSize="14sp"?/>
?</com.google.android.material.textfield.TextInputLayout>
</RelativeLayout>
第 5 步:生成使用 API 的不記名令牌。
導(dǎo)航到以下URL (openai獲取你的api key),只需使用您的電子郵件和密碼注冊(cè)即可。在此屏幕上單擊創(chuàng)建新密鑰以生成新密鑰。生成您的密鑰后,我們必須將其用作制作 API 密鑰的令牌。
第 6 步:使用 MainActivity.kt 文件。
導(dǎo)航到 app > java > 你的應(yīng)用程序包名稱 > MainActivity.kt 文件并向其中添加以下代碼。
這里選擇的模型text-davinci-003,當(dāng)然你可以選擇其他3.5的模型
-
Kotlin
import?android.content.Context
import?android.os.Bundle
import?android.util.Log
import?android.view.inputmethod.EditorInfo
import?android.widget.TextView
import?android.widget.TextView.OnEditorActionListener
import?android.widget.Toast
import?androidx.appcompat.app.AppCompatActivity
import?com.android.volley.RequestQueue
import?com.android.volley.Response
import?com.android.volley.RetryPolicy
import?com.android.volley.VolleyError
import?com.android.volley.toolbox.JsonObjectRequest
import?com.android.volley.toolbox.Volley
import?com.google.android.material.textfield.TextInputEditText
import?org.json.JSONObject
class?MainActivity?:?AppCompatActivity()?{
?//?creating?variables?on?below?line.
?lateinit?var?responseTV:?TextView
?lateinit?var?questionTV:?TextView
?lateinit?var?queryEdt:?TextInputEditText
?var?url?=?"https://api.openai.com/v1/completions"
?override?fun?onCreate(savedInstanceState:?Bundle?)?{
??super.onCreate(savedInstanceState)
??setContentView(R.layout.activity_main)
??
??responseTV?=?findViewById(R.id.idTVResponse)
??questionTV?=?findViewById(R.id.idTVQuestion)
??queryEdt?=?findViewById(R.id.idEdtQuery)
??
??queryEdt.setOnEditorActionListener(OnEditorActionListener?{?v,?actionId,?event?->
???if?(actionId?==?EditorInfo.IME_ACTION_SEND)?{
????
????responseTV.text?=?"Please?wait.."
????
????if?(queryEdt.text.toString().length?>?0)?{
?????
?????getResponse(queryEdt.text.toString())
????}?else?{
?????Toast.makeText(this,?"Please?enter?your?query..",?Toast.LENGTH_SHORT).show()
????}
????return@OnEditorActionListener?true
???}
???false
??})
?}
?private?fun?getResponse(query:?String)?{
??
??questionTV.text?=?query
??queryEdt.setText("")
??
??val?queue:?RequestQueue?=?Volley.newRequestQueue(applicationContext)
??
??val?jsonObject:?JSONObject??=?JSONObject()
??
??jsonObject?.put("model",?"text-davinci-003")
??jsonObject?.put("prompt",?query)
??jsonObject?.put("temperature",?0)
??jsonObject?.put("max_tokens",?100)
??jsonObject?.put("top_p",?1)
??jsonObject?.put("frequency_penalty",?0.0)
??jsonObject?.put("presence_penalty",?0.0)
??
??val?postRequest:?JsonObjectRequest?=
???
???object?:?JsonObjectRequest(Method.POST,?url,?jsonObject,
????Response.Listener?{?response?->
?????
?????val?responseMsg:?String?=
??????response.getJSONArray("choices").getJSONObject(0).getString("text")
?????responseTV.text?=?responseMsg
????},
????
????Response.ErrorListener?{?error?->
?????Log.e("TAGAPI",?"Error?is?:?"?+?error.message?+?"\n"?+?error)
????})?{
????override?fun?getHeaders():?kotlin.collections.MutableMap<kotlin.String,?kotlin.String>?{
?????val?params:?MutableMap<String,?String>?=?HashMap()
????
?????params["Content-Type"]?=?"application/json"
?????params["Authorization"]?=
??????"Bearer?Enter?your?token?here"
?????return?params;
????}
???}
??
??postRequest.setRetryPolicy(object?:?RetryPolicy?{
???override?fun?getCurrentTimeout():?Int?{
????return?50000
???}
???override?fun?getCurrentRetryCount():?Int?{
????return?50000
???}
???@Throws(VolleyError::class)
???override?fun?retry(error:?VolleyError)?{
???}
??})
??
??queue.add(postRequest)
?}
}
最終運(yùn)行結(jié)果:

多年沒(méi)開(kāi)發(fā)安卓的我,也能在很短的時(shí)間不費(fèi)吹飛之力搭建出來(lái),你也趕緊去試試吧!之后我還會(huì)出一些更加詳細(xì)的搭建教程,感謝閱讀!
本文由 mdnice 多平臺(tái)發(fā)布