Hi SwiftUI Lovers, today weāll build simple ChatGPT Application With Official OpenAI API
So letās get start!
First of all we need to go to OpenAI and get an api key
Click Personal in the upper right corner of the screen
Then click View API Keys row
Click create new secret key.
This is our secret api key (Donāt tell anyone š«¢)
Yes, we created our Api Key š„³
After that If you research more with the API a little more you can see Examples Section.
Scroll Down and click Chat
Click on it
As you can see here some info about api request. We will need this when we write our code, curl means client url
- H means: Headers
- D means: Data
Also you can see more examples in OpenAI.
These are just a few examples!
Now, letās create new Xcode Projeeecctttt!!!
Donāt forget SwiftUI š
Now, we need to create a new file for the url request.
I named Request Manager
import Foundation
import Combine
class ChatRequestManager: ObservableObject {
}
I created ChatRequestManager itās an ObservableObject
private var cancellables = Set<AnyCancellable>()
@Published var responseData: Data?
@Published var responseError: Error?
Added some properties:
- Cancellable
- Response Data (Our Data)
- Response Error
Now letās create our request func
func makeRequest(text: String) {
}
I putted text input in our function because weāll use this text in View
Now letās fill our function
func makeRequest(text: String) {
let apiKey = "Open_AI_Key"
let model = "text-davinci-003"
let prompt = text
let temperature = 0.9
let maxTokens = 150
let topP = 1
let frequencyPenalty = 0.0
let presencePenalty = 0.6
let stop = [" Human:", " AI:"]
let requestBody : [String : Any] = [
"model": model,
"prompt": prompt,
"temperature": temperature,
"max_tokens": maxTokens,
"top_p": topP,
"frequency_penalty": frequencyPenalty,
"presence_penalty": presencePenalty,
"stop": stop
]
let jsonData = try? JSONSerialization.data(withJSONObject: requestBody)
var request = URLRequest(url: URL(string: "https://api.openai.com/v1/completions")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.httpBody = jsonData
URLSession.shared
.dataTaskPublisher(for: request)
.map { $0.data }
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let err):
self.responseError = err
default:
break;
}
}, receiveValue: { data in
self.responseData = data
})
.store(in: &self.cancellables)
}
So, what did i do? š
- I created a few values, do they look familiar before? These are the values we need to make api request in curl
- After that some URLRequest operations
- You must put your api key in api key value
Thatās it for the request :)
Now, back to our View
@ObservedObject var apiRequestManager = ChatRequestManager()
@State private var inputText: String = ""
I created these values.
- First One Our RequestManager
- Second One Our Input Text (The input in request function)
Now letās code the UI!
struct ContentView: View {
@ObservedObject var apiRequestManager = ChatRequestManager()
@State private var inputText: String = ""
var body: some View {
VStack(spacing: 25) {
TextField("Ask...", text: $inputText)
.padding()
.overlay(RoundedRectangle(cornerRadius: 10.0).strokeBorder(Color.orange, style: StrokeStyle(lineWidth: 1.5)))
.padding()
Button(action: {
self.apiRequestManager.makeRequest(text: inputText)
}) {
Text("Ask MobGPT")
.frame(minWidth: 0, maxWidth: .infinity)
.font(.system(size: 18))
.fontWeight(.bold)
.padding()
.foregroundColor(.white)
.overlay(
RoundedRectangle(cornerRadius: 20)
.stroke(Color.white, lineWidth: 1)
)
}
.background(Color.green)
.cornerRadius(20)
}
}
}
I Created TextField and Button in VStack
Now letās create a Text and see the results š§
if apiRequestManager.responseData != nil {
Text(String(data: apiRequestManager.responseData!, encoding: .utf8) ?? "")
} else if apiRequestManager.responseError != nil {
Text(apiRequestManager.responseError!.localizedDescription)
}
The text here will show our api response. I checked before if response data is nil because our response data is optional!
Letās run the project!
Yes we saw the response but it comes with like JSON Object š¤ We donāt want this. Only we need just text it starts with Elon Musk is an American technologyā¦.
We need to do a few operations just to get this text in JsonObject using JSONSerialization
if let data = apiRequestManager.responseData {
if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
if let choices = json["choices"] as? [[String: Any]] {
if let text = choices[0]["text"] as? String {
Text(text)
}
}
}
}
This code will help us. It means get into choices dictionary and get first element (0. index) set to text value.
Now letās run the project again!
Thatās It check link for Github Repo:
See you in other articles, bye š