Skip to content

Some of the chunk data fail to convert to JSON completely randomly #13

@houmie

Description

@houmie

Description
This is probably the best SSE implementation for Swift I have found on Github. But there is a problem with consistency. Some of the chunk data fail to convert to JSON completely randomly.

To Reproduce

In this example below we are sending a POST / SSE request to Oobabooga.
It works but some chunks throw Problematic data: error and hence get skipped. I have checked for hours, there is no reason why the chuck should fail to convert to JSON. And it's random.

       guard let urlFull = URL(string: Constants.apiServiceUrlFull) else {
            print("Invalid Full URL")
            return
        }
        var request = URLRequest(url: urlFull)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        let requestBody: [String: Any] = [
            "prompt": "\(prompt)",
            "max_new_tokens": 256,
            "max_tokens": 256,
            "temperature": 1,
            "stream": true,
        ]

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: requestBody, options: [])
            request.httpBody = jsonData
        } catch {
            print("Error serializing JSON: \(error)")
            return
        }

        let eventSource = EventSource()
        var accumulatedResponse = ""
        let dataTask = eventSource.dataTask(for: request)

        for await event in dataTask.events() {
            switch event {
            case .open:
                print("Connection was opened.")
            case let .error(error):
                print("Received an error:", error.localizedDescription)
            case let .message(message):
                if let dataString = message.data, let jsonData = dataString.data(using: .utf8) {
                    do {
                        if let jsonObject = try JSONSerialization
                            .jsonObject(with: jsonData, options: []) as? [String: Any]
                        {
                            if let choices = jsonObject["choices"] as? [[String: Any]],
                               !choices.isEmpty,
                               let text = choices[0]["text"] as? String
                            {
                                accumulatedResponse += text
                            }
                        }
                    } catch {
                        print("Error parsing JSON to dictionary: \(error.localizedDescription)")
                        print("Problematic data: \(dataString)")
                    }
                }
            case .closed:
                DispatchQueue.main.async {
                    completion(accumulatedResponse)
                }
                print("Connection was closed.")
            }
        }

Expected behavior
No valid chunck should fail.
For example this chunk failed as invalid, but why?

{
  "id": "conv-1712055152177441792",
  "object": "text_completion.chunk",
  "created": 1712055152,
  "model": "intervitens_Nous-Hermes-2-Mixtral-8x7B-DPO-3.7bpw-h6-exl2-rpcal",
  "choices": [
    {
      "index": 0,
      "finish_reason": null,
      "text": " \"",
      "logprobs": {
        "top_logprobs": [
          {}
        ]
      }
    }
  ]
}
  • Platform: [iOS 17.0]
  • EventSource version: [0.0.7]

Additional context
Thanks for this great project.

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingquestionFurther information is requested

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions