diff --git a/Sources/AnyLanguageModel/Models/OllamaLanguageModel.swift b/Sources/AnyLanguageModel/Models/OllamaLanguageModel.swift index 74c336e8..86c1e5cf 100644 --- a/Sources/AnyLanguageModel/Models/OllamaLanguageModel.swift +++ b/Sources/AnyLanguageModel/Models/OllamaLanguageModel.swift @@ -279,6 +279,7 @@ public struct OllamaLanguageModel: LanguageModel, ProfileRequestIdentifiedLangua dateDecodingStrategy: .iso8601WithFractionalSeconds ) let chatResponse = try reply.response() + guard chatResponse.done else { throw OllamaError.incompleteResponse } usage.add(chatResponse.reportedUsage) let thinking = chatResponse.message.thinking ?? "" let reasoning = thinking.isEmpty ? nil : Transcript.Reasoning.ollama(thinking) @@ -468,6 +469,7 @@ public struct OllamaLanguageModel: LanguageModel, ProfileRequestIdentifiedLangua ) var toolCalls: [OllamaToolCall] = [] var thinking = "" + var done = false for try await reply in chunks { let chunk = try reply.response() state.usage.merge(chunk.reportedUsage) @@ -477,8 +479,13 @@ public struct OllamaLanguageModel: LanguageModel, ProfileRequestIdentifiedLangua if chunk.message.content != nil || chunk.reportedUsage != nil { if let snapshot = state.snapshot() { continuation.yield(snapshot) } } - if chunk.done { break } + if chunk.done { + done = true + break + } } + try Task.checkCancellation() + guard done else { throw OllamaError.incompleteResponse } guard !toolCalls.isEmpty else { // The final round's reasoning reaches the last snapshot. if !thinking.isEmpty { @@ -487,7 +494,6 @@ public struct OllamaLanguageModel: LanguageModel, ProfileRequestIdentifiedLangua } break } - try Task.checkCancellation() try session.recordToolRound(toolRounds, completed: state.entries) if !thinking.isEmpty { let reasoning = Transcript.Reasoning.ollama(thinking) @@ -894,8 +900,10 @@ private func convertSegmentsToOllama(_ segments: [Transcript.Segment]) -> (Strin return (textParts.joined(separator: "\n"), images) } -/// An error Ollama reported in place of a chat response, with its own message. +/// An error reported by Ollama or detected while reading its response. struct OllamaError: Error, Sendable, CustomStringConvertible { + static let incompleteResponse = Self(message: "The response ended before Ollama sent done: true.") + let message: String var description: String { "Ollama: \(message)" } diff --git a/Tests/AnyLanguageModelTests/HTTPTransportTests.swift b/Tests/AnyLanguageModelTests/HTTPTransportTests.swift index 9538868c..f4a305f6 100644 --- a/Tests/AnyLanguageModelTests/HTTPTransportTests.swift +++ b/Tests/AnyLanguageModelTests/HTTPTransportTests.swift @@ -47,6 +47,45 @@ struct HTTPTransportTests { #expect(response.content == "Hello") } + @Test(arguments: [false, true]) + func incompleteOllamaTextThrows(streaming: Bool) async throws { + let partial = + #"{"model":"m","created_at":"2026-10-18T10:00:00.000Z","message":{"role":"assistant","content":"Hel"},"done":false}"# + let transport = FakeTransport(replies: [.init(chunks: [partial])]) + let model = OllamaLanguageModel(baseURL: Self.ollama, model: "m", transport: transport) + let session = LanguageModelSession(model: model) + + await #expect(throws: OllamaError.self) { + if streaming { + _ = try await session.streamResponse(to: "Hi").collect() + } else { + _ = try await session.respond(to: "Hi") + } + } + } + + @Test(arguments: [false, true]) + func incompleteOllamaToolCallDoesNotRun(streaming: Bool) async throws { + let call = + #"{"model":"m","created_at":"2026-10-18T10:00:00.000Z","message":{"role":"assistant","tool_calls":[{"function":{"name":"getWeather","arguments":{"city":"Paris"}}}]},"done":false}"# + let answer = + #"{"model":"m","created_at":"2026-10-18T10:00:01.000Z","message":{"role":"assistant","content":"Sunny"},"done":true}"# + let transport = FakeTransport(replies: [.init(chunks: [call]), .init(chunks: [answer])]) + let model = OllamaLanguageModel(baseURL: Self.ollama, model: "m", transport: transport) + let tool = spy(on: WeatherTool()) + let session = LanguageModelSession(model: model, tools: [tool]) + + await #expect(throws: OllamaError.self) { + if streaming { + _ = try await session.streamResponse(to: "Weather?").collect() + } else { + _ = try await session.respond(to: "Weather?") + } + } + #expect(await tool.calls.isEmpty) + #expect(transport.requests.count == 1) + } + @Test func eventsSplitAcrossChunksAreRead() async throws { func event(_ content: String) -> String { #"data: {"id":"c","object":"chat.completion.chunk","created":0,"model":"m","choices":[{"index":0,"delta":{"content":"\#(content)"},"finish_reason":null}]}"#