This tutorial teaches you methods to construct a GPT client for iOS using SwiftUI. The tutorial covers methods to send a request to the OpenAI GPT API and decode the JSON response to display the generated text.
Note that this tutorial will give attention to the logic for sending and receiving requests to and from the OpenAI GPT API, and is not going to cover all of the UI details involved in constructing the app.
For the complete code, including the UI implementation, you possibly can visit my Github repo containing working code samples for creating iOS and Android apps
What’s GPT?
GPT, or Generative Pre-trained Transformer, is a variety of machine learning model that’s able to generating natural language text. It’s a variety of language model that has been pre-trained on large amounts of text data, and will be fine-tuned for specific tasks, akin to generating text in response to a prompt.
What is going to we construct?
We’ll construct an app that takes a user input from a TextField, sends it to the GPT API, receives the response, and decodes the JSON so as to display the reply as animated Text. The sendRequest
function is answerable for communicating with the OpenAI GPT API. After encoding the user’s query as a JSON payload, it sends a POST
request to the API. If the API responds with a standing code of 200, the function extracts the generated text from the JSON response and displays it as animated text using SwiftUI’s Text
view. If the API responds with an error, the function displays an error message as an alternative.
Here is an animated screenshot of the ultimate app:
Sending a Request to the GPT API
We’ll now show the code that’s crucial to send a request to the GPT API. A step-by-step explanation will follow.
func sendRequest(query: String) async throws {
guard !query.isEmpty else { return }
let requestDto = RequestDto(prompt: query, max_tokens: 100, model: "text-davinci-003")
guard let payload = try? JSONEncoder().encode(requestDto) else { return }let url = URL(string: "https://api.openai.com/v1/completions")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = payload
request.setValue("Bearer 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", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
isLoading = true
let (data, response) = try await URLSession.shared.data(for: request)
guard (response as? HTTPURLResponse)?.statusCode == 200 else{
DispatchQueue.most important.async {
self.answer = "Unable to receive answer."
self.isLoading = false
}
return
}
let json = try? JSONSerialization.jsonObject(with: data, options: [])
if let json = json as? [String: Any],
let decisions = json["choices"] as? [[String: Any]],
let firstChoice = decisions.first,
let text = firstChoice["text"] as? String {
DispatchQueue.most important.async {
self.answer = text.replacingOccurrences(of: "^s*", with: "", options: .regularExpression)
self.isLoading = false
}
}
}
The source code above allows the app to speak with the OpenAI GPT API. Here’s a transient explanation of the most important parts of the code:
- The
async
keyword indicates that this function is asynchronous, meaning that it is going to run within the background and never block the most important thread. - The
RequestDto
object is created with the user’s query, the utmost variety of tokens to generate, and the GPT model to make use of. - The
payload
variable is created by encoding theRequestDto
object as JSON. - The
url
variable is ready to the URL of the OpenAI GPT API. - The
request
variable is created with the URL and HTTP method set toPOST
. The payload is ready because the HTTP body, and the authorization token and content type are set as HTTP header fields. - The
data
andresponse
variables are created by sending the HTTP request to the API usingsession.data(for: request)
. - The
guard
statement checks whether the API response has a standing code of 200. If it doesn’t, theanswer
variable is ready to “Unable to receive answer” and theisLoading
variable is ready tofalse
. - The
json
variable is created by deserializing the API response data usingJSONSerialization.jsonObject(with: data, options: [])
. - The generated text is extracted from the
json
variable and displayed within theanswer
variable.
The Authorization
header within the code above accommodates an API key that is particular to the developer who created it, on this case me. For those who plan to make use of this code, you’ll need to exchange the API key along with your own.
To acquire an API key for the OpenAI API, you’ll need to create an account on the OpenAI website (openai.com). Once you’ve gotten an account, navigate to the API section of the web site and follow the instructions to create an API key. Be certain to maintain your API key secure and don’t share it with others.
Conclusion
On this tutorial, we construct an iOS app that takes user input, sends it to the OpenAI GPT API, and displays the generated text as animated SwiftUI Text.
I hope you found this tutorial informative and that it has inspired you to create your project based on the GPT API. If you’ve gotten any questions or feedback, be at liberty to go away a comment.
The complete code will be downloaded from my repo that accommodates working code samples for creating iOS and Android apps: https://github.com/twissmueller/mobile-snippets
Thanks for reading!
Your article made me suddenly realize that I am writing a thesis on gate.io. After reading your article, I have a different way of thinking, thank you. However, I still have some doubts, can you help me? Thanks.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://www.binance.info/kz/join?ref=FIHEGIZ8