Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Got a blank message response from Chatgpt #137

Open
wutaiyi0129 opened this issue Jul 2, 2024 · 1 comment
Open

Got a blank message response from Chatgpt #137

wutaiyi0129 opened this issue Jul 2, 2024 · 1 comment

Comments

@wutaiyi0129
Copy link

wutaiyi0129 commented Jul 2, 2024

import OpenAISwift
import SwiftUI

final class ViewModel: ObservableObject {
    init(){}
    private var client: OpenAISwift?
    
    func setup(){
        client = OpenAISwift(config: OpenAISwift.Config.makeDefaultOpenAI(apiKey: "key"))
    }
    
    func send(text: String, completion: @escaping (String) -> Void) {
     
        client?.sendCompletion(with: text, maxTokens: 500, temperature: 0.7, completionHandler: { result in
            switch result {
            case .success(let model):
                let output = model.choices?.first?.text ?? "blank message"
                print(model)
                completion(output)
            case .failure:
               break
            }
        })3
    }
}

struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()
    @State var text = ""
    @State var models = [String]()
    
    var body: some View {
        VStack(alignment: .leading) {
            ForEach(models, id: \.self) { string in
                Text(string)
            }
            Spacer()
            HStack {
                TextField("在此輸入", text: $text)
                Button("送出") {
                    send()
                }
            }
           
        }
        .onAppear {
            viewModel.setup()
        }
        .padding()
    }
    
    func send() {
        guard !text.trimmingCharacters(in: .whitespaces).isEmpty else {
            return
        }
        models.append("Me: \(text)")
        viewModel.send(text: text) { response in
            DispatchQueue.main.async {
                self.models.append("ChatGPT: \(response)")
                self.text = ""
            }
        }
    }
}

#Preview {
    ContentView()
}

@Mnu02
Copy link

Mnu02 commented Jul 31, 2024

Same here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants