TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Using chatGTP in Swift?

Forums > Swift

I've seen there are a number of libraries in github, plus you can roll your own and access the chatGTP API directly.

Have any of you folk done this already? if so what route did you take?

I would simply like to send a request to GTP and display the result. If anyone has done this i'd be intersted in how you implemented it.

Many thanks for all advice!

2      

Hi so I used this.

I hope this can help someone. Below is a ContentView that prompts for a question and returns a response from ChatGTP. It's not perfect but it works and perhaps can be used as a starting point for some better integration.


import SwiftUI

struct GTP: View {
    @State private var text: String = ""
    @State private var output: [String] = []
    @State private var showErrorAlert: Bool = false
    @State private var errorMessage: String = ""

    var body: some View {
        VStack {
            TextField("Enter a prompt", text: $text)
                .padding()
                .border(Color.gray, width: 1)
                .padding()

            Button(action: generateText) {
                Text("Generate Answer")
                    .padding()
                    .foregroundColor(Color.white)
                    .background(Color.blue)
                    .cornerRadius(8)
            }
            .padding()

            List(output, id: \.self) { item in
                Text(item)
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding()

        }
        .alert(isPresented: $showErrorAlert) {
            Alert(title: Text("Error"), message: Text(errorMessage), dismissButton: .default(Text("OK")))
        }
    }

    func generateText() {
        let apiKey = "YOUR_API_KEY"
        let apiURL = "https://api.openai.com/v1/engines/davinci/completions"

        guard let url = URL(string: apiURL) else {
            showErrorAlert = true
            errorMessage = "Invalid API URL"
            return
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("Bearer " + apiKey, forHTTPHeaderField: "Authorization")

        let parameters: [String: Any] = [
            "prompt": text,
            "max_tokens": 500,
            "temperature": 1.0
        ]

        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
        } catch {
            showErrorAlert = true
            errorMessage = "Failed to serialize parameters"
            return
        }

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data, error == nil else {
                showErrorAlert = true
                errorMessage = error?.localizedDescription ?? "Unknown error"
                return
            }

            do {
                let response = try JSONDecoder().decode(ChatGPTResponse.self, from: data)
                let text = response.choices.first?.text ?? ""
                let sentences = text.components(separatedBy: ". ")
                DispatchQueue.main.async {
                    output = sentences.map { "• \($0)" }
                }
            } catch {
                showErrorAlert = true
                errorMessage = "Failed to decode response"
                return
            }
        }

        task.resume()
    }
}

struct ChatGPTResponse: Codable {
    let choices: [ChatGPTChoice]
}

struct ChatGPTChoice: Codable {
    let text: String
}

2      

I need little bit help about this. Would you like to guide me about it?

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.