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

your code is broken. #108

Open
WilliamClancy opened this issue Aug 1, 2023 · 2 comments
Open

your code is broken. #108

WilliamClancy opened this issue Aug 1, 2023 · 2 comments

Comments

@WilliamClancy
Copy link

Describe the bug
Your updated code does not allow for chats and you now have some crazy requirements an API string. After banging my head over and over again to get your stuff to work I gave up.

But I decided to write an API of my own and share it.

Cheers,

Robert Clancy

//
// ViewController.swift
// Open AI API
//
// Created by Robert Clancy on 30.07.2023.
//

import Cocoa
import WebKit
import Foundation
var lastResponse = ""
class ViewController: NSViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    var results = ""
    var openAICommand = ""
    Task {
        do {
            try await postMessage(apiKey: "your key", content: openAICommand, role: "user", model: "gpt-3.5-turbo")
        } catch {
            print("An error occurred: \(error)")
        }
    }


}

@IBOutlet weak var webViewMain: WKWebView!

override var representedObject: Any? {
    didSet {
        // Update the view, if already loaded.
    }
}


struct OpenAIResponse: Codable {
    let id: String
    let object: String
    let created: Int
    let model: String
    let usage: Usage
    let choices: [Choice]
}

struct Usage: Codable {
    let prompt_tokens: Int
    let completion_tokens: Int
    let total_tokens: Int
}

struct Choice: Codable {
    let message: Message
    let finish_reason: String
}


struct Message: Codable {
    let role: String
    let content: String
}

struct CompletionRequest: Codable {
    let model: String
    let max_tokens: Int
    let messages: [Message]
    let temperature: Double
    let stream: Bool
}


func postMessage(apiKey: String, content: String, role: String, model: String,  temperature: Double = 0.7) async throws {
    let url = URL(string: "https://api.openai.com/v1/chat/completions")!
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
    
    let message = Message(role: role, content: content)
    let requestObject = CompletionRequest(model: model, max_tokens: 4000, messages: [message], temperature: temperature, stream: false)
    let requestData = try JSONEncoder().encode(requestObject)
    request.httpBody = requestData
    
    do {
        let (data, _) = try await URLSession.shared.data(for: request)
        if let jsonString = String(data: data, encoding: .utf8) {
            print(jsonString)  // This prints the raw JSON response
        }
        let responseObject = try JSONDecoder().decode(OpenAIResponse.self, from: data)
        print(responseObject.choices[0].message.content) // Handle the response as needed
        lastResponse = responseObject.choices[0].message.content
    } catch {
        print("Error: \(error)")
    }
}

}

@clementinelove
Copy link

You just made me question myself why am I even try to use a third party package for API request 🐦

@WilliamClancy
Copy link
Author

Your welcome!

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