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
14 changes: 11 additions & 3 deletions Sources/AnyLanguageModel/Models/OllamaLanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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)
Expand Down Expand Up @@ -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)" }
Expand Down
39 changes: 39 additions & 0 deletions Tests/AnyLanguageModelTests/HTTPTransportTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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}]}"#
Expand Down
Loading