Impress Your Friends by Making a ChatGPT ChatBot In SwiftUI for iPhones

Introduction

In this article, we are going to create a simple conversational ChatBot app in SwiftUI using ChatGPT.  We will use OpenAI API to create this ChatBot app, this app will take input from the user in a prompt and will show answers or solutions for that text. This article is going to really very interesting to learn and know about ChatGPT, and how it works. We will create our UI in SwiftUI as it takes less code for making our UI easy to understand.

What is ChatGPT?

ChatGPT : ChatBot in SwiftUI

ChatGPT is one of the most trending topics now. It also breaks record with over one million people signed up in just five days no longer will we be googling answers to problems. ChatGPT gives breakdowns of them in fine detail with explanations of how it exactly works, this will make people question just how relevant Google will be in the coming future. Do you want to know the limitations of typescript, ChatGPT has you covered but what exactly is ChatGPT,

What makes it so powerful these are the things we wanted to find out. ChatGPT builds by the same people that are behind OpenAI which are now shaping some really interesting technologies. They have been building powerful engines like Codex which is the engine behind GitHub copilot something that many of us are already using in our day-to-day coding. We might see the beginning of ChatGPT where people put in prompts and they get output from an AI-generated system another example is DALL.E 2 which is an image generator based on prompts that we entered. ChatGPT is therefore an AI to solve or answer a question or a prompt human-like manner. We can use ChatGPT as suppose we are working with a small application and getting an error that could not be figured out so we can copy that error and paste it into ChatGPT, it gives us an explanation of the error with solutions.

Can ChatGPT replace programmers?

There are many questions raised about ChatGPT one of them is Can ChatGPT replace programmers? On this want to say, just think about this what is ChatGPT? nowadays everyone sees ChatGPT as a human who can do everything, but in actuality, we see ChatGPT as just an AI Model. We have shown him a lot of data and whatever he generates according to the training we provided to him. It generates a solution or answers after learning a pattern.

ChatGPT doesn't have emotions it can only generate solutions according to the training, the solutions provided by it can also be wrong we will show him the wrong data. I really don't know why everyone sees ChatGPT as a replacement for programmers it's just an AI Model we trained him so we can also create a new ChatGPT.

Implementation of ChatGPT: ChatBot

ChatGPT : ChatBot in SwiftUI

We have discussed what is ChatGPT. Here we will create our own ChatGPT ChatBot app in SwiftUI using OpenAI. So open your Xcode and give the project name here I have given ChatGPT and select interface SwiftUI as we will create our app in SwiftUI. Hit the next button and yes we are ready to write our code.

ChatGPT : ChatBot in SwiftUI

Now the first thing we have to do is to add a package OpenAI Swift to our project. So for adding a new package we have to click on the file on the navigation bar and then add the package.

ChatGPT : ChatBot in SwiftUI

Here we have to add the OpenAISwift package to our project, so just simply search OpanAI on GitHub and copy that URL link. After that paste in the search area that links as I have done. Now we can see the OpenAISwift package on our left side and then simply hit Add Package button, here we have added the OpenAI package to our project. To ensure everything is working properly build your project if there no error occurred congrats we have done it right.

import Foundation
import OpenAISwift
public class ViewModel: ObservableObject {
    init() {}
    private
    var client: OpenAISwift ? func setup() {
        client = OpenAISwift(authToken: "Auth- Key")
    }
    func send(text: String, completion: @escaping(String) - > Void) {
        client?.sendCompletion(with: text, maxTokens: 500, completionHandler: {
            result in
            switch result {
                case.success(let model): let output = model.choices.first?.text ?? ""
                completion(output)
                case.failure(_): break
            }
        })
    }
}

Now we are going to create a ViewModel for our project where we will write our logic to fetch the response from OpenAI API. Here I have created a class ViewModel of the type ObservableObject. We have initialized our class by writing the init() function. We have a function named setup() where we will create our OpenAISwift client.

We also have a send function which we will use to send our request to OpenAI.

We have also completion in our send function which will return a string.

We have set up our ViewModel. Now we will go to the OpenAI website to generate an API key.

ChatGPT : ChatBot in SwiftUI

Here I already have some API keys so for generating a new API key just click on the "Create new secret key" button and copy that key. Now we will import the OpenAISwift package by just writing import.

Here we will create a private instance name client which is OpenAISwift type. In the setup() function we will instantiate our client, so just write OpenAISwift with authToken and paste that API key we copied earlier. Here I have written Auth-Key instead of my API key. In send() function we will actually make the call so call the method SendCompletion () we will pass here "text" which is a parameter of send() function.

The second argument is maxToken which is used for how much response we want to get from API. The default maxToken is 16 we will give it 500. In the completion handler, we have a result. Here we will write a switch case on the result in the success case we have an output which is the text we want in the response array and in the failure case we will do nothing so just call break here.

import SwiftUI
struct ContentView: View {
    @ObservedObject
    var viewmodel = ViewModel()
    @State
    var text = ""
    @State
    var models = [String]()
    var body: some View {
        NavigationView {
            VStack(alignment: .leading) {
                ForEach(models, id: \.self) {
                    string in HStack {
                        Text(string)
                    }
                }
                Spacer()
                HStack {
                    Image("man").resizable().frame(width: 40, height: 40)
                    TextField("Enter your text", text: $text).frame(height: 40).border(.gray).cornerRadius(2)
                    Button("Send") {
                        send()
                    }.frame(width: 100, height: 40).background(.blue).foregroundColor(.white).font(.title3).cornerRadius(12)
                }
            }.padding(.horizontal).navigationTitle("OpenAI ChatBot")
        }.onAppear {
            viewmodel.setup()
        }
    }
    func send() {
        guard!text.trimmingCharacters(in: .whitespaces).isEmpty
        else {
            return
        }
        models.append("Me : \(text)")
        viewmodel.send(text: text) {
            result in print(result)
            self.models.append("chatGpt :" + result)
        }
        self.text = ""
    }
}
struct ContentView_Previews: PreviewProvider {
    static
    var previews: some View {
        ContentView()
    }
}

Now in the ContentView file, the first thing we will do is we will create ObservedObject which will be ViewModel. We also going to have textField so we have to create a State variable "text". We are also going to have a collection of models that we will append to a list as we get in responses from the API.

In the body, we will create our UI so first of all in Vstack we will get responses and our questions in this list. Now we added a spacer() here to create spaces between components in VStack. We have taken here HStack for creating our prompt text field. We have also added a Button to send our text to API. I have added button names as sent here.

We have a function OnAppear() here we have added here to write some code that will execute when this page view will appear. In this function, we have called the setup function from ViewModel to set up our OpenAI client. Every time when a user will click on send button we are calling a send function.

In this function, we will get a text that the user will input in the text field. Every time when a user will click send button we will get a text from textField append in the model as the user asks the question from OpenAI and will call send() function in ViewModel to send a request for this text, after returning the result we will append that result also into models. Here we have our ChatGPT ChatBot app ready.

ChatGPT ChatBot App

ChatGPT : ChatBot in SwiftUI

Conclusion

In this article, we have learned about how we can create our own ChatGPT using OpenAI. We can ask anything from this ChatBot. OpenAI is a really very interesting topic to learn about, we have created here a simple ChatBot but there are also many things to do OpenAI provides us API for generating images API to generate images for the text we will enter, text completion API, Fine-tuning API, Code completions API, etc. So please learn about that APIs and create an app using those and write an interesting article about those topics.

Hope you have enjoyed this interesting article.