import Foundation import OSLog protocol ModelProvider: AnyObject, Sendable { var displayName: String { get } func stream(messages: [APIMessage], model: String, tools: [ChatTool]) async throws -> AsyncThrowingStream } extension ModelProvider { func stream(messages: [APIMessage], model: String) async throws -> AsyncThrowingStream { try await stream(messages: messages, model: model, tools: []) } /// Runs a request to completion and returns only its text. func complete(messages: [APIMessage], model: String) async throws -> String { var text = "" for try await event in try await stream(messages: messages, model: model) { if case .text(let token) = event { text += token } } return text } } /// One piece of a streamed response: text as it arrives, or a tool call once its arguments are complete. enum StreamEvent: Sendable { case text(String) case toolCall(ToolCall) } enum ProviderError: LocalizedError { case missingAPIKey case invalidURL case httpError(Int, String) case decodingError(String) var errorDescription: String? { switch self { case .missingAPIKey: return "API key is not configured." case .invalidURL: return "Invalid base URL." case .httpError(let code, let body): return "HTTP \(code): \(body)" case .decodingError(let msg): return "Decoding error: \(msg)" } } } /// Streams an OpenAI-compatible `/chat/completions` request. If the model rejects tool /// definitions (some local models can't call tools), retries once without them. func streamChatCompletions( url: URL, headers: [String: String], model: String, messages: [APIMessage], tools: [ChatTool], label: String ) async throws -> AsyncThrowingStream { var req = URLRequest(url: url) req.httpMethod = "POST" req.setValue("application/json", forHTTPHeaderField: "Content-Type") for (field, value) in headers { req.setValue(value, forHTTPHeaderField: field) } var body: [String: Any] = [ "model": model, "stream": true, "messages": messages.map(\.jsonObject) ] if !tools.isEmpty { body["tools"] = tools.map(\.jsonObject) } req.httpBody = try JSONSerialization.data(withJSONObject: body) let (bytes, response) = try await URLSession.shared.bytes(for: req) if let http = response as? HTTPURLResponse { Logger.api.info("\(label, privacy: .public) HTTP status=\(http.statusCode, privacy: .public)") if http.statusCode != 200 { var errBody = "" for try await byte in bytes { errBody.append(Character(UnicodeScalar(byte))) } Logger.api.error("\(label, privacy: .public) error body: \(errBody, privacy: .public)") if !tools.isEmpty, http.statusCode == 400, errBody.localizedCaseInsensitiveContains("tool") { Logger.api.notice("\(label, privacy: .public) model rejected tools — retrying without them") return try await streamChatCompletions( url: url, headers: headers, model: model, messages: messages, tools: [], label: label ) } throw ProviderError.httpError(http.statusCode, errBody) } } return AsyncThrowingStream { cont in Task { do { var calls = ToolCallAccumulator() // Some providers leak the model's native tool-call markup into the text instead, // even on requests without tools; it's never shown. var inline: InlineToolCallFilter? = InlineToolCallFilter() var lineIndex = 0 for try await line in bytes.lines { if lineIndex < 10 { Logger.api.debug("\(label, privacy: .public) raw[\(lineIndex, privacy: .public)]: \(line, privacy: .public)") } lineIndex += 1 for chunk in parseOpenAISSE(line) { switch chunk { case .text(let token): let visible = inline?.feed(token) ?? token if !visible.isEmpty { cont.yield(.text(visible)) } case .toolCallDelta(let delta): calls.add(delta) } } } var finished = calls.finished() if let (rest, inlineCalls) = inline?.finish() { if !rest.isEmpty { cont.yield(.text(rest)) } if finished.isEmpty, !tools.isEmpty { finished = inlineCalls } if !inlineCalls.isEmpty { Logger.api.notice("\(label, privacy: .public) recovered \(inlineCalls.count, privacy: .public) tool call(s) written as text") } } for call in finished { cont.yield(.toolCall(call)) } Logger.api.info("\(label, privacy: .public) stream finished — \(lineIndex, privacy: .public) lines total") cont.finish() } catch { Logger.api.error("\(label, privacy: .public) stream error: \(error, privacy: .public)") cont.finish(throwing: error) } } } } // MARK: - SSE parsing enum SSEChunk { case text(String) case toolCallDelta(ToolCallDelta) } /// A fragment of a streamed tool call. Arguments arrive split across many chunks, keyed by `index`. struct ToolCallDelta { var index: Int var id: String? var name: String? var arguments: String? } struct ToolCallAccumulator { private var calls: [Int: ToolCallDelta] = [:] mutating func add(_ delta: ToolCallDelta) { var call = calls[delta.index] ?? ToolCallDelta(index: delta.index) if let id = delta.id, !id.isEmpty { call.id = id } if let name = delta.name, !name.isEmpty { call.name = name } if let args = delta.arguments { call.arguments = (call.arguments ?? "") + args } calls[delta.index] = call } func finished() -> [ToolCall] { calls.keys.sorted().compactMap { index in guard let call = calls[index], let name = call.name else { return nil } return ToolCall(id: call.id ?? "call_\(index)", name: name, arguments: call.arguments ?? "{}") } } } /// Pulls tool calls a model wrote into its text (DeepSeek's `<|DSML|invoke …>` markup, or /// `{json}`) out of the stream, so they run instead of showing as text. struct InlineToolCallFilter { nonisolated(unsafe) private static let start = try! NSRegularExpression(pattern: #"<\s*[||]\s*DSML|"#) private var pending = "" private var captured: String? /// Returns the text that is safe to show now. mutating func feed(_ token: String) -> String { if captured != nil { captured! += token return "" } pending += token let range = NSRange(pending.startIndex..., in: pending) if let match = Self.start.firstMatch(in: pending, range: range), let r = Range(match.range, in: pending) { let before = String(pending[.. (String, [ToolCall]) { guard let captured else { return (pending, []) } let calls = Self.parseDSML(captured) + Self.parseToolCallTags(captured) // Unparseable DSML is still markup, not prose. if calls.isEmpty, !captured.contains("") { return ("", []) } return calls.isEmpty ? (captured, []) : ("", calls) } private static func parseDSML(_ text: String) -> [ToolCall] { let sep = #"\s*[||]\s*DSML\s*[||]\s*"# guard let invoke = try? NSRegularExpression( pattern: #"<"# + sep + #"invoke\s+name="([^"]+)"\s*>(.*?)<\s*/"# + sep + #"invoke\s*>"#, options: .dotMatchesLineSeparators), let parameter = try? NSRegularExpression( pattern: #"<"# + sep + #"parameter\s+name="([^"]+)"[^>]*>(.*?)<\s*/"# + sep + #"parameter\s*>"#, options: .dotMatchesLineSeparators) else { return [] } let ns = text as NSString return invoke.matches(in: text, range: NSRange(location: 0, length: ns.length)).enumerated().map { i, m in let body = ns.substring(with: m.range(at: 2)) let bns = body as NSString var args: [String: String] = [:] for p in parameter.matches(in: body, range: NSRange(location: 0, length: bns.length)) { args[bns.substring(with: p.range(at: 1))] = bns.substring(with: p.range(at: 2)) .trimmingCharacters(in: .whitespacesAndNewlines) } let json = (try? JSONSerialization.data(withJSONObject: args)).flatMap { String(data: $0, encoding: .utf8) } ?? "{}" return ToolCall(id: "inline_\(i)", name: ns.substring(with: m.range(at: 1)), arguments: json) } } private static func parseToolCallTags(_ text: String) -> [ToolCall] { guard let tag = try? NSRegularExpression(pattern: #"(.*?)"#, options: .dotMatchesLineSeparators) else { return [] } let ns = text as NSString return tag.matches(in: text, range: NSRange(location: 0, length: ns.length)).enumerated().compactMap { i, m in guard let data = ns.substring(with: m.range(at: 1)).data(using: .utf8), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let name = object["name"] as? String else { return nil } let args = (object["arguments"] ?? object["parameters"] ?? [:]) let json = (try? JSONSerialization.data(withJSONObject: args)).flatMap { String(data: $0, encoding: .utf8) } ?? "{}" return ToolCall(id: "inline_\(i)", name: name, arguments: json) } } } // Parses one line from an OpenAI-compatible SSE stream. // Handles both "data: {...}" SSE format and raw JSON lines (some Ollama builds). func parseOpenAISSE(_ line: String) -> [SSEChunk] { let jsonString: String if line.hasPrefix("data: ") { let payload = String(line.dropFirst(6)).trimmingCharacters(in: .whitespaces) guard payload != "[DONE]", !payload.isEmpty else { return [] } jsonString = payload } else if line.hasPrefix("{") { jsonString = line } else { return [] } guard let data = jsonString.data(using: .utf8), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let choices = json["choices"] as? [[String: Any]], let first = choices.first else { return [] } // streaming delta, or non-streaming fallback (message) guard let message = (first["delta"] ?? first["message"]) as? [String: Any] else { return [] } var chunks: [SSEChunk] = [] if let text = message["content"] as? String, !text.isEmpty { chunks.append(.text(text)) } for (offset, call) in ((message["tool_calls"] as? [[String: Any]]) ?? []).enumerated() { let function = call["function"] as? [String: Any] // Ollama sends arguments as an object rather than a JSON string. var arguments = function?["arguments"] as? String if arguments == nil, let object = function?["arguments"], let data = try? JSONSerialization.data(withJSONObject: object) { arguments = String(data: data, encoding: .utf8) } chunks.append(.toolCallDelta(ToolCallDelta( index: call["index"] as? Int ?? offset, id: call["id"] as? String, name: function?["name"] as? String, arguments: arguments ))) } return chunks }