Last active
August 9, 2023 03:19
-
-
Save MatthewWaller/545634c40e7d5857fcd6088cd89d3a10 to your computer and use it in GitHub Desktop.
SwiftUI Meets ChatGPT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
@StateObject var service = ChatGPTService() | |
@State var textResponse = "" | |
var body: some View { | |
VStack { | |
Text("Bot says: \(textResponse)") | |
Button { | |
Task { | |
let response = try await service.processPrompt(prompt: "Pretend to be a choose-your-own adventure book about Jurassic Park please.") | |
textResponse = response ?? "" | |
} | |
} label: { | |
Image(systemName: "globe") | |
.imageScale(.large) | |
.foregroundColor(.accentColor) | |
Text("Hello, world!") | |
} | |
.padding() | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
class ChatGPTService: ObservableObject { | |
let apiKey: String = "this is your api key" | |
let openAIURL = URL(string: "https://api.openai.com/v1/chat/completions") | |
public func processPrompt( | |
prompt: String | |
) async throws -> Optional<String> { | |
var request = URLRequest(url: self.openAIURL!) | |
request.httpMethod = "POST" | |
request.addValue("application/json", forHTTPHeaderField: "Content-Type") | |
request.addValue("Bearer \(self.phoneNumber)", forHTTPHeaderField: "Authorization") | |
let httpBody: [String: Any] = [ | |
"model": "gpt-3.5-turbo", | |
"messages" : [["role" : "user", "content": prompt]], | |
] | |
let httpBodyJson = try JSONSerialization.data(withJSONObject: httpBody, options: .prettyPrinted) | |
request.httpBody = httpBodyJson | |
let (data, _) = try await URLSession.shared.data(for: request) | |
let object = try? JSONSerialization.jsonObject(with: data) | |
let responseHandler = OpenAIResponseHandler() | |
let openAIResponse = responseHandler.decodeJson(data) | |
return openAIResponse?.choices.first?.message.content | |
} | |
struct OpenAIResponseHandler { | |
func decodeJson(_ data: Data) -> OpenAIResponse? { | |
let decoder = JSONDecoder() | |
do { | |
let product = try decoder.decode(OpenAIResponse.self, from: data) | |
return product | |
} catch { | |
print("Error decoding OpenAI API Response") | |
} | |
return nil | |
} | |
} | |
struct OpenAIResponse: Codable { | |
var id: String | |
var choices: [Choice] | |
} | |
struct Choice: Codable { | |
var index: Int | |
var finish_reason: String? | |
var message: Message | |
} | |
struct Message: Codable { | |
var role: String | |
var content: String | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment