alfianlosari / ChatGPTSwift

Access ChatGPT API using Swift
MIT License
649 stars 130 forks source link

Swift/RangeReplaceableCollection.swift:622: Fatal error: Can't remove first element from an empty collection #30

Open itamargilvybe opened 11 months ago

itamargilvybe commented 11 months ago

AnalyticsView - I call the function try await vm.analyseWeek()

AnswersAnalyticsVM:

private let api = ChatGPTAPI(apiKey: Constants.Keys.chatgpt)
private let gptModel = "gpt-3.5-turbo"

func analyseWeek() async throws {
        do {
            let weekAnswers = try await collectAllWeekAnswers() // Fetching the data to input ChatGPT

            let analysisString = try await api.sendMessage(text: weekAnswers, model: gptModel)

            if let userid = await Session.shared.user_id {
                // Saving output to DB
            } else {
                throw CustomError.sessionError
            }

        } catch let err{
            throw err
        }
    }

App crashes when I call api.sendMessage() with the message "Swift/RangeReplaceableCollection.swift:622: Fatal error: Can't remove first element from an empty collection".

XCode crash trickle-down:

public func sendMessage(text: String,
                            model: String = ChatGPTAPI.Constants.defaultModel,
                            systemText: String = ChatGPTAPI.Constants.defaultSystemText,
                            temperature: Double = ChatGPTAPI.Constants.defaultTemperature) async throws -> String {
        var urlRequest = self.urlRequest
        urlRequest.httpBody = try jsonBody(text: text, model: model, systemText: systemText, temperature: temperature, stream: false) // Here
        ...

private func json``` Body(text: String, model: String, systemText: String, temperature: Double, stream: Bool = true) throws -> Data { let request = Request(model: model, temperature: temperature, messages: generateMessages(from: text, systemText: systemText), stream: stream) // Here return try JSONEncoder().encode(request) }


private func generateMessages(fro```
m text: String, systemText: String) -> [Message] {
        var messages = [systemMessage(content: systemText)] + historyList + [Message(role: "user", content: text)]
        if gptEncoder.encode(text: messages.content).count > 4096  {
            _ = historyList.removeFirst()
            messages = generateMessages(from: text, systemText: systemText) // Here
        }
        return messages
    }

Why does it happen? I think it's a bug.

IhorLeshko commented 3 months ago

Same here, any solutions?

conradobh commented 3 weeks ago

same here