Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions Sources/AnyLanguageModel/Shared/JSONLines.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// Splits a JSON Lines (NDJSON) body into its lines as the bytes arrive: each line ends with `\n`,
/// and the last one may not. Empty lines are skipped. A `\r` before the `\n` stays in the line,
/// where a JSON decoder reads it as whitespace.
/// and the last one may not. Empty lines (including `\r\n`) are skipped. A `\r` before the `\n`
/// stays in a non-empty line, where a JSON decoder reads it as whitespace.
struct JSONLines {
private var line: [UInt8] = []

Expand All @@ -11,7 +11,7 @@ struct JSONLines {
return nil
}
defer { line.removeAll(keepingCapacity: true) }
return line.isEmpty ? nil : line
return hasContent ? line : nil
}

/// The lines `bytes` complete.
Expand All @@ -22,6 +22,10 @@ struct JSONLines {
/// The last line, once the body has ended, if it had no `\n`.
mutating func finish() -> [UInt8]? {
defer { line = [] }
return line.isEmpty ? nil : line
return hasContent ? line : nil
}

private var hasContent: Bool {
line.contains { $0 != UInt8(ascii: "\r") }
}
}
16 changes: 16 additions & 0 deletions Tests/AnyLanguageModelTests/HTTPTransportTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,22 @@ struct HTTPTransportTests {
#expect(response.content == "Hello")
}

@Test func streamedEmptyCRLFLinesAreSkipped() async throws {
let transport = FakeTransport(replies: [
.init(chunks: [
"\r\n"
+ #"{"model":"m","created_at":"2026-10-18T10:00:00.000Z","message":{"role":"assistant","content":"Hel"},"done":false}"#
+ "\r\n\r\n",
#"{"model":"m","created_at":"2026-10-18T10:00:00.000Z","message":{"role":"assistant","content":"lo"},"done":true}"#
+ "\r\n\r\n",
])
])
let model = OllamaLanguageModel(baseURL: Self.ollama, model: "m", transport: transport)
let response = try await LanguageModelSession(model: model).streamResponse(to: "Hi").collect()

#expect(response.content == "Hello")
}

@Test(arguments: [false, true])
func incompleteOllamaTextThrows(streaming: Bool) async throws {
let partial =
Expand Down
6 changes: 6 additions & 0 deletions Tests/AnyLanguageModelTests/JSONLinesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,10 @@ struct JSONLinesTests {
struct Line: Decodable { let a: Int }
#expect(try JSONDecoder().decode(Line.self, from: Data(lines[0].utf8)).a == 1)
}

@Test func emptyCRLFLinesAreSkipped() {
#expect(split(["\r\n{\"a\":1}\r\n\r\n"]) == ["{\"a\":1}\r"])
#expect(split(["\r", "\n{\"a\":1}\r", "\n\r", "\n"]) == ["{\"a\":1}\r"])
#expect(split(["{\"a\":1}\r\n\r"]) == ["{\"a\":1}\r"])
}
}
Loading