ChatGPT是当今著名的人工智能工具之一,类似于聊天机器人。这个聊天机器人回答所有发送给它的查询。在本文中,我们将通过集成OpenAI API(ChatGPT)来构建一个简单的类似ChatGPT的android应用程序,我们可以在其中提出任何问题并得到适当的答案

我已经创建了一个示例应用程序,并将看看它的输出,然后我们将进一步在android studio中创建一个新项目。

一步一步的实现

步骤1:在Android Studio中创建一个新项目

要在Android Studio中创建一个新项目,请参考How to Create/Start a New Project in Android Studio。注意,选择Kotlin作为编程语言。

步骤2:添加以下依赖项build.gradle 文件

下面是Volley的依赖关系,我们将使用它从API获取数据。要添加此依赖项,app > Gradle Scripts > build.gradle(app),并在依赖项部分添加以下依赖项。我们已经使用了Picasso依赖项来从URL加载图像

// below line is used for volley library

implementation ‘com.android.volley:volley:1.2.0’

添加这个依赖后,同步你的项目,现在转移到AndroidManifest.xml部分。

步骤3:在AndroidManifest.xml文件中添加网络访问权限

app > AndroidManifest.xml,并将以下代码添加到其中

<!--permissions for INTERNET-->
<uses-permission android:name="android.permission.INTERNET"/>

步骤4:使用activity_main.xml文件

app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.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的记名令牌。

导航到下面的 URL,只需注册您的电子邮件和密码。在此屏幕上单击Create a new secret key以生成新密钥。一旦你的密钥生成,我们必须使用它作为一个令牌,使我们的API密钥。

步骤6:使用MainActivity。kt文件。

导航到app > java > your app’s package name > MainActivity.kt 文件,并添加下面的代码。代码中添加了注释以详细了解它。

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)
// initializing variables on below line.
responseTV = findViewById(R.id.idTVResponse)
questionTV = findViewById(R.id.idTVQuestion)
queryEdt = findViewById(R.id.idEdtQuery)
// adding editor action listener for edit text on below line.
queryEdt.setOnEditorActionListener(OnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEND) {
// setting response tv on below line.
responseTV.text = "Please wait.."
// validating text
if (queryEdt.text.toString().length > 0) {
// calling get response to get the response.
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) {
// setting text on for question on below line.
questionTV.text = query
queryEdt.setText("")
// creating a queue for request queue.
val queue: RequestQueue = Volley.newRequestQueue(applicationContext)
// creating a json object on below line.
val jsonObject: JSONObject? = JSONObject()
// adding params to json object.
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)
// on below line making json object request.
val postRequest: JsonObjectRequest =
// on below line making json object request.
object : JsonObjectRequest(Method.POST, url, jsonObject,
Response.Listener { response ->
// on below line getting response message and setting it to text view.
val responseMsg: String =
response.getJSONArray("choices").getJSONObject(0).getString("text")
responseTV.text = responseMsg
},
// adding on error listener
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()
// adding headers on below line.
params["Content-Type"] = "application/json"
params["Authorization"] =
"Bearer Enter your token here"
return params;
}
}
// on below line adding retry policy for our request.
postRequest.setRetryPolicy(object : RetryPolicy {
override fun getCurrentTimeout(): Int {
return 50000
}
override fun getCurrentRetryCount(): Int {
return 50000
}
@Throws(VolleyError::class)
override fun retry(error: VolleyError) {
}
})
// on below line adding our request to queue.
queue.add(postRequest)
}
}

输出参考

https://media.geeksforgeeks.org/wp-content/uploads/20230118003207/Screenrecorder-2023-01-18-00-28-57-186.mp4?_=1

参考文章:https://www.geeksforgeeks.org/how-to-build-a-chatgpt-like-app-in-android-using-openai-api/

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。