Android Studio版 ChatGPTと話そう!(その1)

OpenAIのGPT-4を使って新しいAndroidアプリをAndroid Studio FlamingoとKotlinを使って作ります。Android StudioはWindowsでもMac, Linux, ChromeOSでも動きますので手元のパソコンが使えます。
ここで作るのはChatGPTと話そう!(その1)としてChatGPTに入力したプロンプトを送って返答を画面に表示するアプリです。いろいろ試してみましたが、GPT-4はAndroidアプリはうまく作れなかったので、もしやと思い、英語でプロンプトを入れたら動くコードをくれました。日本語のKotlinのコードはあまり入っていないようですね。

 

 

GPT-4とのやり取り

プロンプト

Please tell me how to create an android app with the following features with Android Studio and kotlin according to step 1 to step 3. Please be detailed so that even a beginner can understand.

Features:
1. send the entered text to ChatGPT. The model is gpt-3.5-turbo
2. display the returned reply on the screen

Step 1: Explanation of detailed functions
Step 2: Outline of how to make it
Step 3: Explain in detail so that even a newcomer can understand. the communication part with ChatGPT should

返答

This is a simple guide to create an Android application in Kotlin using Android Studio that can communicate with the ChatGPT-3.5-turbo API.

This guide assumes you have Android Studio installed on your machine and basic knowledge of Kotlin. If you need to install Android Studio, please refer to the official Android Studio website.

Here are the steps you need to follow to create the Android Application:

Step 1: Explanation of Detailed Functions

  1. User Input: We need to create an interface where users can input text. For this, we will use an EditText view.
  2. Send Request: When users have entered the text, we need to send it to the OpenAI server via a POST request. This can be done using a library like Retrofit or OkHttp.
  3. Receive Response: Once we have sent the request, we will receive a response from the server. This response needs to be handled and displayed to the user.
  4. Display Response: We will display the response in a TextView.

Step 2: Outline of How to Make It

  1. Create a New Project in Android Studio: Start a new Android Studio project with an Empty Activity.
  2. Layout Design: Design the layout of your application using the XML file in the 'res/layout’ directory. You should have an EditText for input and a Button to send the request, and a TextView to display the response.
  3. Networking: Add Retrofit or OkHttp to your project to handle HTTP requests.
  4. API Key: Register on the OpenAI website and get an API Key. This key will be used to authorize your requests to the OpenAI server.
  5. Request and Response: Create a function to handle the request and response. This function will take the text from the EditText, send it as a request to the OpenAI server, receive the response, and display it in the TextView.

Step 3: Detailed Explanation for Beginners

  1. Project Setup: Open Android Studio, click on “New Project", select “Empty Activity", and click “Next". Give your application a name, select “Kotlin" as the language, and finish.
  2. Layout Design: Open the 'activity_main.xml’ file from the 'res/layout’ directory. Remove any existing code and paste the following:

This will create an EditText for input, a Button for sending the request, and a TextView to display the response.

  1. Adding Dependencies: Now we need to add Retrofit and Gson dependencies to our project. Open your 'build.gradle’ (Module) file and add these lines inside dependencies:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

Click “Sync Now" at the top right corner of the screen to download and integrate these libraries into your project.

  1. API Key: Go to the OpenAI website, create an account, and get your API Key. We will use this key to authorize our requests.
  2. Setting up Retrofit: Now, we will setup Retrofit to handle HTTP requests.
    Creating a Data Class: First, we need to create a data class that represents the request payload and the response payload. The request payload for GPT-3.5-turbo is a JSON that looks like this:

So, our data classes will look like this:

延々と説明が続きます。

プロンプト

Give whole MainActivity.kt source

返答

Here’s a complete example of a MainActivity.kt file based on the instructions above:

import android.os.Bundle
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Headers
import retrofit2.http.POST
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

data class Message(val role: String, val content: String)
data class OpenAIRequest(val messages: List)
data class OpenAIResponse(val choices: List)
data class Choice(val message: Message)

interface OpenAIApi {
    @Headers("Content-Type: application/json", "Authorization: Bearer YOUR_API_KEY")
    @POST("v1/engines/davinci-codex/completions")
    fun getCompletion(@Body body: OpenAIRequest): Call
}

object RetrofitInstance {
    private val retrofit by lazy {
        Retrofit.Builder()
            .baseUrl("https://api.openai.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    val api: OpenAIApi by lazy {
        retrofit.create(OpenAIApi::class.java)
    }
}

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val editText = findViewById<edittext>(R.id.editText)
        val button = findViewById<button>(R.id.button)
        val textView = findViewById<textview>(R.id.textView)

