Files
ai_studio/Sources/Inference.swift
T
2026-11-16 13:41:54 +00:00

201 lines
6.5 KiB
Swift

import Foundation
struct StudioError: LocalizedError, Sendable {
let message: String
init(_ message: String) { self.message = message }
var errorDescription: String? { message }
}
enum Role: String, Codable, Sendable { case system, user, assistant }
struct Message: Identifiable, Equatable, Sendable {
var id = UUID()
let role: Role
var content: String
var thinking = ""
var backend = ""
}
enum Thinking: String, CaseIterable, Codable, Identifiable, Sendable {
case automatic = "Default"
case off = "Off"
case on = "On"
case low, medium, high
var id: Self { self }
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() { self = .automatic }
else if let boolean = try? container.decode(Bool.self) { self = boolean ? .on : .off }
else {
let value = try container.decode(String.self)
guard let level = Self(rawValue: value), [.low, .medium, .high].contains(level) else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid thinking mode")
}
self = level
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .automatic: try container.encodeNil()
case .off: try container.encode(false)
case .on: try container.encode(true)
case .low, .medium, .high: try container.encode(rawValue)
}
}
}
enum Delta: Equatable, Sendable {
case answer(String)
case thinking(String)
case backend(String)
case metrics(ProviderMetrics)
case committed
}
struct InferenceRequest: Sendable {
let model: String
let messages: [Message]
let thinking: Thinking
}
protocol InferenceProvider: Sendable {
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error>
}
// Reserved for user-authorized tool integrations. Providers never dispatch tools.
protocol MCPToolClient: Sendable {
func listTools() async throws -> [MCPTool]
func callTool(_ name: String, argumentsJSON: Data) async throws -> Data
}
struct MCPTool: Sendable {
let name: String
let description: String
let inputSchemaJSON: Data
}
func streaming<Element: Sendable>(
_ work: @escaping @Sendable (AsyncThrowingStream<Element, Error>.Continuation) async throws -> Void
) -> AsyncThrowingStream<Element, Error> {
AsyncThrowingStream { continuation in
let task = Task {
do {
try await work(continuation)
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
continuation.onTermination = { _ in task.cancel() }
}
}
enum Router {
typealias Producer = @Sendable () -> AsyncThrowingStream<Delta, Error>
static func stream(
primary: @escaping Producer,
fallback: Producer?
) -> AsyncThrowingStream<Delta, Error> {
streaming { continuation in
var committed = false
do {
for try await delta in primary() {
try Task.checkCancellation()
switch delta {
case .answer(let text), .thinking(let text):
committed = committed || !text.isEmpty
case .committed: committed = true
case .backend, .metrics: break
}
continuation.yield(delta)
}
try Task.checkCancellation()
} catch {
try Task.checkCancellation()
guard !committed, !(error is CancellationError), (error as? URLError)?.code != .cancelled,
let fallback else { throw error }
do {
for try await delta in fallback() {
try Task.checkCancellation()
continuation.yield(delta)
}
} catch let fallbackError {
try Task.checkCancellation()
if fallbackError is CancellationError { throw fallbackError }
throw StudioError("Ollama: \(error.localizedDescription) MLX: \(fallbackError.localizedDescription)")
}
}
}
}
}
struct ProviderMetrics: Equatable, Sendable {
let tokens: Int
let seconds: Double
var tokensPerSecond: Double? {
guard tokens >= 0, seconds > 0, seconds.isFinite else { return nil }
let rate = Double(tokens) / seconds
return rate.isFinite ? rate : nil
}
}
struct GenerationMeasurement: Identifiable {
let id = UUID()
let backend: String
let firstOutput: Double?
let seconds: Double
let characters: Int
let provider: ProviderMetrics?
let outcome: String
}
enum PromptMode: String, CaseIterable, Identifiable {
case standard = "Default"
case concise = "Concise"
case code = "Coding"
case study = "Study"
case creative = "Creative"
case custom = "Custom"
var id: Self { self }
func instructions(custom text: String) -> String {
switch self {
case .standard: ""
case .concise: "Answer directly and concisely. Include details required for accuracy."
case .code: "Act as a software engineering assistant. Explain assumptions, provide runnable examples where appropriate, and suggest ways to verify changes."
case .study: "Teach step by step. Use a worked example and offer a short practice question where appropriate."
case .creative: "Explore varied ideas. Preserve the requested voice and constraints, and develop the strongest ideas with concrete details."
case .custom: String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(12000))
}
}
}
struct PromptDraft {
var role = ""
var task = ""
var context = ""
var audience = ""
var constraints = ""
var format = ""
var examples = ""
var success = ""
var rendered: String {
[
("Role", role), ("Task", task), ("Context", context), ("Audience", audience),
("Requirements and constraints", constraints), ("Output format", format),
("Examples", examples), ("Success criteria", success)
].compactMap { label, value in
let content = value.trimmingCharacters(in: .whitespacesAndNewlines)
return content.isEmpty ? nil : "## \(label)\n\(content)"
}.joined(separator: "\n\n")
}
}