        button.setOnClickListener {
            val message = Message("user", editText.text.toString())
            val request = OpenAIRequest(listOf(Message("system", "You are a helpful assistant."), message))

            RetrofitInstance.api.getCompletion(request).enqueue(object: Callback {
                override fun onResponse(call: Call, response: Response) {
                    if (response.isSuccessful) {
                        val reply = response.body()?.choices?.get(0)?.message?.content
                        textView.text = reply
                    } else {
                        textView.text = "Error: ${response.code()}"
                    }
                }

                override fun onFailure(call: Call, t: Throwable) {
                    textView.text = "Failure: ${t.message}"
                }
            })
        }
    }
}

Please note that you need to replace “YOUR_API_KEY" with your actual API key from OpenAI. Also, make sure to handle error and edge cases properly in a real-world app. This example is simple and intended for learning purposes. For production-grade applications, consider handling potential errors more thoroughly and take steps to secure the API key.

この状態で実行するとプログラムがクラッシュしました。聞いてみます。

プロンプト

When I click Send button, it crashed

返答

If your app is crashing when you click the “Send" button, it could be due to a number of reasons. Here are a few potential issues and solutions:

  1. Network Permission: Android requires explicit permission for network access in the manifest file. Ensure you’ve added the following line in your AndroidManifest.xml file within the <manifest> tag:

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

これでクラッシュしなくなりました。後はAPI関係の微調整をGPT-4にしてもらいました。

最終的なソースコードは次のとおりです。

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

    <EditText

android:id="@+id/editText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="テキストを入力してください"/>

    <Button

android:id="@+id/button"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="送信"

android:layout_below="@+id/editText"/>

    <TextView

android:id="@+id/textView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="返答はここに表示されます"

android:layout_below="@+id/button"/>

</RelativeLayout>
MainActivity.kt
package com.example.text2chatgpten

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.Headers
import retrofit2.http.POST

import java.util.concurrent.TimeUnit


data class Message(val role: String, val content: String)
data class OpenAIRequest(val model: String, val messages: List<Message>)
data class OpenAIResponse(val choices: List<Choice>)
data class Choice(val message: Message)

interface OpenAIApi {
    @Headers("Content-Type: application/json", "Authorization: Bearer APIKEY")
    @POST("v1/chat/completions")
    fun getCompletion(@Body body: OpenAIRequest): Call<OpenAIResponse>
}

object RetrofitInstance {
    var okHttpClient = OkHttpClient.Builder()
        .connectTimeout(1, TimeUnit.MINUTES)
        .readTimeout(1, TimeUnit.MINUTES)
        .writeTimeout(1, TimeUnit.MINUTES)
        .build()
    private val retrofit by lazy {

Retrofit.Builder()
            .baseUrl("https://api.openai.com/")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }


val api: OpenAIApi by lazy {

retrofit.create(OpenAIApi::class.java)
    }
}

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val editText = findViewById<EditText>(R.id.editText)
        val button = findViewById<Button>(R.id.button)
        val textView = findViewById<TextView>(R.id.textView)

        button.setOnClickListener {

val message = Message("user", editText.text.toString())
            val request = OpenAIRequest("gpt-3.5-turbo", listOf(Message("system", "You are a helpful assistant."), message))

            RetrofitInstance.api.getCompletion(request).enqueue(object: Callback<OpenAIResponse> {
                override fun onResponse(call: Call<OpenAIResponse>, response: Response<OpenAIResponse>) {
                    if (response.isSuccessful) {
                        val reply = response.body()?.choices?.get(0)?.message?.content

textView.text = reply

} else {
                        textView.text = "Error: ${response.code()}"

}
                }

                override fun onFailure(call: Call<OpenAIResponse>, t: Throwable) {
                    textView.text = "Failure: ${t.message}"

}
            })
        }

}
}

Android StudioでAndroidアプリを作る

OpenAI APIキーの取得

いろいろなところで説明されているので参考にしてAPIキーを取得してください。

プロジェクトの作成

Android Studioを起動してTalk2ChatGPTという名前のプロジェクトを作ります。Empty Views AcitivityでAPIは33にします。

XMLとKotlinコードの貼り付け

GPT-4が作ってくれたactivity_main.xmlとMainActivity.ktコードを貼り付けます。MainActivity.ktの中のAPIKEYをあなたのAPIキーと置き換えてください。

実行

実行結果はこの通り。下の画像をクリックしてYouTubeデモビデオを見てください。

 

 

 

Androidアプリ,ChatGPT