feat(m1): Ollama client, catalog, streaming chat and CLI (T1.1-T1.6)
Add endpoint policy and redirect-safe ephemeral HTTP client, error mapping, catalog cache and version checks, streaming chat with phase timeouts/cancellation, provisional Hy-MT3 prompt/language/request factory, warm-up policy, and sprachmittler-cli models/show/translate. Recapture the 7B fixtures; defer the 1.8B VERIFY items; document ADR-016. Also fix the signature checker's pipefail SIGPIPE issue.
This commit is contained in:
1 parent
7ca5c710ec
commit
26b493e7e5
93 files changed
+3732
-218
No files matched your search
@@ -48,13 +48,19 @@ let package = Package(
|
||||
.target(name: "SprachmittlerEval", dependencies: ["SprachmittlerCore"], swiftSettings: strictSettings),
|
||||
|
||||
// Fakes shared by tests (FakePasteboard, FakeClock, FakeOllamaTransport, FakeTextInserter, …).
|
||||
.target(name: "SprachmittlerTestSupport", dependencies: ["SprachmittlerCore"], swiftSettings: strictSettings),
|
||||
.target(
|
||||
name: "SprachmittlerTestSupport",
|
||||
dependencies: ["SprachmittlerCore", "SprachmittlerOllama"],
|
||||
swiftSettings: strictSettings
|
||||
),
|
||||
|
||||
.executableTarget(
|
||||
name: "sprachmittler-cli",
|
||||
dependencies: [
|
||||
"SprachmittlerCore",
|
||||
"SprachmittlerEngines",
|
||||
"SprachmittlerEval",
|
||||
"SprachmittlerOllama",
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
],
|
||||
swiftSettings: strictSettings
|
||||
@@ -67,7 +73,7 @@ let package = Package(
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerOllamaTests",
|
||||
dependencies: ["SprachmittlerOllama"],
|
||||
dependencies: ["SprachmittlerOllama", "SprachmittlerTestSupport"],
|
||||
resources: [.copy("Fixtures")]
|
||||
),
|
||||
.testTarget(
|
||||
@@ -77,7 +83,7 @@ let package = Package(
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerCoreTests",
|
||||
dependencies: ["SprachmittlerCore", "SprachmittlerTestSupport"]
|
||||
dependencies: ["SprachmittlerCore", "SprachmittlerOllama", "SprachmittlerTestSupport"]
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerCaptureTests",
|
||||
@@ -87,6 +93,15 @@ let package = Package(
|
||||
name: "SprachmittlerEvalTests",
|
||||
dependencies: ["SprachmittlerEval", "SprachmittlerTestSupport"]
|
||||
),
|
||||
.testTarget(
|
||||
name: "SprachmittlerCLITests",
|
||||
dependencies: [
|
||||
"sprachmittler-cli",
|
||||
"SprachmittlerEngines",
|
||||
"SprachmittlerOllama",
|
||||
"SprachmittlerTestSupport",
|
||||
]
|
||||
),
|
||||
// Opt-in tests against a real local Ollama: SPRACHMITTLER_LIVE=1 swift test --filter SprachmittlerLiveTests
|
||||
.testTarget(name: "SprachmittlerLiveTests", dependencies: ["SprachmittlerCore"]),
|
||||
]
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// Maps the leaf's transport vocabulary to the domain taxonomy at the Core boundary.
|
||||
public extension SprachmittlerError {
|
||||
/// Creates a domain error from an `OllamaError`.
|
||||
init(ollama error: OllamaError) {
|
||||
switch error {
|
||||
case let .endpointRejected(reason):
|
||||
self = .endpointRejected(reason: reason)
|
||||
case let .unreachable(url):
|
||||
self = .ollamaUnreachable(url: url)
|
||||
case let .modelNotInstalled(model):
|
||||
self = .modelNotInstalled(model: model)
|
||||
case let .badRequest(message):
|
||||
self = .badRequest(message: message)
|
||||
case let .server(status, message):
|
||||
self = .server(status: status, message: message)
|
||||
case let .timeout(phase):
|
||||
self = .timeout(phase: phase)
|
||||
case .cancelled:
|
||||
self = .cancelled
|
||||
case let .decoding(message):
|
||||
self = .server(status: 0, message: message)
|
||||
case let .unsupportedVersion(found, required):
|
||||
self = .ollamaTooOld(found: found, required: required)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// The domain error taxonomy from ARCHITECTURE §5.
|
||||
///
|
||||
/// Leaf modules throw their own errors (e.g. `OllamaError`); this type is produced at the Core
|
||||
/// boundary by `SprachmittlerError(ollama:)`. UI code shows `userMessage`, never a raw body.
|
||||
public enum SprachmittlerError: Error, Sendable, Equatable {
|
||||
// Capture
|
||||
case noSelection
|
||||
case emptyText
|
||||
case textTooLong(characters: Int, limit: Int)
|
||||
case pasteboardUnavailable
|
||||
// Translation
|
||||
case ollamaUnreachable(url: URL)
|
||||
case ollamaTooOld(found: String, required: String)
|
||||
case endpointRejected(reason: EndpointRejection)
|
||||
case modelNotInstalled(model: String)
|
||||
case noAdapter(model: String)
|
||||
case badRequest(message: String)
|
||||
case server(status: Int, message: String)
|
||||
case timeout(phase: TimeoutPhase)
|
||||
case emptyOutput
|
||||
case truncated
|
||||
case repetitionLoop
|
||||
case preambleDetected
|
||||
case protectedTokenLost(token: String)
|
||||
// Insertion
|
||||
case accessibilityNotTrusted
|
||||
case accessibilityUnsupported(app: String?)
|
||||
case insertionTargetChanged
|
||||
case pasteboardRestoreFailed
|
||||
// General
|
||||
case cancelled
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/// The provisional common-language table for the M1 CLI. T2.3 replaces this with the complete
|
||||
/// 102-language catalogue from docs/LANGUAGES.md.
|
||||
public enum HyMT3Languages {
|
||||
/// English.
|
||||
public static let english = ModelLanguage(code: "en", modelName: "English")
|
||||
/// German.
|
||||
public static let german = ModelLanguage(code: "de", modelName: "German")
|
||||
|
||||
/// The common targets exposed by the M1 CLI.
|
||||
public static let all: [ModelLanguage] = [
|
||||
english,
|
||||
german,
|
||||
ModelLanguage(code: "fr", modelName: "French"),
|
||||
ModelLanguage(code: "es", modelName: "Spanish"),
|
||||
ModelLanguage(code: "it", modelName: "Italian"),
|
||||
ModelLanguage(code: "pt", modelName: "Portuguese"),
|
||||
ModelLanguage(code: "nl", modelName: "Dutch"),
|
||||
ModelLanguage(code: "pl", modelName: "Polish"),
|
||||
ModelLanguage(code: "zh", modelName: "Chinese"),
|
||||
ModelLanguage(code: "zh-Hant", modelName: "Traditional Chinese"),
|
||||
ModelLanguage(code: "ja", modelName: "Japanese"),
|
||||
ModelLanguage(code: "ko", modelName: "Korean"),
|
||||
ModelLanguage(code: "ar", modelName: "Arabic"),
|
||||
ModelLanguage(code: "tr", modelName: "Turkish"),
|
||||
ModelLanguage(code: "ru", modelName: "Russian"),
|
||||
ModelLanguage(code: "uk", modelName: "Ukrainian"),
|
||||
]
|
||||
|
||||
/// Resolves a BCP-47 code case-insensitively; unknown codes return nil (never a guess).
|
||||
public static func resolve(_ code: String) -> ModelLanguage? {
|
||||
let normalized = code.lowercased()
|
||||
return all.first { $0.code.lowercased() == normalized }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/// The provisional Hy-MT3 model tags. The default is decided by the M7 evaluation; this constant
|
||||
/// is the only place the tag appears outside docs and tests.
|
||||
public enum HyMT3ModelPreset {
|
||||
/// The provisional default: Hy-MT3-7B Q4_K_M.
|
||||
public static let defaultModel = "hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M"
|
||||
/// The Fast preset: Hy-MT3-1.8B Q4_K_M.
|
||||
public static let fastModel = "hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M"
|
||||
/// The settings default for keeping the model warm.
|
||||
public static let defaultKeepAlive = "30m"
|
||||
/// The only text used for warm-up. Never user text.
|
||||
public static let warmUpText = "Hello."
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// The documented Hy-MT3 sampling values from docs/HYMT3_MODEL.md §2.
|
||||
public enum HyMT3Options {
|
||||
/// Translation defaults: temperature 0.7, top_p 0.6, top_k 20, repeat_penalty 1.05,
|
||||
/// num_predict 4096, num_ctx 8192.
|
||||
public static let translation = ChatOptions(
|
||||
temperature: 0.7,
|
||||
topP: 0.6,
|
||||
topK: 20,
|
||||
repeatPenalty: 1.05,
|
||||
numPredict: 4096,
|
||||
numCtx: 8192
|
||||
)
|
||||
|
||||
/// Warm-up uses the same model settings but only 8 output tokens.
|
||||
public static let warmUp = ChatOptions(
|
||||
temperature: 0.7,
|
||||
topP: 0.6,
|
||||
topK: 20,
|
||||
repeatPenalty: 1.05,
|
||||
numPredict: 8,
|
||||
numCtx: 8192
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/// The documented Hy-MT3 prompt templates. v1 uses the Default Translation template.
|
||||
public enum HyMT3Prompt {
|
||||
/// The byte-exact Default Translation prompt from docs/HYMT3_MODEL.md §3.
|
||||
///
|
||||
/// The prefix depends only on the target language; the source text is appended last so the
|
||||
/// Ollama prompt cache stays valid.
|
||||
public static func defaultTranslation(target: ModelLanguage, source: String) -> String {
|
||||
let prefix = "Translate the following text into \(target.modelName). "
|
||||
+ "Note that you should **only output the translated result without any additional explanation**:"
|
||||
return prefix + "\n\n" + source
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// Builds the documented Hy-MT3 requests. T2.1/T2.2 replace this with the adapter protocol;
|
||||
/// until then this is the only place the translation request shape is assembled.
|
||||
public struct HyMT3RequestFactory: Sendable {
|
||||
/// The model tag.
|
||||
public let model: String
|
||||
/// The Ollama `keep_alive` value.
|
||||
public let keepAlive: String
|
||||
|
||||
/// Creates a factory.
|
||||
public init(
|
||||
model: String = HyMT3ModelPreset.defaultModel,
|
||||
keepAlive: String = HyMT3ModelPreset.defaultKeepAlive
|
||||
) {
|
||||
self.model = model
|
||||
self.keepAlive = keepAlive
|
||||
}
|
||||
|
||||
/// A translation request with the documented prompt and sampling.
|
||||
public func translationRequest(text: String, target: ModelLanguage) -> ChatRequest {
|
||||
ChatRequest(
|
||||
model: model,
|
||||
messages: [ChatMessage(content: HyMT3Prompt.defaultTranslation(target: target, source: text))],
|
||||
stream: true,
|
||||
keepAlive: keepAlive,
|
||||
options: HyMT3Options.translation
|
||||
)
|
||||
}
|
||||
|
||||
/// A warm-up request with fixed synthetic text and `num_predict: 8`.
|
||||
public func warmUpRequest() -> ChatRequest {
|
||||
ChatRequest(
|
||||
model: model,
|
||||
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
|
||||
stream: true,
|
||||
keepAlive: keepAlive,
|
||||
options: HyMT3Options.warmUp
|
||||
)
|
||||
}
|
||||
|
||||
/// A request that unloads the model after it completes.
|
||||
public func unloadRequest() -> ChatRequest {
|
||||
ChatRequest(
|
||||
model: model,
|
||||
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
|
||||
stream: true,
|
||||
keepAlive: "0",
|
||||
options: HyMT3Options.warmUp
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/// A BCP-47 code paired with the exact English model-card name used in the prompt.
|
||||
public struct ModelLanguage: Sendable, Hashable, Codable {
|
||||
/// The BCP-47 code, e.g. `de` or `zh-Hant`.
|
||||
public let code: String
|
||||
/// The exact model-card name, e.g. `German` or `Traditional Chinese`.
|
||||
public let modelName: String
|
||||
|
||||
/// Creates a language pair.
|
||||
public init(code: String, modelName: String) {
|
||||
self.code = code
|
||||
self.modelName = modelName
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
|
||||
|
||||
/// Namespace for the SprachmittlerEngines module.
|
||||
public enum SprachmittlerEnginesModule {
|
||||
public static let moduleName = "SprachmittlerEngines"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import Foundation
|
||||
|
||||
/// A testable sleep seam for phase timeouts.
|
||||
public protocol AsyncSleeper: Sendable {
|
||||
/// Sleeps for the duration, or throws `CancellationError` when the task is cancelled.
|
||||
func sleep(for duration: Duration) async throws
|
||||
}
|
||||
|
||||
/// The production sleeper backed by the continuous clock.
|
||||
public struct ContinuousClockSleeper: AsyncSleeper {
|
||||
/// Creates a continuous-clock sleeper.
|
||||
public init() {}
|
||||
|
||||
/// Sleeps for the duration, or throws `CancellationError` when the task is cancelled.
|
||||
public func sleep(for duration: Duration) async throws {
|
||||
try await Task.sleep(for: duration)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/// One event from a streaming `/api/chat` response.
|
||||
public enum ChatEvent: Sendable, Equatable {
|
||||
/// A content delta.
|
||||
case delta(String)
|
||||
/// The final object, with `done_reason` and metrics.
|
||||
case done(reason: String?, metrics: ChatMetrics)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/// One chat message. v1 sends exactly one user message and never a system message.
|
||||
public struct ChatMessage: Sendable, Equatable, Codable {
|
||||
/// The role; always `user` in v1.
|
||||
public let role: String
|
||||
/// The message text (the documented prompt).
|
||||
public let content: String
|
||||
|
||||
/// Creates a message.
|
||||
public init(role: String = "user", content: String) {
|
||||
self.role = role
|
||||
self.content = content
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/// Timing counters from a completed `/api/chat` response. Durations are nanoseconds.
|
||||
public struct ChatMetrics: Sendable, Equatable {
|
||||
/// `total_duration`.
|
||||
public let totalDuration: Int64?
|
||||
/// `load_duration`.
|
||||
public let loadDuration: Int64?
|
||||
/// `prompt_eval_count`.
|
||||
public let promptEvalCount: Int?
|
||||
/// `prompt_eval_duration`.
|
||||
public let promptEvalDuration: Int64?
|
||||
/// `eval_count`.
|
||||
public let evalCount: Int?
|
||||
/// `eval_duration`.
|
||||
public let evalDuration: Int64?
|
||||
|
||||
/// Creates a metrics value.
|
||||
public init(
|
||||
totalDuration: Int64? = nil,
|
||||
loadDuration: Int64? = nil,
|
||||
promptEvalCount: Int? = nil,
|
||||
promptEvalDuration: Int64? = nil,
|
||||
evalCount: Int? = nil,
|
||||
evalDuration: Int64? = nil
|
||||
) {
|
||||
self.totalDuration = totalDuration
|
||||
self.loadDuration = loadDuration
|
||||
self.promptEvalCount = promptEvalCount
|
||||
self.promptEvalDuration = promptEvalDuration
|
||||
self.evalCount = evalCount
|
||||
self.evalDuration = evalDuration
|
||||
}
|
||||
|
||||
/// An empty metrics value for streams that never produced a final object.
|
||||
public static let empty = ChatMetrics()
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/// Ollama sampling options. The names on the wire are the publisher's Ollama names, not the
|
||||
/// model card's names (see docs/OLLAMA_TRANSLATION_API.md §4).
|
||||
public struct ChatOptions: Sendable, Equatable, Codable {
|
||||
/// `temperature`.
|
||||
public let temperature: Double
|
||||
/// `top_p`.
|
||||
public let topP: Double
|
||||
/// `top_k`.
|
||||
public let topK: Int
|
||||
/// `repeat_penalty`.
|
||||
public let repeatPenalty: Double
|
||||
/// `num_predict`.
|
||||
public let numPredict: Int
|
||||
/// `num_ctx`.
|
||||
public let numCtx: Int
|
||||
|
||||
/// Creates options.
|
||||
public init(
|
||||
temperature: Double,
|
||||
topP: Double,
|
||||
topK: Int,
|
||||
repeatPenalty: Double,
|
||||
numPredict: Int,
|
||||
numCtx: Int
|
||||
) {
|
||||
self.temperature = temperature
|
||||
self.topP = topP
|
||||
self.topK = topK
|
||||
self.repeatPenalty = repeatPenalty
|
||||
self.numPredict = numPredict
|
||||
self.numCtx = numCtx
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case temperature
|
||||
case topP = "top_p"
|
||||
case topK = "top_k"
|
||||
case repeatPenalty = "repeat_penalty"
|
||||
case numPredict = "num_predict"
|
||||
case numCtx = "num_ctx"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/// A streaming `/api/chat` request.
|
||||
public struct ChatRequest: Sendable, Equatable, Encodable {
|
||||
/// The model tag.
|
||||
public let model: String
|
||||
/// Exactly one user message in v1.
|
||||
public let messages: [ChatMessage]
|
||||
/// Always true for translation and warm-up.
|
||||
public let stream: Bool
|
||||
/// The Ollama `keep_alive` value.
|
||||
public let keepAlive: String
|
||||
/// The sampling options.
|
||||
public let options: ChatOptions
|
||||
|
||||
/// Creates a request.
|
||||
public init(
|
||||
model: String,
|
||||
messages: [ChatMessage],
|
||||
stream: Bool = true,
|
||||
keepAlive: String = "30m",
|
||||
options: ChatOptions
|
||||
) {
|
||||
self.model = model
|
||||
self.messages = messages
|
||||
self.stream = stream
|
||||
self.keepAlive = keepAlive
|
||||
self.options = options
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case model
|
||||
case messages
|
||||
case stream
|
||||
case keepAlive = "keep_alive"
|
||||
case options
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import Foundation
|
||||
|
||||
/// Owns the stream continuation and the producing task. All state is actor-isolated.
|
||||
actor ChatStreamContext {
|
||||
private let continuation: AsyncThrowingStream<ChatEvent, any Error>.Continuation
|
||||
private var task: Task<Void, Never>?
|
||||
private var finished = false
|
||||
private var sawDone = false
|
||||
private var started = false
|
||||
private var startContinuation: CheckedContinuation<Void, Never>?
|
||||
|
||||
init(continuation: AsyncThrowingStream<ChatEvent, any Error>.Continuation) {
|
||||
self.continuation = continuation
|
||||
}
|
||||
|
||||
/// Blocks the producer until `setTask` has stored its cancellation handle.
|
||||
func waitForStart() async {
|
||||
if started {
|
||||
return
|
||||
}
|
||||
await withCheckedContinuation { continuation in
|
||||
startContinuation = continuation
|
||||
}
|
||||
}
|
||||
|
||||
func setTask(_ task: Task<Void, Never>) {
|
||||
self.task = task
|
||||
started = true
|
||||
startContinuation?.resume()
|
||||
startContinuation = nil
|
||||
if finished {
|
||||
task.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func markDone() {
|
||||
sawDone = true
|
||||
}
|
||||
|
||||
func finishIfDone() {
|
||||
guard !finished else { return }
|
||||
if sawDone {
|
||||
finish()
|
||||
} else {
|
||||
fail(OllamaError.decoding("Stream ended without a done event"))
|
||||
}
|
||||
}
|
||||
|
||||
func emit(_ event: ChatEvent) {
|
||||
guard !finished else { return }
|
||||
continuation.yield(event)
|
||||
}
|
||||
|
||||
func finish() {
|
||||
guard !finished else { return }
|
||||
finished = true
|
||||
continuation.finish()
|
||||
task?.cancel()
|
||||
task = nil
|
||||
}
|
||||
|
||||
func fail(_ error: any Error) {
|
||||
guard !finished else { return }
|
||||
finished = true
|
||||
continuation.finish(throwing: error)
|
||||
task?.cancel()
|
||||
task = nil
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
guard !finished else { return }
|
||||
finished = true
|
||||
continuation.finish()
|
||||
task?.cancel()
|
||||
task = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import Foundation
|
||||
|
||||
/// Schedules one timeout at a time. Scheduling a new phase cancels the previous timer.
|
||||
actor ChatTimeoutController {
|
||||
private let sleeper: any AsyncSleeper
|
||||
private var generation = 0
|
||||
private var task: Task<Void, Never>?
|
||||
private var handler: (@Sendable (TimeoutPhase) -> Void)?
|
||||
|
||||
init(sleeper: any AsyncSleeper) {
|
||||
self.sleeper = sleeper
|
||||
}
|
||||
|
||||
func schedule(
|
||||
_ phase: TimeoutPhase,
|
||||
after duration: Duration,
|
||||
onTimeout: @escaping @Sendable (TimeoutPhase) -> Void
|
||||
) {
|
||||
generation += 1
|
||||
let expected = generation
|
||||
task?.cancel()
|
||||
handler = onTimeout
|
||||
task = Task { [weak self, sleeper] in
|
||||
do {
|
||||
try await sleeper.sleep(for: duration)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
await self?.fire(expected, phase)
|
||||
}
|
||||
}
|
||||
|
||||
private func fire(_ expected: Int, _ phase: TimeoutPhase) {
|
||||
guard expected == generation else { return }
|
||||
handler?(phase)
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
generation += 1
|
||||
task?.cancel()
|
||||
task = nil
|
||||
handler = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/// Per-phase timeout budgets for one chat chunk.
|
||||
public struct ChatTimeouts: Sendable, Equatable {
|
||||
/// Request sent to the first content byte; includes a cold model load.
|
||||
public let firstToken: Duration
|
||||
/// Gap between stream lines once streaming has started.
|
||||
public let idle: Duration
|
||||
/// Hard cap for one chunk.
|
||||
public let total: Duration
|
||||
|
||||
/// Creates a budget.
|
||||
public init(firstToken: Duration, idle: Duration, total: Duration) {
|
||||
self.firstToken = firstToken
|
||||
self.idle = idle
|
||||
self.total = total
|
||||
}
|
||||
|
||||
/// The documented defaults (docs/OLLAMA_TRANSLATION_API.md §1.3).
|
||||
public static let standard = ChatTimeouts(
|
||||
firstToken: .seconds(120),
|
||||
idle: .seconds(20),
|
||||
total: .seconds(180)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import Foundation
|
||||
|
||||
/// Validates the configured Ollama endpoint before any request is built (SP-5, SP-6).
|
||||
public enum EndpointPolicy {
|
||||
/// Returns the validated base URL, or throws `EndpointRejection`.
|
||||
///
|
||||
/// Loopback (`127.0.0.1`, `localhost`, `::1`) may use `http` or `https`. A remote host needs
|
||||
/// the explicit `allowRemote` toggle and `https`.
|
||||
public static func validate(_ url: URL, allowRemote: Bool) throws -> URL {
|
||||
guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else {
|
||||
throw EndpointRejection.scheme
|
||||
}
|
||||
guard url.user == nil, url.password == nil, url.query == nil, url.fragment == nil,
|
||||
let host = url.host?.lowercased(), !host.isEmpty
|
||||
else {
|
||||
throw EndpointRejection.form
|
||||
}
|
||||
if isLoopback(url) {
|
||||
return url
|
||||
}
|
||||
guard allowRemote else {
|
||||
throw EndpointRejection.remoteNotAllowed
|
||||
}
|
||||
guard scheme == "https" else {
|
||||
throw EndpointRejection.remoteRequiresHTTPS
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
/// True for the three loopback spellings the app accepts.
|
||||
public static func isLoopback(_ url: URL) -> Bool {
|
||||
guard let host = url.host?.lowercased() else { return false }
|
||||
return ["127.0.0.1", "localhost", "::1"].contains(host)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/// Why an Ollama endpoint was rejected before any request was sent (SP-5, SP-6).
|
||||
public enum EndpointRejection: Error, Sendable, Equatable {
|
||||
/// The URL scheme is not `http` or `https`.
|
||||
case scheme
|
||||
/// The URL carries user info, a query or a fragment.
|
||||
case form
|
||||
/// A non-loopback endpoint was configured without the explicit remote toggle.
|
||||
case remoteNotAllowed
|
||||
/// A remote endpoint uses `http` instead of `https`.
|
||||
case remoteRequiresHTTPS
|
||||
/// A redirect response was refused.
|
||||
case redirect
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import Foundation
|
||||
|
||||
/// One model returned by `GET /api/tags`.
|
||||
public struct InstalledModel: Sendable, Equatable, Decodable {
|
||||
/// The user-facing tag, e.g. `hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M`.
|
||||
public let name: String
|
||||
/// The tag as Ollama reports it (normally identical to `name`).
|
||||
public let model: String
|
||||
/// The ISO-8601 modification time, when present.
|
||||
public let modifiedAt: String?
|
||||
/// The model size in bytes, when present.
|
||||
public let size: Int64?
|
||||
/// The full sha256 digest.
|
||||
public let digest: String
|
||||
/// The optional family/quantization details.
|
||||
public let details: ModelDetailsInfo?
|
||||
|
||||
/// Creates a model value.
|
||||
public init(
|
||||
name: String,
|
||||
model: String,
|
||||
modifiedAt: String? = nil,
|
||||
size: Int64? = nil,
|
||||
digest: String,
|
||||
details: ModelDetailsInfo? = nil
|
||||
) {
|
||||
self.name = name
|
||||
self.model = model
|
||||
self.modifiedAt = modifiedAt
|
||||
self.size = size
|
||||
self.digest = digest
|
||||
self.details = details
|
||||
}
|
||||
|
||||
/// True when the tag or model name contains `hy-mt3`, case-insensitively.
|
||||
///
|
||||
/// Temporary for the M1 CLI filter; the adapter registry (T2.1) owns family matching in M2.
|
||||
public var isHyMT3: Bool {
|
||||
name.localizedCaseInsensitiveContains("hy-mt3")
|
||||
|| model.localizedCaseInsensitiveContains("hy-mt3")
|
||||
}
|
||||
|
||||
/// `name` with a trailing `:latest` removed.
|
||||
public var normalizedName: String {
|
||||
Self.normalizedName(name)
|
||||
}
|
||||
|
||||
/// Removes only a trailing `:latest`; other tags are preserved.
|
||||
public static func normalizedName(_ name: String) -> String {
|
||||
name.hasSuffix(":latest") ? String(name.dropLast(":latest".count)) : name
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case name
|
||||
case model
|
||||
case modifiedAt = "modified_at"
|
||||
case size
|
||||
case digest
|
||||
case details
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import Foundation
|
||||
|
||||
/// One model returned by `GET /api/ps`.
|
||||
public struct LoadedModel: Sendable, Equatable, Decodable {
|
||||
/// The model tag.
|
||||
public let name: String
|
||||
/// The tag as Ollama reports it, when present.
|
||||
public let model: String?
|
||||
/// The total resident size in bytes.
|
||||
public let size: Int64?
|
||||
/// The resident size in VRAM in bytes.
|
||||
public let sizeVRAM: Int64?
|
||||
/// When Ollama will unload the model.
|
||||
public let expiresAt: String?
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case name
|
||||
case model
|
||||
case size
|
||||
case sizeVRAM = "size_vram"
|
||||
case expiresAt = "expires_at"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import Foundation
|
||||
|
||||
/// The details block returned by `/api/tags` and `/api/show`.
|
||||
public struct ModelDetailsInfo: Sendable, Equatable, Decodable {
|
||||
/// The parent model tag, when reported.
|
||||
public let parentModel: String?
|
||||
/// The format, normally `gguf`.
|
||||
public let format: String?
|
||||
/// The model family, e.g. `hunyuan-dense`.
|
||||
public let family: String?
|
||||
/// All reported families.
|
||||
public let families: [String]?
|
||||
/// The parameter size string, e.g. `7.5B`.
|
||||
public let parameterSize: String?
|
||||
/// The quantization level, e.g. `Q4_K_M`.
|
||||
public let quantizationLevel: String?
|
||||
/// The base context length from `/api/tags` details, when present (the adapter uses 8192).
|
||||
public let contextLength: Int?
|
||||
/// The embedding length from `/api/tags` details, when present.
|
||||
public let embeddingLength: Int?
|
||||
/// The runner name, when reported.
|
||||
public let runner: String?
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case parentModel = "parent_model"
|
||||
case format
|
||||
case family
|
||||
case families
|
||||
case parameterSize = "parameter_size"
|
||||
case quantizationLevel = "quantization_level"
|
||||
case contextLength = "context_length"
|
||||
case embeddingLength = "embedding_length"
|
||||
case runner
|
||||
}
|
||||
}
|
||||
|
||||
/// One parameter line from `/api/show`'s `parameters` string.
|
||||
public struct ModelParameter: Sendable, Equatable {
|
||||
/// The parameter name, e.g. `stop`.
|
||||
public let name: String
|
||||
/// The parameter value with surrounding quotes removed.
|
||||
public let value: String
|
||||
|
||||
/// Creates a parameter.
|
||||
public init(name: String, value: String) {
|
||||
self.name = name
|
||||
self.value = value
|
||||
}
|
||||
|
||||
/// Parses the newline-separated `name value` lines from `/api/show`.
|
||||
public static func parse(_ text: String) -> [ModelParameter] {
|
||||
text.split(separator: "\n").compactMap { line in
|
||||
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||
guard let separator = trimmed.firstIndex(where: { $0 == " " || $0 == "\t" }) else {
|
||||
return nil
|
||||
}
|
||||
let name = String(trimmed[..<separator])
|
||||
var value = String(trimmed[separator...]).trimmingCharacters(in: .whitespaces)
|
||||
if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 {
|
||||
value = String(value.dropFirst().dropLast())
|
||||
}
|
||||
return ModelParameter(name: name, value: value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The fields from `POST /api/show` that v1 uses.
|
||||
public struct ModelDetails: Sendable, Equatable, Decodable {
|
||||
/// Capabilities such as `completion`; empty when omitted.
|
||||
public let capabilities: [String]
|
||||
/// Family and quantization details.
|
||||
public let details: ModelDetailsInfo?
|
||||
/// The raw parameter lines; parse them with `ModelParameter.parse`.
|
||||
public let parameters: String?
|
||||
/// The chat template.
|
||||
public let template: String?
|
||||
/// The server-reported licence; `null` for the current GGUF.
|
||||
public let license: String?
|
||||
|
||||
/// Creates model details.
|
||||
public init(
|
||||
capabilities: [String] = [],
|
||||
details: ModelDetailsInfo? = nil,
|
||||
parameters: String? = nil,
|
||||
template: String? = nil,
|
||||
license: String? = nil
|
||||
) {
|
||||
self.capabilities = capabilities
|
||||
self.details = details
|
||||
self.parameters = parameters
|
||||
self.template = template
|
||||
self.license = license
|
||||
}
|
||||
|
||||
/// The parsed parameter lines, preserving repeated keys such as `stop`.
|
||||
public var parsedParameters: [ModelParameter] {
|
||||
ModelParameter.parse(parameters ?? "")
|
||||
}
|
||||
|
||||
/// True when the model reports text completion.
|
||||
public var supportsCompletion: Bool {
|
||||
capabilities.contains("completion")
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case capabilities
|
||||
case details
|
||||
case parameters
|
||||
case template
|
||||
case license
|
||||
}
|
||||
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
capabilities = try container.decodeIfPresent([String].self, forKey: .capabilities) ?? []
|
||||
details = try container.decodeIfPresent(ModelDetailsInfo.self, forKey: .details)
|
||||
parameters = try container.decodeIfPresent(String.self, forKey: .parameters)
|
||||
template = try container.decodeIfPresent(String.self, forKey: .template)
|
||||
license = try container.decodeIfPresent(String.self, forKey: .license)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/// Model discovery and inspection against a running Ollama server.
|
||||
public protocol OllamaCatalog: Sendable {
|
||||
/// `GET /api/version`.
|
||||
func serverVersion() async throws -> String
|
||||
/// `GET /api/tags`.
|
||||
func installedModels() async throws -> [InstalledModel]
|
||||
/// `POST /api/show`.
|
||||
func show(model: String) async throws -> ModelDetails
|
||||
/// `GET /api/ps`.
|
||||
func loadedModels() async throws -> [LoadedModel]
|
||||
/// Clears the per-digest details cache and the name→digest map after a pull or removal.
|
||||
func refresh() async
|
||||
/// Throws when the server is older than the minimum supported version.
|
||||
func checkMinimumVersion() async throws
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import Foundation
|
||||
|
||||
/// The concrete catalog client. Model details are cached by digest for the app lifetime;
|
||||
/// `refresh()` invalidates the cache after a model pull or removal.
|
||||
public actor OllamaCatalogClient: OllamaCatalog {
|
||||
private let http: any OllamaHTTPTransport
|
||||
private let minimumVersion: OllamaVersion
|
||||
private var detailsByDigest: [String: ModelDetails] = [:]
|
||||
private var digestByName: [String: String] = [:]
|
||||
|
||||
/// Creates a catalog client over an HTTP transport.
|
||||
public init(http: any OllamaHTTPTransport, minimumVersion: OllamaVersion = .minimumSupported) {
|
||||
self.http = http
|
||||
self.minimumVersion = minimumVersion
|
||||
}
|
||||
|
||||
public func serverVersion() async throws -> String {
|
||||
let response = try await http.send(.init(path: "/api/version"), model: nil)
|
||||
return try decode(VersionResponse.self, from: response).version
|
||||
}
|
||||
|
||||
public func installedModels() async throws -> [InstalledModel] {
|
||||
let response = try await http.send(.init(path: "/api/tags"), model: nil)
|
||||
let models = try decode(TagsResponse.self, from: response).models
|
||||
digestByName = models.reduce(into: [:]) { result, model in
|
||||
result[model.normalizedName] = model.digest
|
||||
}
|
||||
return models
|
||||
}
|
||||
|
||||
public func show(model: String) async throws -> ModelDetails {
|
||||
let normalized = InstalledModel.normalizedName(model)
|
||||
if digestByName[normalized] == nil {
|
||||
_ = try await installedModels()
|
||||
}
|
||||
|
||||
if let digest = digestByName[normalized], let cached = detailsByDigest[digest] {
|
||||
return cached
|
||||
}
|
||||
|
||||
let body = try JSONEncoder().encode(ShowRequest(model: model))
|
||||
let request = OllamaHTTPRequest(method: .post, path: "/api/show", body: body)
|
||||
let response = try await http.send(request, model: model)
|
||||
let details = try decode(ModelDetails.self, from: response)
|
||||
if let digest = digestByName[normalized] {
|
||||
detailsByDigest[digest] = details
|
||||
}
|
||||
return details
|
||||
}
|
||||
|
||||
public func loadedModels() async throws -> [LoadedModel] {
|
||||
let response = try await http.send(.init(path: "/api/ps"), model: nil)
|
||||
return try decode(PsResponse.self, from: response).models
|
||||
}
|
||||
|
||||
/// Clears the per-digest details cache and the name→digest map.
|
||||
public func refresh() async {
|
||||
detailsByDigest.removeAll()
|
||||
digestByName.removeAll()
|
||||
}
|
||||
|
||||
/// Throws `OllamaError.unsupportedVersion` when the server is older than the minimum.
|
||||
public func checkMinimumVersion() async throws {
|
||||
let found = try await serverVersion()
|
||||
guard let parsed = OllamaVersion(found), parsed >= minimumVersion else {
|
||||
throw OllamaError.unsupportedVersion(
|
||||
found: found,
|
||||
required: minimumVersion.description
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func decode<Value: Decodable>(
|
||||
_ type: Value.Type,
|
||||
from response: OllamaHTTPResponse
|
||||
) throws -> Value {
|
||||
do {
|
||||
return try JSONDecoder().decode(type, from: response.body)
|
||||
} catch {
|
||||
throw OllamaError.decoding("Invalid \(type) response")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct VersionResponse: Decodable {
|
||||
let version: String
|
||||
}
|
||||
|
||||
private struct TagsResponse: Decodable {
|
||||
let models: [InstalledModel]
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case models
|
||||
}
|
||||
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
models = try container.decodeIfPresent([InstalledModel].self, forKey: .models) ?? []
|
||||
}
|
||||
}
|
||||
|
||||
private struct PsResponse: Decodable {
|
||||
let models: [LoadedModel]
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case models
|
||||
}
|
||||
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
models = try container.decodeIfPresent([LoadedModel].self, forKey: .models) ?? []
|
||||
}
|
||||
}
|
||||
|
||||
private struct ShowRequest: Encodable {
|
||||
let model: String
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import Foundation
|
||||
|
||||
/// The streaming Ollama chat client. One task reads NDJSON lines; a timeout controller guards
|
||||
/// first-token, idle and total phases.
|
||||
public struct OllamaChatClient: OllamaChatting, Sendable {
|
||||
private let http: OllamaHTTPClient
|
||||
private let sleeper: any AsyncSleeper
|
||||
private let timeouts: ChatTimeouts
|
||||
|
||||
/// Creates a chat client.
|
||||
public init(
|
||||
http: OllamaHTTPClient,
|
||||
sleeper: any AsyncSleeper = ContinuousClockSleeper(),
|
||||
timeouts: ChatTimeouts = .standard
|
||||
) {
|
||||
self.http = http
|
||||
self.sleeper = sleeper
|
||||
self.timeouts = timeouts
|
||||
}
|
||||
|
||||
/// Streams deltas and one final `done` event. Throws `OllamaError` on failure.
|
||||
public func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error> {
|
||||
AsyncThrowingStream { continuation in
|
||||
let context = ChatStreamContext(continuation: continuation)
|
||||
let task = Task {
|
||||
await context.waitForStart()
|
||||
await run(request, context: context)
|
||||
}
|
||||
Task {
|
||||
await context.setTask(task)
|
||||
}
|
||||
continuation.onTermination = { @Sendable _ in
|
||||
task.cancel()
|
||||
Task {
|
||||
await context.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func run(_ request: ChatRequest, context: ChatStreamContext) async {
|
||||
if Task.isCancelled {
|
||||
await context.cancel()
|
||||
return
|
||||
}
|
||||
let phase = ChatTimeoutController(sleeper: sleeper)
|
||||
let total = ChatTimeoutController(sleeper: sleeper)
|
||||
|
||||
do {
|
||||
let body = try JSONEncoder().encode(request)
|
||||
let httpRequest = OllamaHTTPRequest(method: .post, path: "/api/chat", body: body)
|
||||
|
||||
await phase.schedule(.firstToken, after: timeouts.firstToken) { phase in
|
||||
Task {
|
||||
await context.fail(OllamaError.timeout(phase))
|
||||
}
|
||||
}
|
||||
await total.schedule(.total, after: timeouts.total) { phase in
|
||||
Task {
|
||||
await context.fail(OllamaError.timeout(phase))
|
||||
}
|
||||
}
|
||||
|
||||
try await http.stream(httpRequest, model: request.model) { line in
|
||||
try await handle(
|
||||
line,
|
||||
request: request,
|
||||
context: context,
|
||||
phase: phase,
|
||||
total: total
|
||||
)
|
||||
}
|
||||
await context.finishIfDone()
|
||||
} catch let error as OllamaError {
|
||||
if case .cancelled = error {
|
||||
await context.cancel()
|
||||
} else {
|
||||
await context.fail(error)
|
||||
}
|
||||
} catch is CancellationError {
|
||||
await context.cancel()
|
||||
} catch {
|
||||
await context.fail(OllamaError.decoding("Stream failed"))
|
||||
}
|
||||
|
||||
await phase.cancel()
|
||||
await total.cancel()
|
||||
}
|
||||
|
||||
private func handle(
|
||||
_ line: String,
|
||||
request: ChatRequest,
|
||||
context: ChatStreamContext,
|
||||
phase: ChatTimeoutController,
|
||||
total: ChatTimeoutController
|
||||
) async throws -> StreamLineAction {
|
||||
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else {
|
||||
return .continueStream
|
||||
}
|
||||
guard let data = trimmed.data(using: .utf8) else {
|
||||
throw OllamaError.decoding("Invalid stream line")
|
||||
}
|
||||
|
||||
let object: StreamLine
|
||||
do {
|
||||
object = try JSONDecoder().decode(StreamLine.self, from: data)
|
||||
} catch {
|
||||
throw OllamaError.decoding("Invalid stream line")
|
||||
}
|
||||
|
||||
if let message = object.error, !message.isEmpty {
|
||||
throw streamError(message, model: request.model)
|
||||
}
|
||||
|
||||
if let content = object.message?.content, !content.isEmpty {
|
||||
await phase.schedule(.idle, after: timeouts.idle) { phase in
|
||||
Task {
|
||||
await context.fail(OllamaError.timeout(phase))
|
||||
}
|
||||
}
|
||||
await context.emit(.delta(content))
|
||||
}
|
||||
|
||||
if object.done == true {
|
||||
await phase.cancel()
|
||||
await total.cancel()
|
||||
// Unknown done_reason values are passed through unchanged. Logging them at .info
|
||||
// needs an injected logger in M2/M4.
|
||||
await context.markDone()
|
||||
await context.emit(.done(reason: object.doneReason, metrics: object.metrics))
|
||||
await context.finish()
|
||||
return .stop
|
||||
}
|
||||
|
||||
return .continueStream
|
||||
}
|
||||
|
||||
private func streamError(_ message: String, model: String) -> OllamaError {
|
||||
if message.localizedCaseInsensitiveContains("not found") {
|
||||
return .modelNotInstalled(model)
|
||||
}
|
||||
return .server(status: 0, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
/// One NDJSON object from `/api/chat`.
|
||||
private struct StreamLine: Decodable {
|
||||
struct Message: Decodable {
|
||||
let content: String?
|
||||
}
|
||||
|
||||
let message: Message?
|
||||
let done: Bool?
|
||||
let doneReason: String?
|
||||
let error: String?
|
||||
let totalDuration: Int64?
|
||||
let loadDuration: Int64?
|
||||
let promptEvalCount: Int?
|
||||
let promptEvalDuration: Int64?
|
||||
let evalCount: Int?
|
||||
let evalDuration: Int64?
|
||||
|
||||
var metrics: ChatMetrics {
|
||||
ChatMetrics(
|
||||
totalDuration: totalDuration,
|
||||
loadDuration: loadDuration,
|
||||
promptEvalCount: promptEvalCount,
|
||||
promptEvalDuration: promptEvalDuration,
|
||||
evalCount: evalCount,
|
||||
evalDuration: evalDuration
|
||||
)
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case message
|
||||
case done
|
||||
case doneReason = "done_reason"
|
||||
case error
|
||||
case totalDuration = "total_duration"
|
||||
case loadDuration = "load_duration"
|
||||
case promptEvalCount = "prompt_eval_count"
|
||||
case promptEvalDuration = "prompt_eval_duration"
|
||||
case evalCount = "eval_count"
|
||||
case evalDuration = "eval_duration"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/// The streaming chat contract from ARCHITECTURE §8.1.
|
||||
public protocol OllamaChatting: Sendable {
|
||||
/// Streams deltas and one final `done` event. Throws `OllamaError` on failure.
|
||||
func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error>
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import Foundation
|
||||
|
||||
/// Transport-, policy- and HTTP-level failures from the Ollama client.
|
||||
///
|
||||
/// This is the leaf module's error vocabulary. `SprachmittlerCore` maps it to
|
||||
/// `SprachmittlerError` at the boundary; the leaf never depends on Core.
|
||||
public enum OllamaError: Error, Sendable, Equatable {
|
||||
/// The endpoint failed `EndpointPolicy` or a redirect was refused.
|
||||
case endpointRejected(EndpointRejection)
|
||||
/// Connection refused, host unreachable or another transport failure.
|
||||
case unreachable(URL)
|
||||
/// A 404 whose body says the model was not found.
|
||||
case modelNotInstalled(String)
|
||||
/// A 400-class request problem, with a truncated server message.
|
||||
case badRequest(String)
|
||||
/// Any other non-2xx status, with a truncated server message.
|
||||
case server(status: Int, message: String)
|
||||
/// A timeout in the given phase.
|
||||
case timeout(TimeoutPhase)
|
||||
/// The task was cancelled.
|
||||
case cancelled
|
||||
/// A response body could not be decoded.
|
||||
case decoding(String)
|
||||
/// The Ollama server is older than the minimum supported version.
|
||||
case unsupportedVersion(found: String, required: String)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import Foundation
|
||||
|
||||
/// Extracts a short, non-user-facing message from an Ollama error body.
|
||||
///
|
||||
/// The body is `{"error":"…"}`; plain text is accepted as a fallback. The result is capped at
|
||||
/// 500 characters and is never shown raw to the user or logged in clear.
|
||||
enum OllamaErrorBody {
|
||||
static func message(from data: Data) -> String? {
|
||||
if let envelope = try? JSONDecoder().decode(ErrorEnvelope.self, from: data), !envelope.error.isEmpty {
|
||||
return truncate(envelope.error)
|
||||
}
|
||||
guard let text = String(data: data, encoding: .utf8)?
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||
!text.isEmpty
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
return truncate(text)
|
||||
}
|
||||
|
||||
private static func truncate(_ value: String) -> String {
|
||||
value.count > 500 ? String(value.prefix(500)) : value
|
||||
}
|
||||
|
||||
private struct ErrorEnvelope: Decodable {
|
||||
let error: String
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import Foundation
|
||||
|
||||
/// The JSON HTTP client for Ollama. The only module that builds `URLRequest`s and owns a
|
||||
/// `URLSession` (SP-4, SP-6).
|
||||
public final class OllamaHTTPClient: OllamaHTTPTransport, Sendable {
|
||||
/// The validated base URL, e.g. `http://127.0.0.1:11434`.
|
||||
public let baseURL: URL
|
||||
|
||||
let session: URLSession
|
||||
|
||||
/// Creates a client with an ephemeral session and a redirect-refusing delegate.
|
||||
public init(baseURL: URL, allowRemote: Bool = false) throws {
|
||||
let validated: URL
|
||||
do {
|
||||
validated = try EndpointPolicy.validate(baseURL, allowRemote: allowRemote)
|
||||
} catch let rejection as EndpointRejection {
|
||||
throw OllamaError.endpointRejected(rejection)
|
||||
}
|
||||
self.baseURL = validated
|
||||
session = URLSession(
|
||||
configuration: OllamaSessionFactory.makeConfiguration(),
|
||||
delegate: RedirectRefusingDelegate(),
|
||||
delegateQueue: nil
|
||||
)
|
||||
}
|
||||
|
||||
/// Test seam: inject a session with a `URLProtocol` stub.
|
||||
init(baseURL: URL, session: URLSession) throws {
|
||||
let validated: URL
|
||||
do {
|
||||
validated = try EndpointPolicy.validate(baseURL, allowRemote: false)
|
||||
} catch let rejection as EndpointRejection {
|
||||
throw OllamaError.endpointRejected(rejection)
|
||||
}
|
||||
self.baseURL = validated
|
||||
self.session = session
|
||||
}
|
||||
|
||||
deinit {
|
||||
session.invalidateAndCancel()
|
||||
}
|
||||
|
||||
/// Sends a request and returns a 2xx response. Non-2xx statuses and transport failures are
|
||||
/// mapped to `OllamaError`.
|
||||
///
|
||||
/// - Parameter model: the model tag for a 404 body check; pass it for chat/show requests.
|
||||
public func send(_ request: OllamaHTTPRequest, model: String? = nil) async throws -> OllamaHTTPResponse {
|
||||
let url = try makeURL(for: request.path)
|
||||
let urlRequest = try makeURLRequest(request)
|
||||
|
||||
do {
|
||||
let (data, response) = try await session.data(for: urlRequest)
|
||||
guard let http = response as? HTTPURLResponse else {
|
||||
throw OllamaError.decoding("Non-HTTP response")
|
||||
}
|
||||
if (300 ..< 400).contains(http.statusCode) {
|
||||
throw OllamaError.endpointRejected(.redirect)
|
||||
}
|
||||
guard (200 ..< 300).contains(http.statusCode) else {
|
||||
throw httpError(status: http.statusCode, data: data, model: model)
|
||||
}
|
||||
return OllamaHTTPResponse(status: http.statusCode, body: data)
|
||||
} catch let error as OllamaError {
|
||||
throw error
|
||||
} catch let error as URLError {
|
||||
throw transportError(error, url: url)
|
||||
} catch is CancellationError {
|
||||
throw OllamaError.cancelled
|
||||
} catch {
|
||||
throw OllamaError.decoding("Request failed")
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends a request and decodes a JSON response.
|
||||
public func sendJSON<Response: Decodable>(
|
||||
_ request: OllamaHTTPRequest,
|
||||
as type: Response.Type,
|
||||
model: String? = nil
|
||||
) async throws -> Response {
|
||||
let response = try await send(request, model: model)
|
||||
do {
|
||||
return try JSONDecoder().decode(Response.self, from: response.body)
|
||||
} catch {
|
||||
throw OllamaError.decoding("Invalid JSON response")
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams NDJSON lines from a request. The caller decides when to stop after a `done` line.
|
||||
func stream(
|
||||
_ request: OllamaHTTPRequest,
|
||||
model: String?,
|
||||
onLine: @escaping @Sendable (String) async throws -> StreamLineAction
|
||||
) async throws {
|
||||
let url = try makeURL(for: request.path)
|
||||
let urlRequest = try makeURLRequest(request)
|
||||
|
||||
do {
|
||||
let (bytes, response) = try await session.bytes(for: urlRequest)
|
||||
guard let http = response as? HTTPURLResponse else {
|
||||
throw OllamaError.decoding("Non-HTTP response")
|
||||
}
|
||||
try await validateStreamResponse(http, bytes: bytes, model: model)
|
||||
var lines = bytes.lines.makeAsyncIterator()
|
||||
while let line = try await lines.next() {
|
||||
if try await onLine(line) == .stop {
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch let error as OllamaError {
|
||||
throw error
|
||||
} catch let error as URLError {
|
||||
throw transportError(error, url: url)
|
||||
} catch is CancellationError {
|
||||
throw OllamaError.cancelled
|
||||
} catch {
|
||||
throw OllamaError.decoding("Stream failed")
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the request URL without producing `//` at the base-path boundary.
|
||||
func makeURL(for path: String) throws -> URL {
|
||||
guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else {
|
||||
throw OllamaError.decoding("Invalid base URL")
|
||||
}
|
||||
let requestPath = path.hasPrefix("/") ? path : "/" + path
|
||||
let basePath = components.path
|
||||
if basePath.isEmpty || basePath == "/" {
|
||||
components.path = requestPath
|
||||
} else if basePath.hasSuffix("/") {
|
||||
components.path = String(basePath.dropLast()) + requestPath
|
||||
} else {
|
||||
components.path = basePath + requestPath
|
||||
}
|
||||
guard let url = components.url else {
|
||||
throw OllamaError.decoding("Invalid request URL")
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
private func validateStreamResponse(
|
||||
_ http: HTTPURLResponse,
|
||||
bytes: URLSession.AsyncBytes,
|
||||
model: String?
|
||||
) async throws {
|
||||
if (300 ..< 400).contains(http.statusCode) {
|
||||
throw OllamaError.endpointRejected(.redirect)
|
||||
}
|
||||
guard (200 ..< 300).contains(http.statusCode) else {
|
||||
var data = Data()
|
||||
for try await byte in bytes {
|
||||
guard data.count < 4096 else { break }
|
||||
data.append(byte)
|
||||
}
|
||||
throw httpError(status: http.statusCode, data: data, model: model)
|
||||
}
|
||||
}
|
||||
|
||||
private func makeURLRequest(_ request: OllamaHTTPRequest) throws -> URLRequest {
|
||||
let url = try makeURL(for: request.path)
|
||||
var urlRequest = URLRequest(url: url)
|
||||
urlRequest.httpMethod = request.method.rawValue
|
||||
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
|
||||
if let body = request.body {
|
||||
urlRequest.httpBody = body
|
||||
urlRequest.setValue(
|
||||
request.contentType ?? "application/json",
|
||||
forHTTPHeaderField: "Content-Type"
|
||||
)
|
||||
}
|
||||
return urlRequest
|
||||
}
|
||||
|
||||
private func httpError(status: Int, data: Data, model: String?) -> OllamaError {
|
||||
let message = OllamaErrorBody.message(from: data) ?? ""
|
||||
if status == 404, let model, message.localizedCaseInsensitiveContains("not found") {
|
||||
return .modelNotInstalled(model)
|
||||
}
|
||||
if status == 400 {
|
||||
return .badRequest(message)
|
||||
}
|
||||
return .server(status: status, message: message)
|
||||
}
|
||||
|
||||
private func transportError(_ error: URLError, url: URL) -> OllamaError {
|
||||
switch error.code {
|
||||
case .cancelled:
|
||||
.cancelled
|
||||
case .timedOut:
|
||||
.timeout(.connect)
|
||||
case .cannotConnectToHost, .cannotFindHost, .dnsLookupFailed,
|
||||
.networkConnectionLost, .notConnectedToInternet:
|
||||
.unreachable(url)
|
||||
default:
|
||||
.unreachable(url)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import Foundation
|
||||
|
||||
/// The HTTP methods the Ollama API uses in v1.
|
||||
public enum OllamaHTTPMethod: String, Sendable {
|
||||
case get = "GET"
|
||||
case post = "POST"
|
||||
}
|
||||
|
||||
/// A transport-independent Ollama request.
|
||||
public struct OllamaHTTPRequest: Sendable, Equatable {
|
||||
/// The HTTP method.
|
||||
public let method: OllamaHTTPMethod
|
||||
/// The path below the configured base URL, e.g. `/api/version`.
|
||||
public let path: String
|
||||
/// An optional JSON body.
|
||||
public let body: Data?
|
||||
/// The body content type; defaults to `application/json` when a body is present.
|
||||
public let contentType: String?
|
||||
|
||||
/// Creates a request.
|
||||
public init(
|
||||
method: OllamaHTTPMethod = .get,
|
||||
path: String,
|
||||
body: Data? = nil,
|
||||
contentType: String? = nil
|
||||
) {
|
||||
self.method = method
|
||||
self.path = path
|
||||
self.body = body
|
||||
self.contentType = contentType
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import Foundation
|
||||
|
||||
/// A successful HTTP response from Ollama.
|
||||
public struct OllamaHTTPResponse: Sendable, Equatable {
|
||||
/// The HTTP status code.
|
||||
public let status: Int
|
||||
/// The response body.
|
||||
public let body: Data
|
||||
|
||||
/// Creates a response value.
|
||||
public init(status: Int, body: Data) {
|
||||
self.status = status
|
||||
self.body = body
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/// A transport seam so catalog and chat tests can run without a live socket.
|
||||
public protocol OllamaHTTPTransport: Sendable {
|
||||
/// Sends one request and returns a 2xx response, throwing `OllamaError` otherwise.
|
||||
///
|
||||
/// - Parameter model: the model tag for a 404 body check; pass it for chat/show requests.
|
||||
func send(_ request: OllamaHTTPRequest, model: String?) async throws -> OllamaHTTPResponse
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import Foundation
|
||||
|
||||
/// The privacy-preserving `URLSession` configuration for every Ollama request (SP-6).
|
||||
public enum OllamaSessionFactory {
|
||||
/// An ephemeral configuration with no cookies, cache or credential storage.
|
||||
public static func makeConfiguration() -> URLSessionConfiguration {
|
||||
let configuration = URLSessionConfiguration.ephemeral
|
||||
configuration.httpCookieStorage = nil
|
||||
configuration.urlCache = nil
|
||||
configuration.urlCredentialStorage = nil
|
||||
configuration.httpShouldSetCookies = false
|
||||
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
|
||||
configuration.waitsForConnectivity = false
|
||||
// Never let URLSession's default 60 s request timeout pre-empt the documented 120 s
|
||||
// first-token budget (which includes a cold model load). The chat client enforces the
|
||||
// finer phases.
|
||||
configuration.timeoutIntervalForRequest = 180
|
||||
configuration.timeoutIntervalForResource = 180
|
||||
return configuration
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import Foundation
|
||||
|
||||
/// A comparable Ollama version such as `0.40.18`.
|
||||
public struct OllamaVersion: Comparable, Sendable, CustomStringConvertible {
|
||||
/// The numeric components, e.g. `[0, 40, 18]`.
|
||||
public let components: [Int]
|
||||
|
||||
/// The minimum supported server version (ARCHITECTURE §2).
|
||||
public static let minimumSupported = OllamaVersion(components: [0, 40, 0])
|
||||
|
||||
/// Parses a dotted numeric version. Returns nil for non-numeric or empty input.
|
||||
public init?(_ string: String) {
|
||||
let withoutBuild = string.split(separator: "+", maxSplits: 1).first.map(String.init) ?? string
|
||||
let core = withoutBuild.split(separator: "-", maxSplits: 1).first.map(String.init) ?? withoutBuild
|
||||
let parts = core.split(separator: ".").map { Int($0) }
|
||||
guard !parts.isEmpty, parts.allSatisfy({ $0 != nil }) else {
|
||||
return nil
|
||||
}
|
||||
components = parts.compactMap(\.self)
|
||||
}
|
||||
|
||||
private init(components: [Int]) {
|
||||
self.components = components
|
||||
}
|
||||
|
||||
/// The dotted representation.
|
||||
public var description: String {
|
||||
components.map(String.init).joined(separator: ".")
|
||||
}
|
||||
|
||||
/// Component-wise comparison, padding the shorter version with zeros.
|
||||
public static func < (lhs: OllamaVersion, rhs: OllamaVersion) -> Bool {
|
||||
let count = max(lhs.components.count, rhs.components.count)
|
||||
for index in 0 ..< count {
|
||||
let left = index < lhs.components.count ? lhs.components[index] : 0
|
||||
let right = index < rhs.components.count ? rhs.components[index] : 0
|
||||
if left != right {
|
||||
return left < right
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// Equality treats `0.40` and `0.40.0` as the same version.
|
||||
public static func == (lhs: OllamaVersion, rhs: OllamaVersion) -> Bool {
|
||||
!(lhs < rhs) && !(rhs < lhs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import Foundation
|
||||
|
||||
/// Warm-up is allowed only for a loopback endpoint and only when the user enabled it.
|
||||
public enum OllamaWarmUpPolicy {
|
||||
/// Returns true only for a local endpoint with warm-up enabled.
|
||||
public static func shouldWarmUp(endpoint: URL, enabled: Bool) -> Bool {
|
||||
enabled && EndpointPolicy.isLoopback(endpoint)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/// Runs a warm-up or unload request and discards the streamed output.
|
||||
public struct OllamaWarmUpRunner: Sendable {
|
||||
private let chat: any OllamaChatting
|
||||
|
||||
/// Creates a runner over a chat client.
|
||||
public init(chat: any OllamaChatting) {
|
||||
self.chat = chat
|
||||
}
|
||||
|
||||
/// Runs the request to completion; never returns or stores the output.
|
||||
public func run(_ request: ChatRequest) async throws {
|
||||
for try await _ in chat.chat(request) {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import Foundation
|
||||
|
||||
/// Cancels every HTTP redirect. The Ollama endpoint is fixed; a redirect could move the request
|
||||
/// to a different host and leak text. Immutable, stateless, and only implements the delegate
|
||||
/// method, so `@unchecked Sendable` is safe.
|
||||
final class RedirectRefusingDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
|
||||
func urlSession(
|
||||
_ session: URLSession,
|
||||
task: URLSessionTask,
|
||||
willPerformHTTPRedirection response: HTTPURLResponse,
|
||||
newRequest request: URLRequest,
|
||||
completionHandler: @escaping (URLRequest?) -> Void
|
||||
) {
|
||||
completionHandler(nil)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
|
||||
|
||||
/// Namespace for the SprachmittlerOllama module.
|
||||
public enum SprachmittlerOllamaModule {
|
||||
public static let moduleName = "SprachmittlerOllama"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/// Whether a streaming reader should continue after handling one NDJSON line.
|
||||
enum StreamLineAction: Sendable, Equatable {
|
||||
case continueStream
|
||||
case stop
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/// The phase in which an Ollama request timed out.
|
||||
public enum TimeoutPhase: Sendable, Equatable {
|
||||
/// TCP connect plus TLS.
|
||||
case connect
|
||||
/// Request sent until the first content byte; includes a cold model load.
|
||||
case firstToken
|
||||
/// Gap between stream lines once streaming has started.
|
||||
case idle
|
||||
/// Hard cap for one chunk.
|
||||
case total
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// A catalog fake backed by fixed values.
|
||||
public struct FakeOllamaCatalog: OllamaCatalog, Sendable {
|
||||
/// The reported server version.
|
||||
public let version: String
|
||||
/// The installed models.
|
||||
public let models: [InstalledModel]
|
||||
/// Details by model tag.
|
||||
public let details: [String: ModelDetails]
|
||||
/// The loaded models.
|
||||
public let loaded: [LoadedModel]
|
||||
|
||||
/// Creates a catalog fake.
|
||||
public init(
|
||||
version: String = "0.40.18",
|
||||
models: [InstalledModel] = [],
|
||||
details: [String: ModelDetails] = [:],
|
||||
loaded: [LoadedModel] = []
|
||||
) {
|
||||
self.version = version
|
||||
self.models = models
|
||||
self.details = details
|
||||
self.loaded = loaded
|
||||
}
|
||||
|
||||
public func serverVersion() async throws -> String {
|
||||
version
|
||||
}
|
||||
|
||||
public func installedModels() async throws -> [InstalledModel] {
|
||||
models
|
||||
}
|
||||
|
||||
public func show(model: String) async throws -> ModelDetails {
|
||||
guard let details = details[model] else {
|
||||
throw OllamaError.modelNotInstalled(model)
|
||||
}
|
||||
return details
|
||||
}
|
||||
|
||||
public func loadedModels() async throws -> [LoadedModel] {
|
||||
loaded
|
||||
}
|
||||
|
||||
public func refresh() async {}
|
||||
|
||||
public func checkMinimumVersion() async throws {
|
||||
guard let parsed = OllamaVersion(version), parsed >= .minimumSupported else {
|
||||
throw OllamaError.unsupportedVersion(
|
||||
found: version,
|
||||
required: OllamaVersion.minimumSupported.description
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// A chat fake that emits a fixed event list and records the request through a caller closure.
|
||||
public struct FakeOllamaChat: OllamaChatting, Sendable {
|
||||
/// The events emitted for every chat call.
|
||||
public let events: [ChatEvent]
|
||||
/// Called synchronously with each request.
|
||||
public let onRequest: @Sendable (ChatRequest) -> Void
|
||||
|
||||
/// Creates a fake chat.
|
||||
public init(
|
||||
events: [ChatEvent] = [.done(reason: "stop", metrics: .empty)],
|
||||
onRequest: @escaping @Sendable (ChatRequest) -> Void = { _ in }
|
||||
) {
|
||||
self.events = events
|
||||
self.onRequest = onRequest
|
||||
}
|
||||
|
||||
public func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error> {
|
||||
onRequest(request)
|
||||
return AsyncThrowingStream { continuation in
|
||||
for event in events {
|
||||
continuation.yield(event)
|
||||
}
|
||||
continuation.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// A transport fake for catalog and chat tests. It records every request and answers through a
|
||||
/// caller-supplied handler.
|
||||
public actor FakeOllamaHTTPTransport: OllamaHTTPTransport {
|
||||
/// The reply function.
|
||||
public typealias Handler = @Sendable (OllamaHTTPRequest) throws -> OllamaHTTPResponse
|
||||
|
||||
private let handler: Handler
|
||||
/// Every request seen, in order.
|
||||
public private(set) var requests: [OllamaHTTPRequest] = []
|
||||
/// The model argument supplied with each request, in order.
|
||||
public private(set) var models: [String?] = []
|
||||
|
||||
/// Creates a fake with the given reply handler.
|
||||
public init(handler: @escaping Handler) {
|
||||
self.handler = handler
|
||||
}
|
||||
|
||||
public func send(_ request: OllamaHTTPRequest, model: String?) async throws -> OllamaHTTPResponse {
|
||||
requests.append(request)
|
||||
models.append(model)
|
||||
return try handler(request)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// A manual sleeper for timeout tests: no real time passes. Tests wait for a pending duration
|
||||
/// and advance it explicitly.
|
||||
public actor ManualSleeper: AsyncSleeper {
|
||||
private struct Waiter {
|
||||
let duration: Duration
|
||||
let continuation: CheckedContinuation<Void, any Error>
|
||||
}
|
||||
|
||||
private var waiters: [UUID: Waiter] = [:]
|
||||
private var observers: [Duration: [CheckedContinuation<Void, Never>]] = [:]
|
||||
|
||||
/// Creates a manual sleeper.
|
||||
public init() {}
|
||||
|
||||
public func sleep(for duration: Duration) async throws {
|
||||
if Task.isCancelled {
|
||||
throw CancellationError()
|
||||
}
|
||||
let id = UUID()
|
||||
try await withTaskCancellationHandler {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
waiters[id] = Waiter(duration: duration, continuation: continuation)
|
||||
let pending = observers.removeValue(forKey: duration) ?? []
|
||||
pending.forEach { $0.resume() }
|
||||
}
|
||||
} onCancel: {
|
||||
Task {
|
||||
await self.cancel(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Suspends until a sleep for `duration` is waiting.
|
||||
public func waitUntilPending(_ duration: Duration) async {
|
||||
if waiters.values.contains(where: { $0.duration == duration }) {
|
||||
return
|
||||
}
|
||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||
observers[duration, default: []].append(continuation)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resumes every sleep waiting for `duration`.
|
||||
public func advance(matching duration: Duration) {
|
||||
let matching = waiters.filter { $0.value.duration == duration }
|
||||
for (id, waiter) in matching {
|
||||
waiters.removeValue(forKey: id)
|
||||
waiter.continuation.resume()
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of sleepers currently waiting for `duration`.
|
||||
public func pendingCount(_ duration: Duration) -> Int {
|
||||
waiters.values.filter { $0.duration == duration }.count
|
||||
}
|
||||
|
||||
private func cancel(_ id: UUID) {
|
||||
guard let waiter = waiters.removeValue(forKey: id) else { return }
|
||||
waiter.continuation.resume(throwing: CancellationError())
|
||||
}
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
// Placeholder so the target compiles. Replace during T0.1+ (see docs/IMPLEMENTATION_PLAN.md).
|
||||
|
||||
/// Namespace for the SprachmittlerTestSupport module.
|
||||
public enum SprachmittlerTestSupportModule {
|
||||
public static let moduleName = "SprachmittlerTestSupport"
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
/// The CLI composition root. Concrete clients are created only here (CODING_STANDARDS).
|
||||
struct CLIEnvironment: Sendable {
|
||||
let baseURL: URL
|
||||
let allowRemote: Bool
|
||||
|
||||
func makeHTTPClient() throws -> OllamaHTTPClient {
|
||||
try OllamaHTTPClient(baseURL: baseURL, allowRemote: allowRemote)
|
||||
}
|
||||
|
||||
func makeCatalog() throws -> any OllamaCatalog {
|
||||
try OllamaCatalogClient(http: makeHTTPClient())
|
||||
}
|
||||
|
||||
func makeChatClient() throws -> OllamaChatClient {
|
||||
try OllamaChatClient(http: makeHTTPClient())
|
||||
}
|
||||
|
||||
func makeRequestFactory(model: String) -> HyMT3RequestFactory {
|
||||
HyMT3RequestFactory(model: model)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
|
||||
enum CLIError {
|
||||
static func perform(_ operation: () async throws -> Void) async throws {
|
||||
do {
|
||||
try await operation()
|
||||
} catch let exit as ExitCode {
|
||||
throw exit
|
||||
} catch let error as OllamaError {
|
||||
writeError(message(for: error))
|
||||
throw ExitCode(exitCode(for: error))
|
||||
} catch let rejection as EndpointRejection {
|
||||
// Defensive: EndpointPolicy may be called directly outside OllamaHTTPClient.
|
||||
writeError(message(for: rejection))
|
||||
throw ExitCode(2)
|
||||
} catch let validation as ValidationError {
|
||||
writeError(String(describing: validation))
|
||||
throw ExitCode(2)
|
||||
} catch {
|
||||
writeError("Error: \(error)")
|
||||
throw ExitCode(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// 2 = endpoint/usage, 3 = unreachable, 4 = model missing, 1 = other runtime failure.
|
||||
static func exitCode(for error: OllamaError) -> Int32 {
|
||||
switch error {
|
||||
case .endpointRejected:
|
||||
2
|
||||
case .unreachable:
|
||||
3
|
||||
case .modelNotInstalled:
|
||||
4
|
||||
default:
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
static func message(for error: OllamaError) -> String {
|
||||
switch error {
|
||||
case let .endpointRejected(reason):
|
||||
"Endpoint rejected: \(message(for: reason))"
|
||||
case let .unreachable(url):
|
||||
"Ollama is not reachable at \(url.absoluteString)."
|
||||
case let .modelNotInstalled(model):
|
||||
"Model not installed: \(model)"
|
||||
case .badRequest:
|
||||
"Ollama rejected the request."
|
||||
case let .server(status, _):
|
||||
"Ollama returned HTTP \(status)."
|
||||
case .timeout:
|
||||
"Timed out while talking to Ollama."
|
||||
case .cancelled:
|
||||
"Cancelled."
|
||||
case .decoding:
|
||||
"Ollama returned an unreadable response."
|
||||
case let .unsupportedVersion(found, required):
|
||||
"Ollama \(found) is too old; \(required) or newer is required."
|
||||
}
|
||||
}
|
||||
|
||||
static func message(for rejection: EndpointRejection) -> String {
|
||||
switch rejection {
|
||||
case .scheme:
|
||||
"Only http and https endpoints are supported."
|
||||
case .form:
|
||||
"The endpoint must not contain credentials, a query or a fragment."
|
||||
case .remoteNotAllowed:
|
||||
"Remote endpoints are disabled; use --allow-remote or a loopback endpoint."
|
||||
case .remoteRequiresHTTPS:
|
||||
"Remote endpoints require HTTPS."
|
||||
case .redirect:
|
||||
"The endpoint redirected; redirects are refused."
|
||||
}
|
||||
}
|
||||
|
||||
/// Diagnostics go to stderr so `translate --json` keeps stdout machine-readable.
|
||||
private static func writeError(_ message: String) {
|
||||
FileHandle.standardError.write(Data((message + "\n").utf8))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
enum CLIOutput {
|
||||
static func models(_ summaries: [ModelSummary]) -> String {
|
||||
guard !summaries.isEmpty else {
|
||||
return "No Hy-MT3 models installed."
|
||||
}
|
||||
return summaries.map { summary in
|
||||
var lines = [summary.model.name]
|
||||
lines.append(" digest: \(summary.model.digest.prefix(12))")
|
||||
lines.append(" capabilities: \(summary.capabilities.joined(separator: ", "))")
|
||||
if let details = summary.model.details {
|
||||
if let family = details.family {
|
||||
lines.append(" family: \(family)")
|
||||
}
|
||||
if let parameters = details.parameterSize {
|
||||
lines.append(" parameters: \(parameters)")
|
||||
}
|
||||
if let quantization = details.quantizationLevel {
|
||||
lines.append(" quantization: \(quantization)")
|
||||
}
|
||||
}
|
||||
return lines.joined(separator: "\n")
|
||||
}.joined(separator: "\n\n")
|
||||
}
|
||||
|
||||
static func show(_ details: ModelDetails) -> String {
|
||||
var lines = [
|
||||
"capabilities: \(details.capabilities.joined(separator: ", "))",
|
||||
]
|
||||
if let info = details.details {
|
||||
if let family = info.family {
|
||||
lines.append("family: \(family)")
|
||||
}
|
||||
if let parameters = info.parameterSize {
|
||||
lines.append("parameters: \(parameters)")
|
||||
}
|
||||
if let quantization = info.quantizationLevel {
|
||||
lines.append("quantization: \(quantization)")
|
||||
}
|
||||
}
|
||||
lines.append("license: \(details.license ?? "unknown")")
|
||||
if let parameters = details.parameters {
|
||||
lines.append("parameters:\n\(parameters)")
|
||||
}
|
||||
if let template = details.template {
|
||||
lines.append("template:\n\(template)")
|
||||
}
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
|
||||
struct EndpointOptions: ParsableArguments {
|
||||
@Option(name: .long, help: "Ollama base URL (default http://127.0.0.1:11434).")
|
||||
var endpoint = "http://127.0.0.1:11434"
|
||||
|
||||
@Flag(name: .long, help: "Allow a remote HTTPS endpoint.")
|
||||
var allowRemote = false
|
||||
|
||||
func makeEnvironment() throws -> CLIEnvironment {
|
||||
guard let url = URL(string: endpoint) else {
|
||||
throw ValidationError("Invalid endpoint URL: \(endpoint)")
|
||||
}
|
||||
return CLIEnvironment(baseURL: url, allowRemote: allowRemote)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
struct ModelSummary: Sendable, Equatable {
|
||||
let model: InstalledModel
|
||||
let capabilities: [String]
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import ArgumentParser
|
||||
import SprachmittlerOllama
|
||||
|
||||
struct ModelsCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "models",
|
||||
abstract: "List installed Hy-MT3 models and their capabilities."
|
||||
)
|
||||
|
||||
@OptionGroup var endpoint: EndpointOptions
|
||||
|
||||
func run() async throws {
|
||||
try await CLIError.perform {
|
||||
let environment = try endpoint.makeEnvironment()
|
||||
let catalog = try environment.makeCatalog()
|
||||
let summaries = try await ModelsRunner(catalog: catalog).run()
|
||||
print(CLIOutput.models(summaries))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
struct ModelsRunner: Sendable {
|
||||
let catalog: any OllamaCatalog
|
||||
|
||||
func run() async throws -> [ModelSummary] {
|
||||
let models = try await catalog.installedModels()
|
||||
var summaries: [ModelSummary] = []
|
||||
for model in models where model.isHyMT3 {
|
||||
let details = try await catalog.show(model: model.name)
|
||||
summaries.append(ModelSummary(model: model, capabilities: details.capabilities))
|
||||
}
|
||||
return summaries
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import ArgumentParser
|
||||
import SprachmittlerOllama
|
||||
|
||||
struct ShowCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "show",
|
||||
abstract: "Show an installed model's capabilities, parameters and template."
|
||||
)
|
||||
|
||||
@Argument(help: "Installed model tag.")
|
||||
var model: String
|
||||
|
||||
@OptionGroup var endpoint: EndpointOptions
|
||||
|
||||
func run() async throws {
|
||||
try await CLIError.perform {
|
||||
let environment = try endpoint.makeEnvironment()
|
||||
let catalog = try environment.makeCatalog()
|
||||
let details = try await ShowRunner(catalog: catalog).run(model: model)
|
||||
print(CLIOutput.show(details))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import SprachmittlerOllama
|
||||
|
||||
struct ShowRunner: Sendable {
|
||||
let catalog: any OllamaCatalog
|
||||
|
||||
func run(model: String) async throws -> ModelDetails {
|
||||
try await catalog.show(model: model)
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,15 @@
|
||||
import ArgumentParser
|
||||
import SprachmittlerCore
|
||||
import SprachmittlerEval
|
||||
|
||||
/// Headless harness for Sprachmittler. Subcommands are added in T1.6 (models, show, translate),
|
||||
/// T2.7 (detect, prompt inspection) and T7.1 (eval). See docs/IMPLEMENTATION_PLAN.md.
|
||||
/// Headless harness for Sprachmittler. See docs/IMPLEMENTATION_PLAN.md T1.6, T2.7 and T7.1.
|
||||
@main
|
||||
struct SprachmittlerCLI: ParsableCommand {
|
||||
struct SprachmittlerCLI: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "sprachmittler-cli",
|
||||
abstract: "Headless translator and test harness for Sprachmittler.",
|
||||
subcommands: []
|
||||
subcommands: [
|
||||
ModelsCommand.self,
|
||||
ShowCommand.self,
|
||||
TranslateCommand.self,
|
||||
]
|
||||
)
|
||||
|
||||
func run() throws {
|
||||
print(
|
||||
"sprachmittler-cli: no subcommands implemented yet "
|
||||
+ "(\(SprachmittlerCoreModule.moduleName), \(SprachmittlerEvalModule.moduleName))"
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
struct TranslateCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "translate",
|
||||
abstract: "Translate text with a local Hy-MT3 model."
|
||||
)
|
||||
|
||||
@Option(name: .long, help: "Text to translate.")
|
||||
var text: String?
|
||||
|
||||
@Option(name: .long, help: "File to read UTF-8 text from.")
|
||||
var file: String?
|
||||
|
||||
@Option(name: .long, help: "Target BCP-47 code, e.g. de.")
|
||||
var target: String
|
||||
|
||||
@Option(name: .long, help: "Model tag.")
|
||||
var model = HyMT3ModelPreset.defaultModel
|
||||
|
||||
@Flag(name: .long, help: "Emit the JSON schema instead of plain text.")
|
||||
var json = false
|
||||
|
||||
@Flag(name: .long, help: "Include the source text in JSON (debugging only).")
|
||||
var includeSource = false
|
||||
|
||||
@OptionGroup var endpoint: EndpointOptions
|
||||
|
||||
func validate() throws {
|
||||
if (text == nil) == (file == nil) {
|
||||
throw ValidationError("Use exactly one of --text or --file.")
|
||||
}
|
||||
if HyMT3Languages.resolve(target) == nil {
|
||||
let supported = HyMT3Languages.all.map(\.code).joined(separator: ", ")
|
||||
throw ValidationError("Unknown target language '\(target)'. Supported: \(supported)")
|
||||
}
|
||||
}
|
||||
|
||||
func run() async throws {
|
||||
guard let language = HyMT3Languages.resolve(target) else {
|
||||
throw ValidationError("Unknown target language '\(target)'.")
|
||||
}
|
||||
let source = try sourceText()
|
||||
|
||||
try await CLIError.perform {
|
||||
let environment = try endpoint.makeEnvironment()
|
||||
let chat = try environment.makeChatClient()
|
||||
let runner = TranslateRunner(
|
||||
chat: chat,
|
||||
factory: environment.makeRequestFactory(model: model)
|
||||
)
|
||||
let outcome = try await runner.run(text: source, target: language)
|
||||
if json {
|
||||
let data = try outcome.jsonData(includeSource: includeSource, source: source)
|
||||
print(String(data: data, encoding: .utf8) ?? "{}")
|
||||
} else {
|
||||
print(outcome.translation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `--text` or the UTF-8 contents of `--file`; validation guarantees one is present.
|
||||
func sourceText() throws -> String {
|
||||
if let text {
|
||||
return text
|
||||
}
|
||||
guard let file else {
|
||||
throw ValidationError("Use exactly one of --text or --file.")
|
||||
}
|
||||
do {
|
||||
return try String(contentsOfFile: file, encoding: .utf8)
|
||||
} catch {
|
||||
throw ValidationError("Could not read \(file): \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
struct TranslateOutcome: Sendable, Equatable {
|
||||
let translation: String
|
||||
let model: String
|
||||
let target: ModelLanguage
|
||||
let metrics: ChatMetrics
|
||||
let firstTokenMs: Int?
|
||||
let totalMs: Int
|
||||
let sourceCharacters: Int
|
||||
|
||||
/// The CLI JSON contract from docs/TRANSLATION_OUTPUT.md §10. `sourceLanguage` stays null
|
||||
/// until T2.4; warnings stay empty until T2.5.
|
||||
func jsonData(includeSource: Bool, source: String) throws -> Data {
|
||||
let timing: [String: Any] = [
|
||||
"firstTokenMs": firstTokenMs.map { $0 as Any } ?? NSNull(),
|
||||
"totalMs": totalMs,
|
||||
"promptTokens": metrics.promptEvalCount.map { $0 as Any } ?? NSNull(),
|
||||
"outputTokens": metrics.evalCount.map { $0 as Any } ?? NSNull(),
|
||||
]
|
||||
var object: [String: Any] = [
|
||||
"schema": "sprachmittler-translation-v1",
|
||||
"sourceLanguage": NSNull(),
|
||||
"targetLanguage": target.code,
|
||||
"model": model,
|
||||
"sourceCharacters": sourceCharacters,
|
||||
"translation": translation,
|
||||
"warnings": [String](),
|
||||
"timing": timing,
|
||||
]
|
||||
if includeSource {
|
||||
object["source"] = source
|
||||
}
|
||||
return try JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
|
||||
struct TranslateRunner: Sendable {
|
||||
let chat: any OllamaChatting
|
||||
let factory: HyMT3RequestFactory
|
||||
|
||||
func run(text: String, target: ModelLanguage) async throws -> TranslateOutcome {
|
||||
let request = factory.translationRequest(text: text, target: target)
|
||||
let started = Date()
|
||||
var firstDelta: Date?
|
||||
var translation = ""
|
||||
var metrics = ChatMetrics.empty
|
||||
|
||||
for try await event in chat.chat(request) {
|
||||
switch event {
|
||||
case let .delta(delta):
|
||||
if firstDelta == nil {
|
||||
firstDelta = Date()
|
||||
}
|
||||
translation += delta
|
||||
case let .done(_, doneMetrics):
|
||||
metrics = doneMetrics
|
||||
}
|
||||
}
|
||||
|
||||
let totalMs = max(0, Int(Date().timeIntervalSince(started) * 1000))
|
||||
let firstTokenMs = firstDelta.map { max(0, Int($0.timeIntervalSince(started) * 1000)) }
|
||||
return TranslateOutcome(
|
||||
translation: translation,
|
||||
model: request.model,
|
||||
target: target,
|
||||
metrics: metrics,
|
||||
firstTokenMs: firstTokenMs,
|
||||
totalMs: totalMs,
|
||||
sourceCharacters: text.count
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import SprachmittlerEngines
|
||||
import SprachmittlerOllama
|
||||
import SprachmittlerTestSupport
|
||||
import Testing
|
||||
@testable import sprachmittler_cli
|
||||
|
||||
@Suite("CLI runners")
|
||||
struct CLITests {
|
||||
@Test func modelsRunnerFiltersHyMT3AndPrintsCapabilities() async throws {
|
||||
let hyModel = InstalledModel(
|
||||
name: "hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M",
|
||||
model: "hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M",
|
||||
digest: "262ac792aeb5",
|
||||
details: nil
|
||||
)
|
||||
let other = InstalledModel(name: "llama3:latest", model: "llama3:latest", digest: "abcdef")
|
||||
let details = ModelDetails(capabilities: ["completion"])
|
||||
let catalog = FakeOllamaCatalog(
|
||||
models: [hyModel, other],
|
||||
details: [hyModel.name: details]
|
||||
)
|
||||
|
||||
let summaries = try await ModelsRunner(catalog: catalog).run()
|
||||
#expect(summaries.count == 1)
|
||||
#expect(summaries[0].capabilities == ["completion"])
|
||||
|
||||
let output = CLIOutput.models(summaries)
|
||||
#expect(output.contains(hyModel.name))
|
||||
#expect(output.contains("completion"))
|
||||
#expect(output.contains("262ac792aeb5"))
|
||||
#expect(CLIOutput.models([]) == "No Hy-MT3 models installed.")
|
||||
}
|
||||
|
||||
@Test func showRunnerReturnsDetailsAndPrintsTemplate() async throws {
|
||||
let model = InstalledModel(name: "hy-mt3", model: "hy-mt3", digest: "abcdef")
|
||||
let details = ModelDetails(
|
||||
capabilities: ["completion"],
|
||||
parameters: "stop \"<|eos|>\"",
|
||||
template: "{{ .Prompt }}"
|
||||
)
|
||||
let catalog = FakeOllamaCatalog(models: [model], details: [model.name: details])
|
||||
|
||||
let shown = try await ShowRunner(catalog: catalog).run(model: model.name)
|
||||
#expect(shown == details)
|
||||
let output = CLIOutput.show(shown)
|
||||
#expect(output.contains("capabilities: completion"))
|
||||
#expect(output.contains("template:"))
|
||||
#expect(output.contains("stop"))
|
||||
}
|
||||
|
||||
@Test func translateRunnerUsesDocumentedPromptAndMetrics() async throws {
|
||||
let box = RequestBox()
|
||||
let chat = FakeOllamaChat(
|
||||
events: [
|
||||
.delta("Hal"),
|
||||
.delta("lo"),
|
||||
.done(reason: "stop", metrics: ChatMetrics(promptEvalCount: 9, evalCount: 2)),
|
||||
],
|
||||
onRequest: { box.record($0) }
|
||||
)
|
||||
let factory = HyMT3RequestFactory(model: "test-model", keepAlive: "5m")
|
||||
let outcome = try await TranslateRunner(chat: chat, factory: factory)
|
||||
.run(text: "Hello.", target: HyMT3Languages.german)
|
||||
|
||||
#expect(outcome.translation == "Hallo")
|
||||
#expect(outcome.model == "test-model")
|
||||
#expect(outcome.target == HyMT3Languages.german)
|
||||
#expect(outcome.sourceCharacters == 6)
|
||||
#expect(outcome.metrics.evalCount == 2)
|
||||
|
||||
let request = try #require(box.request)
|
||||
#expect(request.keepAlive == "5m")
|
||||
#expect(
|
||||
request.messages.first?.content
|
||||
== HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "Hello.")
|
||||
)
|
||||
}
|
||||
|
||||
@Test func translateJSONOmitsSourceUnlessRequested() throws {
|
||||
let outcome = TranslateOutcome(
|
||||
translation: "Hallo",
|
||||
model: "test-model",
|
||||
target: HyMT3Languages.german,
|
||||
metrics: ChatMetrics(promptEvalCount: 9, evalCount: 2),
|
||||
firstTokenMs: 4,
|
||||
totalMs: 12,
|
||||
sourceCharacters: 6
|
||||
)
|
||||
|
||||
let data = try outcome.jsonData(includeSource: false, source: "Hello.")
|
||||
let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
#expect(object["schema"] as? String == "sprachmittler-translation-v1")
|
||||
#expect(object["targetLanguage"] as? String == "de")
|
||||
#expect(object["model"] as? String == "test-model")
|
||||
#expect(object["translation"] as? String == "Hallo")
|
||||
#expect(object["sourceLanguage"] is NSNull)
|
||||
#expect((object["warnings"] as? [Any])?.isEmpty == true)
|
||||
#expect(object["source"] == nil)
|
||||
|
||||
let withSourceData = try outcome.jsonData(includeSource: true, source: "Hello.")
|
||||
let withSource = try #require(JSONSerialization.jsonObject(with: withSourceData) as? [String: Any])
|
||||
#expect(withSource["source"] as? String == "Hello.")
|
||||
}
|
||||
|
||||
@Test func unknownLanguageAndMutuallyExclusiveInputsFailValidation() {
|
||||
#expect(HyMT3Languages.resolve("xx") == nil)
|
||||
|
||||
assertValidationError(
|
||||
["--text", "x", "--file", "y", "--target", "de"],
|
||||
message: "Use exactly one of --text or --file"
|
||||
)
|
||||
assertValidationError(
|
||||
["--text", "x", "--target", "xx"],
|
||||
message: "Unknown target language"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func readsTheSourceFileAndText() throws {
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("sprachmittler-cli-\(UUID().uuidString).txt")
|
||||
try "Hello from a file.".write(to: url, atomically: true, encoding: .utf8)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let fileCommand = try TranslateCommand.parse(["--file", url.path, "--target", "de"])
|
||||
#expect(try fileCommand.sourceText() == "Hello from a file.")
|
||||
|
||||
let textCommand = try TranslateCommand.parse(["--text", "Hello.", "--target", "de"])
|
||||
#expect(try textCommand.sourceText() == "Hello.")
|
||||
}
|
||||
|
||||
@Test func exitCodesMatchTheContract() throws {
|
||||
let url = try #require(URL(string: "http://127.0.0.1:9"))
|
||||
#expect(CLIError.exitCode(for: .endpointRejected(.remoteNotAllowed)) == 2)
|
||||
#expect(CLIError.exitCode(for: .unreachable(url)) == 3)
|
||||
#expect(CLIError.exitCode(for: .modelNotInstalled("m")) == 4)
|
||||
#expect(CLIError.exitCode(for: .cancelled) == 1)
|
||||
}
|
||||
|
||||
private func assertValidationError(_ arguments: [String], message: String) {
|
||||
do {
|
||||
let command = try TranslateCommand.parse(arguments)
|
||||
try command.validate()
|
||||
Issue.record("expected ValidationError for \(arguments)")
|
||||
} catch {
|
||||
#expect(String(describing: error).contains(message))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A lock-protected request box for the synchronous `FakeOllamaChat` callback.
|
||||
private final class RequestBox: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var value: ChatRequest?
|
||||
|
||||
var request: ChatRequest? {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return value
|
||||
}
|
||||
|
||||
func record(_ request: ChatRequest) {
|
||||
lock.lock()
|
||||
value = request
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import Testing
|
||||
@testable import sprachmittler_cli
|
||||
|
||||
@Test func cliModuleLoads() {
|
||||
#expect(SprachmittlerCLI.configuration.commandName == "sprachmittler-cli")
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
import Testing
|
||||
@testable import SprachmittlerCore
|
||||
|
||||
@Suite("Ollama error mapping")
|
||||
struct ErrorMappingTests {
|
||||
@Test func mapsEveryOllamaCaseToTheDomainTaxonomy() throws {
|
||||
let url = try #require(URL(string: "http://127.0.0.1:11434"))
|
||||
|
||||
#expect(
|
||||
SprachmittlerError(ollama: .endpointRejected(.redirect))
|
||||
== .endpointRejected(reason: .redirect)
|
||||
)
|
||||
#expect(
|
||||
SprachmittlerError(ollama: .unreachable(url))
|
||||
== .ollamaUnreachable(url: url)
|
||||
)
|
||||
#expect(
|
||||
SprachmittlerError(ollama: .modelNotInstalled("missing"))
|
||||
== .modelNotInstalled(model: "missing")
|
||||
)
|
||||
#expect(
|
||||
SprachmittlerError(ollama: .badRequest("bad input"))
|
||||
== .badRequest(message: "bad input")
|
||||
)
|
||||
#expect(
|
||||
SprachmittlerError(ollama: .server(status: 500, message: "out of memory"))
|
||||
== .server(status: 500, message: "out of memory")
|
||||
)
|
||||
#expect(
|
||||
SprachmittlerError(ollama: .timeout(.firstToken))
|
||||
== .timeout(phase: .firstToken)
|
||||
)
|
||||
#expect(
|
||||
SprachmittlerError(ollama: .cancelled)
|
||||
== .cancelled
|
||||
)
|
||||
#expect(
|
||||
SprachmittlerError(ollama: .decoding("Invalid JSON response"))
|
||||
== .server(status: 0, message: "Invalid JSON response")
|
||||
)
|
||||
#expect(
|
||||
SprachmittlerError(ollama: .unsupportedVersion(found: "0.39.9", required: "0.40.0"))
|
||||
== .ollamaTooOld(found: "0.39.9", required: "0.40.0")
|
||||
)
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
import Foundation
|
||||
import SprachmittlerOllama
|
||||
import Testing
|
||||
@testable import SprachmittlerEngines
|
||||
|
||||
@Suite("Hy-MT3 request factory")
|
||||
struct HyMT3RequestFactoryTests {
|
||||
@Test func warmUpUsesFixedTextAndEightTokens() throws {
|
||||
let request = HyMT3RequestFactory().warmUpRequest()
|
||||
let message = try #require(request.messages.first)
|
||||
#expect(request.messages.count == 1)
|
||||
#expect(message.role == "user")
|
||||
#expect(message.content == "Hello.")
|
||||
#expect(request.options.numPredict == 8)
|
||||
#expect(request.options.numCtx == 8192)
|
||||
#expect(request.keepAlive == "30m")
|
||||
#expect(request.stream)
|
||||
#expect(request.model == HyMT3ModelPreset.defaultModel)
|
||||
}
|
||||
|
||||
@Test func unloadUsesKeepAliveZero() {
|
||||
let request = HyMT3RequestFactory().unloadRequest()
|
||||
#expect(request.keepAlive == "0")
|
||||
#expect(request.messages.map(\.content) == ["Hello."])
|
||||
}
|
||||
|
||||
@Test func translationPromptIsByteExact() throws {
|
||||
let factory = HyMT3RequestFactory(model: "test-model", keepAlive: "5m")
|
||||
let request = factory.translationRequest(text: "Hello.", target: HyMT3Languages.german)
|
||||
let message = try #require(request.messages.first)
|
||||
#expect(request.messages.count == 1)
|
||||
#expect(
|
||||
message.content
|
||||
== "Translate the following text into German. "
|
||||
+ "Note that you should **only output the translated result without any additional explanation**:"
|
||||
+ "\n\nHello."
|
||||
)
|
||||
#expect(request.model == "test-model")
|
||||
#expect(request.keepAlive == "5m")
|
||||
#expect(request.options.numPredict == 4096)
|
||||
#expect(request.options.numCtx == 8192)
|
||||
#expect(request.options.temperature == 0.7)
|
||||
#expect(request.options.topP == 0.6)
|
||||
#expect(request.options.topK == 20)
|
||||
#expect(request.options.repeatPenalty == 1.05)
|
||||
}
|
||||
|
||||
@Test func promptMatchesTheGoldenFixture() throws {
|
||||
let base = try #require(Bundle.module.resourceURL)
|
||||
let url = base.appendingPathComponent("Fixtures/default-prompt.txt")
|
||||
let template = try String(contentsOf: url, encoding: .utf8)
|
||||
.trimmingCharacters(in: .newlines)
|
||||
let expected = template
|
||||
.replacingOccurrences(of: "{target_lang}", with: "German")
|
||||
.replacingOccurrences(of: "{source_text}", with: "Hello.")
|
||||
#expect(
|
||||
HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "Hello.")
|
||||
== expected
|
||||
)
|
||||
}
|
||||
|
||||
@Test func promptPrefixIsStableForTheSameTarget() {
|
||||
let factory = HyMT3RequestFactory()
|
||||
let first = factory.translationRequest(text: "One.", target: HyMT3Languages.german)
|
||||
let second = factory.translationRequest(text: "Two.", target: HyMT3Languages.german)
|
||||
let firstContent = first.messages[0].content
|
||||
let secondContent = second.messages[0].content
|
||||
let suffix = "\n\n"
|
||||
let firstPrefix = firstContent.components(separatedBy: suffix)[0]
|
||||
let secondPrefix = secondContent.components(separatedBy: suffix)[0]
|
||||
#expect(firstPrefix == secondPrefix)
|
||||
#expect(firstContent.hasSuffix("One."))
|
||||
#expect(secondContent.hasSuffix("Two."))
|
||||
}
|
||||
|
||||
@Test func resolvesOnlyTheProvisionalCommonLanguages() {
|
||||
#expect(HyMT3Languages.resolve("de") == HyMT3Languages.german)
|
||||
#expect(HyMT3Languages.resolve("EN") == HyMT3Languages.english)
|
||||
#expect(HyMT3Languages.resolve("zh-Hant")?.modelName == "Traditional Chinese")
|
||||
#expect(HyMT3Languages.resolve("xx") == nil)
|
||||
#expect(HyMT3Languages.all.count == 16)
|
||||
}
|
||||
|
||||
@Test func optionsMatchTheDocumentedPublisherValues() {
|
||||
#expect(HyMT3Options.translation.temperature == 0.7)
|
||||
#expect(HyMT3Options.translation.topP == 0.6)
|
||||
#expect(HyMT3Options.translation.topK == 20)
|
||||
#expect(HyMT3Options.translation.repeatPenalty == 1.05)
|
||||
#expect(HyMT3Options.translation.numPredict == 4096)
|
||||
#expect(HyMT3Options.translation.numCtx == 8192)
|
||||
#expect(HyMT3Options.warmUp.numPredict == 8)
|
||||
}
|
||||
}
|
||||
-5
@@ -2,11 +2,6 @@ import Foundation
|
||||
import Testing
|
||||
@testable import SprachmittlerEngines
|
||||
|
||||
@Test func moduleLinks() {
|
||||
#expect(SprachmittlerEnginesModule.moduleName == "SprachmittlerEngines")
|
||||
}
|
||||
|
||||
/// T2.2 will replace this with a byte-exact comparison against the adapter's prompt.
|
||||
@Test func canonicalDefaultPromptFixtureIsTheDocumentedTemplate() throws {
|
||||
let base = try #require(Bundle.module.resourceURL)
|
||||
let url = base.appendingPathComponent("Fixtures/default-prompt.txt")
|
||||
@@ -0,0 +1,65 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import SprachmittlerOllama
|
||||
|
||||
@Suite("Endpoint policy")
|
||||
struct EndpointPolicyTests {
|
||||
@Test(arguments: [
|
||||
"http://127.0.0.1:11434",
|
||||
"https://127.0.0.1:11434",
|
||||
"http://localhost:11434",
|
||||
"https://LOCALHOST:11434",
|
||||
"http://[::1]:11434",
|
||||
])
|
||||
func acceptsLoopback(_ string: String) throws {
|
||||
let url = try #require(URL(string: string))
|
||||
#expect(try EndpointPolicy.validate(url, allowRemote: false) == url)
|
||||
}
|
||||
|
||||
@Test func rejectsRemoteWithoutToggle() throws {
|
||||
let url = try #require(URL(string: "https://example.com:11434"))
|
||||
#expect(rejection(url, allowRemote: false) == .remoteNotAllowed)
|
||||
}
|
||||
|
||||
@Test func rejectsRemoteHTTPEvenWithToggle() throws {
|
||||
let url = try #require(URL(string: "http://example.com:11434"))
|
||||
#expect(rejection(url, allowRemote: true) == .remoteRequiresHTTPS)
|
||||
}
|
||||
|
||||
@Test func acceptsRemoteHTTPSWithToggle() throws {
|
||||
let url = try #require(URL(string: "https://example.com:11434"))
|
||||
#expect(try EndpointPolicy.validate(url, allowRemote: true) == url)
|
||||
}
|
||||
|
||||
@Test func rejectsUnsupportedScheme() throws {
|
||||
let url = try #require(URL(string: "ftp://127.0.0.1:11434"))
|
||||
#expect(rejection(url, allowRemote: false) == .scheme)
|
||||
}
|
||||
|
||||
@Test(arguments: [
|
||||
"http://user:password@127.0.0.1:11434",
|
||||
"http://127.0.0.1:11434/?a=b",
|
||||
"http://127.0.0.1:11434/#fragment",
|
||||
])
|
||||
func rejectsUserInfoQueryAndFragment(_ string: String) throws {
|
||||
let url = try #require(URL(string: string))
|
||||
#expect(rejection(url, allowRemote: false) == .form)
|
||||
}
|
||||
|
||||
@Test func rejectsMissingHost() throws {
|
||||
let url = try #require(URL(string: "http:///api"))
|
||||
#expect(rejection(url, allowRemote: false) == .form)
|
||||
#expect(EndpointPolicy.isLoopback(url) == false)
|
||||
}
|
||||
|
||||
private func rejection(_ url: URL, allowRemote: Bool) -> EndpointRejection? {
|
||||
do {
|
||||
_ = try EndpointPolicy.validate(url, allowRemote: allowRemote)
|
||||
return nil
|
||||
} catch let error as EndpointRejection {
|
||||
return error
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import SprachmittlerOllama
|
||||
|
||||
@Suite("Ephemeral session")
|
||||
struct EphemeralSessionTests {
|
||||
@Test func configurationHasNoCookiesCacheOrCredentials() {
|
||||
let configuration = OllamaSessionFactory.makeConfiguration()
|
||||
#expect(configuration.httpCookieStorage == nil)
|
||||
#expect(configuration.urlCache == nil)
|
||||
#expect(configuration.urlCredentialStorage == nil)
|
||||
#expect(configuration.httpShouldSetCookies == false)
|
||||
#expect(configuration.requestCachePolicy == .reloadIgnoringLocalCacheData)
|
||||
#expect(configuration.waitsForConnectivity == false)
|
||||
#expect(configuration.timeoutIntervalForRequest >= 180)
|
||||
#expect(configuration.timeoutIntervalForResource >= 180)
|
||||
}
|
||||
|
||||
@Test func productionClientUsesEphemeralSessionAndRedirectDelegate() throws {
|
||||
let url = try #require(URL(string: "http://127.0.0.1:11434"))
|
||||
let client = try OllamaHTTPClient(baseURL: url)
|
||||
let configuration = client.session.configuration
|
||||
#expect(configuration.httpCookieStorage == nil)
|
||||
#expect(configuration.urlCache == nil)
|
||||
#expect(configuration.urlCredentialStorage == nil)
|
||||
#expect(configuration.httpShouldSetCookies == false)
|
||||
#expect(client.session.delegate is RedirectRefusingDelegate)
|
||||
}
|
||||
|
||||
@Test func productionClientRejectsRemoteWithoutToggle() throws {
|
||||
let url = try #require(URL(string: "https://example.com:11434"))
|
||||
do {
|
||||
_ = try OllamaHTTPClient(baseURL: url)
|
||||
Issue.record("expected remoteNotAllowed")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .endpointRejected(.remoteNotAllowed))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import SprachmittlerOllama
|
||||
|
||||
/// T1.1: the recorded Ollama fixtures stay small, internally consistent and decodable.
|
||||
@Suite("Fixture contract")
|
||||
struct FixtureContractTests {
|
||||
@Test func fixturesStayUnderBudget() throws {
|
||||
let directory = try fixtures()
|
||||
let files = try FileManager.default.contentsOfDirectory(
|
||||
at: directory,
|
||||
includingPropertiesForKeys: [.fileSizeKey]
|
||||
)
|
||||
for file in files where !file.hasDirectoryPath {
|
||||
let size = try file.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
|
||||
#expect(size < 200 * 1024, "\(file.lastPathComponent) is \(size) bytes")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func captureMetaMatchesTagsAndVersion() throws {
|
||||
let meta = try object("capture-meta.json")
|
||||
let tags = try object("tags.json")
|
||||
let version = try object("version.json")
|
||||
|
||||
let ollama = try #require(meta["ollama"] as? String)
|
||||
// Pinned to the verified server version; update on a deliberate fixture recapture.
|
||||
#expect(ollama == "0.40.18")
|
||||
#expect(version["version"] as? String == ollama)
|
||||
|
||||
let metaModels = try #require(meta["models"] as? [[String: Any]])
|
||||
#expect(!metaModels.isEmpty)
|
||||
let tagModels = try #require(tags["models"] as? [[String: Any]])
|
||||
|
||||
for model in metaModels {
|
||||
let name = try #require(model["model"] as? String)
|
||||
let digest = try #require(model["digest"] as? String)
|
||||
#expect(digest.count == 12)
|
||||
let tag = try #require(tagModels.first { $0["name"] as? String == name })
|
||||
let fullDigest = try #require(tag["digest"] as? String)
|
||||
#expect(fullDigest.hasPrefix(digest))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func doneReasonsAreRecorded() throws {
|
||||
let stop = try lastObject(of: "chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-en-de.ndjson")
|
||||
let length = try lastObject(of: "chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-truncated.ndjson")
|
||||
#expect(stop["done_reason"] as? String == "stop")
|
||||
#expect(length["done_reason"] as? String == "length")
|
||||
}
|
||||
|
||||
@Test func everyNDJSONLineDecodes() throws {
|
||||
let directory = try fixtures()
|
||||
let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
|
||||
.filter { $0.pathExtension == "ndjson" }
|
||||
#expect(!files.isEmpty)
|
||||
|
||||
for file in files {
|
||||
let text = try String(contentsOf: file, encoding: .utf8)
|
||||
let lines = text.split(separator: "\n", omittingEmptySubsequences: true)
|
||||
#expect(!lines.isEmpty)
|
||||
for line in lines {
|
||||
let object = try? JSONSerialization.jsonObject(with: Data(line.utf8))
|
||||
#expect(object != nil, "\(file.lastPathComponent): \(line.prefix(80))")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test func showFixtureHasDocumentedFields() throws {
|
||||
let show = try object("show-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M.json")
|
||||
let capabilities = try #require(show["capabilities"] as? [String])
|
||||
#expect(capabilities.contains("completion"))
|
||||
let parameters = try #require(show["parameters"] as? String)
|
||||
#expect(parameters.contains("stop"))
|
||||
let template = try #require(show["template"] as? String)
|
||||
#expect(template.contains("<|startoftext|>"))
|
||||
#expect(show.keys.contains("license"))
|
||||
}
|
||||
|
||||
private func fixtures() throws -> URL {
|
||||
let base = try #require(Bundle.module.resourceURL)
|
||||
return base.appendingPathComponent("Fixtures")
|
||||
}
|
||||
|
||||
private func object(_ name: String) throws -> [String: Any] {
|
||||
let url = try fixtures().appendingPathComponent(name)
|
||||
let data = try Data(contentsOf: url)
|
||||
return try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
}
|
||||
|
||||
private func lastObject(of name: String) throws -> [String: Any] {
|
||||
let url = try fixtures().appendingPathComponent(name)
|
||||
let text = try String(contentsOf: url, encoding: .utf8)
|
||||
let line = try #require(text.split(separator: "\n").last)
|
||||
return try #require(try JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any])
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"date": "2026-11-26T10:50:04Z",
|
||||
"date": "2026-11-26T11:36:50Z",
|
||||
"ollama": "0.40.18",
|
||||
"hardware": "Apple M5 Pro",
|
||||
"memoryBytes": "51539607552",
|
||||
|
||||
+26
-26
@@ -1,26 +1,26 @@
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.999173Z","message":{"role":"assistant","content":"Size"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.026416Z","message":{"role":"assistant","content":" changes"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.048719Z","message":{"role":"assistant","content":" and"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.076474Z","message":{"role":"assistant","content":" roads"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.098414Z","message":{"role":"assistant","content":" are"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.119328Z","message":{"role":"assistant","content":" important"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.143258Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.166468Z","message":{"role":"assistant","content":" Please"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.191479Z","message":{"role":"assistant","content":" open"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.216114Z","message":{"role":"assistant","content":" https"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.241732Z","message":{"role":"assistant","content":"://"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.265654Z","message":{"role":"assistant","content":"example"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.287662Z","message":{"role":"assistant","content":".de"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.316362Z","message":{"role":"assistant","content":"/h"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.341857Z","message":{"role":"assistant","content":"il"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.364919Z","message":{"role":"assistant","content":"fe"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.386826Z","message":{"role":"assistant","content":" and"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.408914Z","message":{"role":"assistant","content":" set"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.431967Z","message":{"role":"assistant","content":" the"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.456708Z","message":{"role":"assistant","content":" limit"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.477947Z","message":{"role":"assistant","content":" to"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.49891Z","message":{"role":"assistant","content":" {{"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.520627Z","message":{"role":"assistant","content":"limit"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.542168Z","message":{"role":"assistant","content":"}}"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.565442Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.586143Z","message":{"role":"assistant","content":""},"done":true,"done_reason":"stop","total_duration":685861833,"load_duration":938583,"prompt_eval_count":56,"prompt_eval_cached_count":6,"prompt_eval_duration":92529000,"eval_count":26,"eval_duration":586872000}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.484974Z","message":{"role":"assistant","content":"Size"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.515194Z","message":{"role":"assistant","content":" changes"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.53694Z","message":{"role":"assistant","content":" and"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.564852Z","message":{"role":"assistant","content":" roads"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.5904Z","message":{"role":"assistant","content":" are"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.612629Z","message":{"role":"assistant","content":" important"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.641951Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.666052Z","message":{"role":"assistant","content":" Please"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.689821Z","message":{"role":"assistant","content":" open"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.712026Z","message":{"role":"assistant","content":" https"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.736654Z","message":{"role":"assistant","content":"://"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.76546Z","message":{"role":"assistant","content":"example"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.787224Z","message":{"role":"assistant","content":".de"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.816042Z","message":{"role":"assistant","content":"/h"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.841031Z","message":{"role":"assistant","content":"il"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.862039Z","message":{"role":"assistant","content":"fe"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.885918Z","message":{"role":"assistant","content":" and"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.908108Z","message":{"role":"assistant","content":" set"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.928689Z","message":{"role":"assistant","content":" the"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.949235Z","message":{"role":"assistant","content":" limit"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.974229Z","message":{"role":"assistant","content":" to"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.996005Z","message":{"role":"assistant","content":" {{"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.024238Z","message":{"role":"assistant","content":"limit"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.045455Z","message":{"role":"assistant","content":"}}"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.070118Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.092303Z","message":{"role":"assistant","content":""},"done":true,"done_reason":"stop","total_duration":707828583,"load_duration":949667,"prompt_eval_count":56,"prompt_eval_cached_count":6,"prompt_eval_duration":93676000,"eval_count":26,"eval_duration":607234000}
|
||||
+38
-39
@@ -1,39 +1,38 @@
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.041299Z","message":{"role":"assistant","content":"Der"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.062402Z","message":{"role":"assistant","content":" schn"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.082942Z","message":{"role":"assistant","content":"elle"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.104113Z","message":{"role":"assistant","content":" bra"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.124845Z","message":{"role":"assistant","content":"une"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.145739Z","message":{"role":"assistant","content":" F"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.16648Z","message":{"role":"assistant","content":"uchs"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.187129Z","message":{"role":"assistant","content":" spring"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.208482Z","message":{"role":"assistant","content":"t"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.228993Z","message":{"role":"assistant","content":" über"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.249733Z","message":{"role":"assistant","content":" den"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.270729Z","message":{"role":"assistant","content":" fa"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.292143Z","message":{"role":"assistant","content":"ulen"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.313133Z","message":{"role":"assistant","content":" Hund"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.335165Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.357874Z","message":{"role":"assistant","content":" Bitte"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.380728Z","message":{"role":"assistant","content":" öff"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.40349Z","message":{"role":"assistant","content":"ne"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.426946Z","message":{"role":"assistant","content":" https"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.453306Z","message":{"role":"assistant","content":"://"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.475121Z","message":{"role":"assistant","content":"example"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.495912Z","message":{"role":"assistant","content":".com"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.517223Z","message":{"role":"assistant","content":"/docs"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.540613Z","message":{"role":"assistant","content":"?"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.564655Z","message":{"role":"assistant","content":"lang"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.586532Z","message":{"role":"assistant","content":"=en"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.610249Z","message":{"role":"assistant","content":" und"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.633386Z","message":{"role":"assistant","content":" set"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.658404Z","message":{"role":"assistant","content":"ze"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.681504Z","message":{"role":"assistant","content":" die"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.703193Z","message":{"role":"assistant","content":" Beg"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.725477Z","message":{"role":"assistant","content":"ren"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.749429Z","message":{"role":"assistant","content":"zung"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.771122Z","message":{"role":"assistant","content":" auf"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.792122Z","message":{"role":"assistant","content":" {{"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.815377Z","message":{"role":"assistant","content":"limit"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.836742Z","message":{"role":"assistant","content":"}}"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.858155Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:01.878784Z","message":{"role":"assistant","content":""},"done":true,"done_reason":"stop","total_duration":1097586000,"load_duration":800042,"prompt_eval_count":54,"prompt_eval_cached_count":40,"prompt_eval_duration":255365000,"eval_count":39,"eval_duration":837305000}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.510794Z","message":{"role":"assistant","content":"Der"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.535189Z","message":{"role":"assistant","content":" schn"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.557499Z","message":{"role":"assistant","content":"elle"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.580002Z","message":{"role":"assistant","content":" bra"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.602281Z","message":{"role":"assistant","content":"une"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.62429Z","message":{"role":"assistant","content":" F"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.648922Z","message":{"role":"assistant","content":"uchs"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.672854Z","message":{"role":"assistant","content":" spring"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.6985Z","message":{"role":"assistant","content":"t"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.720133Z","message":{"role":"assistant","content":" über"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.748481Z","message":{"role":"assistant","content":" den"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.773641Z","message":{"role":"assistant","content":" fa"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.795296Z","message":{"role":"assistant","content":"ulen"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.823754Z","message":{"role":"assistant","content":" Hund"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.845798Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.869885Z","message":{"role":"assistant","content":" Bitte"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.89341Z","message":{"role":"assistant","content":" öff"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.916502Z","message":{"role":"assistant","content":"ne"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.940296Z","message":{"role":"assistant","content":" https"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.961331Z","message":{"role":"assistant","content":"://"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:47.984869Z","message":{"role":"assistant","content":"example"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.008698Z","message":{"role":"assistant","content":".com"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.031625Z","message":{"role":"assistant","content":"/docs"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.053258Z","message":{"role":"assistant","content":"?"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.076258Z","message":{"role":"assistant","content":"lang"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.098998Z","message":{"role":"assistant","content":"=en"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.123902Z","message":{"role":"assistant","content":" und"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.146793Z","message":{"role":"assistant","content":" set"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.167094Z","message":{"role":"assistant","content":"ze"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.19041Z","message":{"role":"assistant","content":" die"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.211094Z","message":{"role":"assistant","content":" Gren"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.234047Z","message":{"role":"assistant","content":"ze"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.257057Z","message":{"role":"assistant","content":" auf"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.277687Z","message":{"role":"assistant","content":" {{"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.298089Z","message":{"role":"assistant","content":"limit"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.319587Z","message":{"role":"assistant","content":"}}"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.342369Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:48.363507Z","message":{"role":"assistant","content":""},"done":true,"done_reason":"stop","total_duration":913071792,"load_duration":467500,"prompt_eval_count":54,"prompt_eval_cached_count":41,"prompt_eval_duration":56906000,"eval_count":38,"eval_duration":852566000}
|
||||
+41
-41
@@ -1,41 +1,41 @@
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.772327Z","message":{"role":"assistant","content":"#"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.794702Z","message":{"role":"assistant","content":" Release"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.818863Z","message":{"role":"assistant","content":"-"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.841715Z","message":{"role":"assistant","content":"Not"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.863613Z","message":{"role":"assistant","content":"izen"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.886164Z","message":{"role":"assistant","content":"\n\n"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.906353Z","message":{"role":"assistant","content":"Ö"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.926587Z","message":{"role":"assistant","content":"ff"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.946987Z","message":{"role":"assistant","content":"ne"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.967266Z","message":{"role":"assistant","content":" **"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:02.987899Z","message":{"role":"assistant","content":"E"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.009445Z","message":{"role":"assistant","content":"inst"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.032835Z","message":{"role":"assistant","content":"ellungen"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.054065Z","message":{"role":"assistant","content":"**"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.076403Z","message":{"role":"assistant","content":" und"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.098292Z","message":{"role":"assistant","content":" set"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.120065Z","message":{"role":"assistant","content":"ze"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.14216Z","message":{"role":"assistant","content":" `"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.165036Z","message":{"role":"assistant","content":"max"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.186887Z","message":{"role":"assistant","content":"_tokens"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.210027Z","message":{"role":"assistant","content":"`"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.232047Z","message":{"role":"assistant","content":" auf"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.253984Z","message":{"role":"assistant","content":" {{"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.276083Z","message":{"role":"assistant","content":"limit"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.299105Z","message":{"role":"assistant","content":"}}"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.326721Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.349855Z","message":{"role":"assistant","content":" Sie"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.375916Z","message":{"role":"assistant","content":"he"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.39872Z","message":{"role":"assistant","content":" ["},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.425595Z","message":{"role":"assistant","content":"die"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.44871Z","message":{"role":"assistant","content":" Dok"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.470652Z","message":{"role":"assistant","content":"ument"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.495128Z","message":{"role":"assistant","content":"ation"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.518055Z","message":{"role":"assistant","content":"]("},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.543014Z","message":{"role":"assistant","content":"https"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.564178Z","message":{"role":"assistant","content":"://"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.586378Z","message":{"role":"assistant","content":"example"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.607084Z","message":{"role":"assistant","content":".com"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.627655Z","message":{"role":"assistant","content":"/docs"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.648102Z","message":{"role":"assistant","content":")."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.66923Z","message":{"role":"assistant","content":""},"done":true,"done_reason":"stop","total_duration":1060656625,"load_duration":982125,"prompt_eval_count":55,"prompt_eval_cached_count":24,"prompt_eval_duration":158860000,"eval_count":41,"eval_duration":896534000}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.2118Z","message":{"role":"assistant","content":"#"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.235709Z","message":{"role":"assistant","content":" Release"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.261627Z","message":{"role":"assistant","content":"-"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.284876Z","message":{"role":"assistant","content":"Not"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.309729Z","message":{"role":"assistant","content":"izen"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.332942Z","message":{"role":"assistant","content":"\n\n"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.353637Z","message":{"role":"assistant","content":"Ö"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.383404Z","message":{"role":"assistant","content":"ff"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.407232Z","message":{"role":"assistant","content":"ne"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.428767Z","message":{"role":"assistant","content":" **"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.45081Z","message":{"role":"assistant","content":"E"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.474696Z","message":{"role":"assistant","content":"inst"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.49549Z","message":{"role":"assistant","content":"ellungen"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.520014Z","message":{"role":"assistant","content":"**"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.54312Z","message":{"role":"assistant","content":" und"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.567111Z","message":{"role":"assistant","content":" set"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.5903Z","message":{"role":"assistant","content":"ze"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.61214Z","message":{"role":"assistant","content":" `"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.635474Z","message":{"role":"assistant","content":"max"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.658322Z","message":{"role":"assistant","content":"_tokens"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.679825Z","message":{"role":"assistant","content":"`"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.707329Z","message":{"role":"assistant","content":" auf"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.728885Z","message":{"role":"assistant","content":" {{"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.752198Z","message":{"role":"assistant","content":"limit"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.77604Z","message":{"role":"assistant","content":"}}"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.798615Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.824911Z","message":{"role":"assistant","content":" Sie"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.848787Z","message":{"role":"assistant","content":"he"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.870786Z","message":{"role":"assistant","content":" ["},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.893752Z","message":{"role":"assistant","content":"die"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.916754Z","message":{"role":"assistant","content":" Dok"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.940443Z","message":{"role":"assistant","content":"ument"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.962156Z","message":{"role":"assistant","content":"ation"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:49.984438Z","message":{"role":"assistant","content":"]("},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.007121Z","message":{"role":"assistant","content":"https"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.028935Z","message":{"role":"assistant","content":"://"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.052627Z","message":{"role":"assistant","content":"example"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.072993Z","message":{"role":"assistant","content":".com"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.093486Z","message":{"role":"assistant","content":"/docs"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.113791Z","message":{"role":"assistant","content":")."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.134227Z","message":{"role":"assistant","content":""},"done":true,"done_reason":"stop","total_duration":1017156916,"load_duration":593625,"prompt_eval_count":55,"prompt_eval_cached_count":24,"prompt_eval_duration":88372000,"eval_count":41,"eval_duration":922310000}
|
||||
+17
-17
@@ -1,17 +1,17 @@
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.719059Z","message":{"role":"assistant","content":"Der"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.741856Z","message":{"role":"assistant","content":" schn"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.763971Z","message":{"role":"assistant","content":"elle"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.788457Z","message":{"role":"assistant","content":" bra"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.816115Z","message":{"role":"assistant","content":"une"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.837982Z","message":{"role":"assistant","content":" F"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.859818Z","message":{"role":"assistant","content":"uchs"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.882871Z","message":{"role":"assistant","content":" spring"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.903597Z","message":{"role":"assistant","content":"t"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.924467Z","message":{"role":"assistant","content":" über"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.945168Z","message":{"role":"assistant","content":" den"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.96565Z","message":{"role":"assistant","content":" fa"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:03.986248Z","message":{"role":"assistant","content":"ulen"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:04.006813Z","message":{"role":"assistant","content":" Hund"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:04.027953Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:04.05037Z","message":{"role":"assistant","content":" Bitte"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T10:50:04.05045Z","message":{"role":"assistant","content":""},"done":true,"done_reason":"length","total_duration":360730916,"load_duration":829666,"prompt_eval_count":54,"prompt_eval_cached_count":53,"prompt_eval_duration":22903000,"eval_count":16,"eval_duration":332421000}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.186194Z","message":{"role":"assistant","content":"Der"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.208196Z","message":{"role":"assistant","content":" schn"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.232177Z","message":{"role":"assistant","content":"elle"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.254076Z","message":{"role":"assistant","content":" bra"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.276858Z","message":{"role":"assistant","content":"une"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.300817Z","message":{"role":"assistant","content":" F"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.32413Z","message":{"role":"assistant","content":"uchs"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.346233Z","message":{"role":"assistant","content":" spring"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.368461Z","message":{"role":"assistant","content":"t"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.391574Z","message":{"role":"assistant","content":" über"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.415355Z","message":{"role":"assistant","content":" den"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.436625Z","message":{"role":"assistant","content":" fa"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.460204Z","message":{"role":"assistant","content":"ulen"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.481948Z","message":{"role":"assistant","content":" Hund"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.504425Z","message":{"role":"assistant","content":"."},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.52598Z","message":{"role":"assistant","content":" Bitte"},"done":false}
|
||||
{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","created_at":"2026-11-26T11:36:50.526122Z","message":{"role":"assistant","content":""},"done":true,"done_reason":"length","total_duration":370233958,"load_duration":782416,"prompt_eval_count":54,"prompt_eval_cached_count":53,"prompt_eval_duration":23159000,"eval_count":16,"eval_duration":340994000}
|
||||
@@ -1 +1 @@
|
||||
{"models":[{"name":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","size":6488609259,"digest":"262ac792aeb50fb8dfeae6feea465dfb10a0542dc9931c24de0a88d6b44fd1e7","details":{"parent_model":"","format":"gguf","family":"hunyuan-dense","families":["hunyuan-dense"],"parameter_size":"7.5B","quantization_level":"unknown"},"expires_at":"2026-11-26T12:19:57.087651+01:00","size_vram":6488609259,"context_length":8192,"runner":"llamacpp"}]}
|
||||
{"models":[{"name":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","size":6488609259,"digest":"262ac792aeb50fb8dfeae6feea465dfb10a0542dc9931c24de0a88d6b44fd1e7","details":{"parent_model":"","format":"gguf","family":"hunyuan-dense","families":["hunyuan-dense"],"parameter_size":"7.5B","quantization_level":"unknown"},"expires_at":"2026-11-26T12:41:30.110955+01:00","size_vram":6488609259,"context_length":8192,"runner":"llamacpp"}]}
|
||||
+1
@@ -14,6 +14,7 @@
|
||||
},
|
||||
"parameters": "stop \"<|startoftext|>\"\nstop \"<|extra_4|>\"\nstop \"<|extra_0|>\"\nstop \"<|eos|>\"",
|
||||
"template": "{{ if .System }}<|startoftext|>{{ .System }}<|extra_4|>{{ end }}{{ if .Prompt }}<|startoftext|>{{ .Prompt }}<|extra_0|>{{ end }}{{ .Response }}<|eos|>",
|
||||
"license": null,
|
||||
"model_info": {
|
||||
"hunyuan-dense.block_count": 32,
|
||||
"hunyuan-dense.context_length": 262144,
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"models":[{"name":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","modified_at":"2026-11-26T09:09:25.155214479+01:00","size":5145532022,"digest":"262ac792aeb50fb8dfeae6feea465dfb10a0542dc9931c24de0a88d6b44fd1e7","details":{"parent_model":"","format":"gguf","family":"hunyuan-dense","families":["hunyuan-dense"],"parameter_size":"7.5B","quantization_level":"Q4_K_M","context_length":262144,"embedding_length":4096,"runner":"ggml"},"capabilities":["completion"]},{"name":"deepseek-ocr:3b","model":"deepseek-ocr:3b","modified_at":"2026-11-12T21:19:05.025742233+01:00","size":6687240356,"digest":"0e7b018b8a22373167ee79c9a852821235488cbd2a2a5a93495558627423278c","details":{"parent_model":"","format":"gguf","family":"deepseekocr","families":["deepseekocr"],"parameter_size":"3.3B","quantization_level":"F16","context_length":8192,"embedding_length":1280,"runner":"ggml"},"capabilities":["completion","vision"]},{"name":"maternion/LightOnOCR-3:0.8b","model":"maternion/LightOnOCR-3:0.8b","modified_at":"2026-11-11T22:53:43.933731782+01:00","size":1019190827,"digest":"605bb25fbd99bc71baf607a9fba03e3ce73575e4e90ea2378c3f24578a28694b","details":{"parent_model":"LightOnOCR-3-0.8B.Q8_0.gguf","format":"gguf","family":"qwen35","families":["qwen35"],"parameter_size":"752.39M","quantization_level":"Q8_0","context_length":262144,"embedding_length":1024,"runner":"llamacpp"},"capabilities":["completion","vision","tools","thinking"]},{"name":"maternion/LightOnOCR-3:4b","model":"maternion/LightOnOCR-3:4b","modified_at":"2026-11-11T22:51:28.04473841+01:00","size":3384374666,"digest":"a1d387a47620c3e343cf8978e8fd63f5f677d2fa97bd5d3e28f031cc69b59748","details":{"parent_model":"LightOnOCR-3-4B.i1-Q4_K_M.gguf","format":"gguf","family":"qwen35","families":["qwen35"],"parameter_size":"4.2B","quantization_level":"Q4_K_M","context_length":262144,"embedding_length":2560,"runner":"llamacpp"},"capabilities":["completion","vision","tools","thinking"]},{"name":"deepseek-ocr:latest","model":"deepseek-ocr:latest","modified_at":"2026-11-11T22:49:31.646969001+01:00","size":6687240356,"digest":"0e7b018b8a22373167ee79c9a852821235488cbd2a2a5a93495558627423278c","details":{"parent_model":"","format":"gguf","family":"deepseekocr","families":["deepseekocr"],"parameter_size":"3.3B","quantization_level":"F16","context_length":8192,"embedding_length":1280,"runner":"ggml"},"capabilities":["completion","vision"]},{"name":"phonon:40m-en","model":"phonon:40m-en","modified_at":"2026-11-02T10:58:39.491697329+01:00","size":131759489,"digest":"b74a4edf2fe2cdc766ec44783089563fbf6c09a163846d7d0e1e316e98390029","details":{"parent_model":"","format":"safetensors","family":"","families":null,"parameter_size":"","quantization_level":"","runner":"mlx"},"capabilities":["speech"]},{"name":"phonon:40m-de","model":"phonon:40m-de","modified_at":"2026-10-30T16:24:22.463655473+01:00","size":125613369,"digest":"024449ea0a54272832611a4c38a16c3b2c8e67752a2e1a2fd0c4350b3561a905","details":{"parent_model":"","format":"safetensors","family":"","families":null,"parameter_size":"","quantization_level":"","runner":"mlx"},"capabilities":["speech"]},{"name":"glm-ocr:latest","model":"glm-ocr:latest","modified_at":"2026-07-27T10:24:59.910954687+02:00","size":2219299168,"digest":"6effedd0dc8aec66ad86c94b8099395376e212f22c87a9d7147c422f7e447be4","details":{"parent_model":"","format":"gguf","family":"glmocr","families":["glmocr"],"parameter_size":"1.1B","quantization_level":"F16","context_length":131072,"embedding_length":1536,"runner":"ggml"},"capabilities":["completion","vision","tools"]}]}
|
||||
{"models":[{"name":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M","modified_at":"2026-11-26T12:06:02.554744486+01:00","size":5145532022,"digest":"262ac792aeb50fb8dfeae6feea465dfb10a0542dc9931c24de0a88d6b44fd1e7","details":{"parent_model":"","format":"gguf","family":"hunyuan-dense","families":["hunyuan-dense"],"parameter_size":"7.5B","quantization_level":"Q4_K_M","context_length":262144,"embedding_length":4096,"runner":"ggml"},"capabilities":["completion"]},{"name":"deepseek-ocr:3b","model":"deepseek-ocr:3b","modified_at":"2026-11-12T21:19:05.025742233+01:00","size":6687240356,"digest":"0e7b018b8a22373167ee79c9a852821235488cbd2a2a5a93495558627423278c","details":{"parent_model":"","format":"gguf","family":"deepseekocr","families":["deepseekocr"],"parameter_size":"3.3B","quantization_level":"F16","context_length":8192,"embedding_length":1280,"runner":"ggml"},"capabilities":["completion","vision"]},{"name":"maternion/LightOnOCR-3:0.8b","model":"maternion/LightOnOCR-3:0.8b","modified_at":"2026-11-11T22:53:43.933731782+01:00","size":1019190827,"digest":"605bb25fbd99bc71baf607a9fba03e3ce73575e4e90ea2378c3f24578a28694b","details":{"parent_model":"LightOnOCR-3-0.8B.Q8_0.gguf","format":"gguf","family":"qwen35","families":["qwen35"],"parameter_size":"752.39M","quantization_level":"Q8_0","context_length":262144,"embedding_length":1024,"runner":"llamacpp"},"capabilities":["completion","vision","tools","thinking"]},{"name":"maternion/LightOnOCR-3:4b","model":"maternion/LightOnOCR-3:4b","modified_at":"2026-11-11T22:51:28.04473841+01:00","size":3384374666,"digest":"a1d387a47620c3e343cf8978e8fd63f5f677d2fa97bd5d3e28f031cc69b59748","details":{"parent_model":"LightOnOCR-3-4B.i1-Q4_K_M.gguf","format":"gguf","family":"qwen35","families":["qwen35"],"parameter_size":"4.2B","quantization_level":"Q4_K_M","context_length":262144,"embedding_length":2560,"runner":"llamacpp"},"capabilities":["completion","vision","tools","thinking"]},{"name":"deepseek-ocr:latest","model":"deepseek-ocr:latest","modified_at":"2026-11-11T22:49:31.646969001+01:00","size":6687240356,"digest":"0e7b018b8a22373167ee79c9a852821235488cbd2a2a5a93495558627423278c","details":{"parent_model":"","format":"gguf","family":"deepseekocr","families":["deepseekocr"],"parameter_size":"3.3B","quantization_level":"F16","context_length":8192,"embedding_length":1280,"runner":"ggml"},"capabilities":["completion","vision"]},{"name":"phonon:40m-en","model":"phonon:40m-en","modified_at":"2026-11-02T10:58:39.491697329+01:00","size":131759489,"digest":"b74a4edf2fe2cdc766ec44783089563fbf6c09a163846d7d0e1e316e98390029","details":{"parent_model":"","format":"safetensors","family":"","families":null,"parameter_size":"","quantization_level":"","runner":"mlx"},"capabilities":["speech"]},{"name":"phonon:40m-de","model":"phonon:40m-de","modified_at":"2026-10-30T16:24:22.463655473+01:00","size":125613369,"digest":"024449ea0a54272832611a4c38a16c3b2c8e67752a2e1a2fd0c4350b3561a905","details":{"parent_model":"","format":"safetensors","family":"","families":null,"parameter_size":"","quantization_level":"","runner":"mlx"},"capabilities":["speech"]},{"name":"glm-ocr:latest","model":"glm-ocr:latest","modified_at":"2026-07-27T10:24:59.910954687+02:00","size":2219299168,"digest":"6effedd0dc8aec66ad86c94b8099395376e212f22c87a9d7147c422f7e447be4","details":{"parent_model":"","format":"gguf","family":"glmocr","families":["glmocr"],"parameter_size":"1.1B","quantization_level":"F16","context_length":131072,"embedding_length":1536,"runner":"ggml"},"capabilities":["completion","vision","tools"]}]}
|
||||
@@ -0,0 +1,168 @@
|
||||
import Foundation
|
||||
import SprachmittlerTestSupport
|
||||
import Testing
|
||||
@testable import SprachmittlerOllama
|
||||
|
||||
@Suite("Ollama catalog")
|
||||
struct OllamaCatalogTests {
|
||||
@Test func decodesTagsAndFiltersHyMT3() throws {
|
||||
let envelope = try JSONDecoder().decode(TagsEnvelope.self, from: fixture("tags.json"))
|
||||
let hyMT3 = envelope.models.filter(\.isHyMT3)
|
||||
#expect(hyMT3.count == 1)
|
||||
#expect(hyMT3.first?.name.contains("Hy-MT3") == true)
|
||||
#expect(envelope.models.count > 1)
|
||||
#expect(!InstalledModel(name: "llama3:latest", model: "llama3:latest", digest: "abc").isHyMT3)
|
||||
#expect(InstalledModel(name: "x/HY-MT3-1.8B:Q4", model: "x", digest: "abc").isHyMT3)
|
||||
}
|
||||
|
||||
@Test func normalizesOnlyTrailingLatest() {
|
||||
#expect(InstalledModel.normalizedName("model:latest") == "model")
|
||||
#expect(InstalledModel.normalizedName("model:Q4_K_M") == "model:Q4_K_M")
|
||||
#expect(InstalledModel.normalizedName("model") == "model")
|
||||
#expect(InstalledModel.normalizedName("latest") == "latest")
|
||||
}
|
||||
|
||||
@Test func parsesQuotedStopParameters() throws {
|
||||
let details = try JSONDecoder().decode(ModelDetails.self, from: fixture(showFixtureName))
|
||||
#expect(details.supportsCompletion)
|
||||
#expect(details.capabilities == ["completion"])
|
||||
|
||||
let parameters = details.parsedParameters
|
||||
#expect(parameters.count == 4)
|
||||
#expect(parameters.allSatisfy { $0.name == "stop" })
|
||||
#expect(parameters.map(\.value).contains("<|startoftext|>"))
|
||||
#expect(parameters.map(\.value).contains("<|eos|>"))
|
||||
#expect(!parameters.map(\.value).contains { $0.hasPrefix("\"") })
|
||||
}
|
||||
|
||||
@Test func cachesShowDetailsByDigest() async throws {
|
||||
let tags = try fixture("tags.json")
|
||||
let show = try fixture(showFixtureName)
|
||||
let transport = FakeOllamaHTTPTransport { request in
|
||||
switch request.path {
|
||||
case "/api/tags":
|
||||
OllamaHTTPResponse(status: 200, body: tags)
|
||||
case "/api/show":
|
||||
OllamaHTTPResponse(status: 200, body: show)
|
||||
default:
|
||||
OllamaHTTPResponse(status: 404, body: Data())
|
||||
}
|
||||
}
|
||||
let catalog = OllamaCatalogClient(http: transport)
|
||||
|
||||
let models = try await catalog.installedModels()
|
||||
let model = try #require(models.first?.name)
|
||||
_ = try await catalog.show(model: model)
|
||||
_ = try await catalog.show(model: model)
|
||||
|
||||
let cachedCount = await transport.requests.filter { $0.path == "/api/show" }.count
|
||||
#expect(cachedCount == 1)
|
||||
|
||||
await catalog.refresh()
|
||||
_ = try await catalog.show(model: model)
|
||||
let refreshedCount = await transport.requests.filter { $0.path == "/api/show" }.count
|
||||
#expect(refreshedCount == 2)
|
||||
}
|
||||
|
||||
@Test func showWithoutTagsEntryStillFetchesShow() async throws {
|
||||
let tags = Data(#"{"models":[]}"#.utf8)
|
||||
let show = try fixture(showFixtureName)
|
||||
let transport = FakeOllamaHTTPTransport { request in
|
||||
switch request.path {
|
||||
case "/api/tags":
|
||||
OllamaHTTPResponse(status: 200, body: tags)
|
||||
case "/api/show":
|
||||
OllamaHTTPResponse(status: 200, body: show)
|
||||
default:
|
||||
OllamaHTTPResponse(status: 404, body: Data())
|
||||
}
|
||||
}
|
||||
let catalog = OllamaCatalogClient(http: transport)
|
||||
|
||||
let details = try await catalog.show(model: "missing-from-tags")
|
||||
#expect(details.capabilities == ["completion"])
|
||||
|
||||
let paths = await transport.requests.map(\.path)
|
||||
#expect(paths == ["/api/tags", "/api/show"])
|
||||
let models = await transport.models
|
||||
#expect(models == [nil, "missing-from-tags"])
|
||||
}
|
||||
|
||||
@Test func showForwardsTheModelOnlyToShowRequests() async throws {
|
||||
let tags = try fixture("tags.json")
|
||||
let show = try fixture(showFixtureName)
|
||||
let transport = FakeOllamaHTTPTransport { request in
|
||||
switch request.path {
|
||||
case "/api/tags":
|
||||
OllamaHTTPResponse(status: 200, body: tags)
|
||||
case "/api/show":
|
||||
OllamaHTTPResponse(status: 200, body: show)
|
||||
default:
|
||||
OllamaHTTPResponse(status: 404, body: Data())
|
||||
}
|
||||
}
|
||||
let catalog = OllamaCatalogClient(http: transport)
|
||||
let models = try await catalog.installedModels()
|
||||
let model = try #require(models.first?.name)
|
||||
_ = try await catalog.show(model: model)
|
||||
|
||||
let recorded = await transport.models
|
||||
#expect(recorded == [nil, model])
|
||||
}
|
||||
|
||||
@Test func refusesAnOldServerVersion() async throws {
|
||||
let current = FakeOllamaHTTPTransport { _ in
|
||||
OllamaHTTPResponse(status: 200, body: Data(#"{"version":"0.40.18"}"#.utf8))
|
||||
}
|
||||
try await OllamaCatalogClient(http: current).checkMinimumVersion()
|
||||
|
||||
let old = FakeOllamaHTTPTransport { _ in
|
||||
OllamaHTTPResponse(status: 200, body: Data(#"{"version":"0.39.9"}"#.utf8))
|
||||
}
|
||||
do {
|
||||
try await OllamaCatalogClient(http: old).checkMinimumVersion()
|
||||
Issue.record("expected unsupportedVersion")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .unsupportedVersion(found: "0.39.9", required: "0.40.0"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func comparesVersionsByComponent() throws {
|
||||
let current = try #require(OllamaVersion("0.40.18"))
|
||||
let older = try #require(OllamaVersion("0.40.9"))
|
||||
let tiny = try #require(OllamaVersion("0.9"))
|
||||
let minimum = try #require(OllamaVersion("0.40"))
|
||||
let padded = try #require(OllamaVersion("0.40.0"))
|
||||
let prerelease = try #require(OllamaVersion("0.40.18-rc1"))
|
||||
#expect(current > older)
|
||||
#expect(tiny < minimum)
|
||||
#expect(minimum == padded)
|
||||
#expect(prerelease == current)
|
||||
#expect(OllamaVersion("abc") == nil)
|
||||
#expect(OllamaVersion("") == nil)
|
||||
}
|
||||
|
||||
@Test func decodesLoadedModels() throws {
|
||||
let envelope = try JSONDecoder().decode(PsEnvelope.self, from: fixture("ps.json"))
|
||||
#expect(envelope.models.count == 1)
|
||||
#expect(envelope.models[0].name.contains("Hy-MT3"))
|
||||
#expect((envelope.models[0].size ?? 0) > 0)
|
||||
}
|
||||
|
||||
private func fixture(_ name: String) throws -> Data {
|
||||
let base = try #require(Bundle.module.resourceURL)
|
||||
return try Data(contentsOf: base.appendingPathComponent("Fixtures/\(name)"))
|
||||
}
|
||||
|
||||
private var showFixtureName: String {
|
||||
"show-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M.json"
|
||||
}
|
||||
}
|
||||
|
||||
private struct TagsEnvelope: Decodable {
|
||||
let models: [InstalledModel]
|
||||
}
|
||||
|
||||
private struct PsEnvelope: Decodable {
|
||||
let models: [LoadedModel]
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import Foundation
|
||||
import SprachmittlerTestSupport
|
||||
import Testing
|
||||
@testable import SprachmittlerOllama
|
||||
|
||||
@Suite("Ollama chat client", .serialized)
|
||||
struct OllamaChatClientTests {
|
||||
@Test func streamsSplitLinesAndFinalMetrics() async throws {
|
||||
let first = Data(#"{"message":{"role":"assistant","content":"Hallo"},"done":false}"#.utf8)
|
||||
let second = Data(#"{"message":{"role":"assistant","content":" Welt"},"done":false}"#.utf8)
|
||||
let final = Data((
|
||||
#"{"message":{"role":"assistant","content":""},"done":true,"#
|
||||
+ #""done_reason":"stop","total_duration":123,"eval_count":2}"#
|
||||
).utf8)
|
||||
let cut = first.count / 2
|
||||
ChatStubURLProtocol.reset(.init(chunks: [
|
||||
Data(first.prefix(cut)),
|
||||
Data(first.suffix(from: cut)) + Data("\n".utf8),
|
||||
second + Data("\n".utf8),
|
||||
final + Data("\n".utf8),
|
||||
]))
|
||||
defer { ChatStubURLProtocol.reset() }
|
||||
|
||||
let events = try await collect(chatClient().chat(request()))
|
||||
#expect(events.contains(.delta("Hallo")))
|
||||
#expect(events.contains(.delta(" Welt")))
|
||||
guard let last = events.last, case let .done(reason, metrics) = last else {
|
||||
Issue.record("missing done event")
|
||||
return
|
||||
}
|
||||
#expect(reason == "stop")
|
||||
#expect(metrics.totalDuration == 123)
|
||||
#expect(metrics.evalCount == 2)
|
||||
}
|
||||
|
||||
@Test func reportsStopAndLengthFromFixtures() async throws {
|
||||
let cases = [
|
||||
("chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-en-de.ndjson", "stop"),
|
||||
("chat-hf.co_tencent_Hy-MT3-7B-GGUF_Q4_K_M-truncated.ndjson", "length"),
|
||||
]
|
||||
for (fixtureName, expectedReason) in cases {
|
||||
try ChatStubURLProtocol.reset(.init(chunks: chunks(from: fixtureName)))
|
||||
let events = try await collect(chatClient().chat(request()))
|
||||
guard let last = events.last, case let .done(reason, _) = last else {
|
||||
Issue.record("missing done event for \(fixtureName)")
|
||||
continue
|
||||
}
|
||||
#expect(reason == expectedReason)
|
||||
}
|
||||
ChatStubURLProtocol.reset()
|
||||
}
|
||||
|
||||
@Test func streamEndingWithoutDoneFails() async throws {
|
||||
let delta = Data(#"{"message":{"content":"Hallo"},"done":false}"#.utf8) + Data("\n".utf8)
|
||||
ChatStubURLProtocol.reset(.init(chunks: [delta]))
|
||||
defer { ChatStubURLProtocol.reset() }
|
||||
|
||||
do {
|
||||
_ = try await collect(chatClient().chat(request()))
|
||||
Issue.record("expected missing done error")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .decoding("Stream ended without a done event"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func midStreamErrorLineFailsTheStream() async throws {
|
||||
ChatStubURLProtocol.reset(.init(chunks: [
|
||||
Data(#"{"message":{"content":"Hallo"},"done":false}"#.utf8) + Data("\n".utf8),
|
||||
Data(#"{"error":"model 'missing' not found"}"#.utf8) + Data("\n".utf8),
|
||||
]))
|
||||
defer { ChatStubURLProtocol.reset() }
|
||||
|
||||
do {
|
||||
_ = try await collect(chatClient().chat(request(model: "missing")))
|
||||
Issue.record("expected error")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .modelNotInstalled("missing"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func firstTokenTimeoutFires() async throws {
|
||||
let sleeper = ManualSleeper()
|
||||
ChatStubURLProtocol.reset(.init(chunks: [], hangAfterChunks: true))
|
||||
defer { ChatStubURLProtocol.reset() }
|
||||
|
||||
let client = try chatClient(sleeper: sleeper, timeouts: testTimeouts)
|
||||
let task = Task {
|
||||
try await collect(client.chat(request()))
|
||||
}
|
||||
await sleeper.waitUntilPending(.seconds(1))
|
||||
for _ in 0 ..< 1000 {
|
||||
if ChatStubURLProtocol.started() {
|
||||
break
|
||||
}
|
||||
await Task.yield()
|
||||
}
|
||||
await sleeper.advance(matching: .seconds(1))
|
||||
|
||||
do {
|
||||
_ = try await task.value
|
||||
Issue.record("expected first-token timeout")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .timeout(.firstToken))
|
||||
}
|
||||
for _ in 0 ..< 1000 {
|
||||
if ChatStubURLProtocol.stopped() {
|
||||
break
|
||||
}
|
||||
await Task.yield()
|
||||
}
|
||||
#expect(ChatStubURLProtocol.stopped())
|
||||
}
|
||||
|
||||
@Test func idleTimeoutFiresAfterFirstDelta() async throws {
|
||||
let sleeper = ManualSleeper()
|
||||
let delta = Data(#"{"message":{"content":"Hallo"},"done":false}"#.utf8) + Data("\n".utf8)
|
||||
ChatStubURLProtocol.reset(.init(chunks: [delta], hangAfterChunks: true))
|
||||
defer { ChatStubURLProtocol.reset() }
|
||||
|
||||
let client = try chatClient(sleeper: sleeper, timeouts: testTimeouts)
|
||||
let task = Task {
|
||||
try await collect(client.chat(request()))
|
||||
}
|
||||
await sleeper.waitUntilPending(.seconds(2))
|
||||
await sleeper.advance(matching: .seconds(2))
|
||||
|
||||
do {
|
||||
_ = try await task.value
|
||||
Issue.record("expected idle timeout")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .timeout(.idle))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func totalTimeoutFires() async throws {
|
||||
let sleeper = ManualSleeper()
|
||||
ChatStubURLProtocol.reset(.init(chunks: [], hangAfterChunks: true))
|
||||
defer { ChatStubURLProtocol.reset() }
|
||||
|
||||
let client = try chatClient(sleeper: sleeper, timeouts: testTimeouts)
|
||||
let task = Task {
|
||||
try await collect(client.chat(request()))
|
||||
}
|
||||
await sleeper.waitUntilPending(.seconds(3))
|
||||
await sleeper.advance(matching: .seconds(3))
|
||||
|
||||
do {
|
||||
_ = try await task.value
|
||||
Issue.record("expected total timeout")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .timeout(.total))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func cancelMidStreamStopsURLTask() async throws {
|
||||
let sleeper = ManualSleeper()
|
||||
let delta = Data(#"{"message":{"content":"Hallo"},"done":false}"#.utf8) + Data("\n".utf8)
|
||||
ChatStubURLProtocol.reset(.init(chunks: [delta], hangAfterChunks: true))
|
||||
defer { ChatStubURLProtocol.reset() }
|
||||
|
||||
let client = try chatClient(sleeper: sleeper, timeouts: testTimeouts)
|
||||
let task = Task {
|
||||
try await collect(client.chat(request()))
|
||||
}
|
||||
await sleeper.waitUntilPending(.seconds(2))
|
||||
task.cancel()
|
||||
|
||||
do {
|
||||
_ = try await task.value
|
||||
} catch {
|
||||
// The consumer task is cancelled; the stream is expected to throw.
|
||||
}
|
||||
for _ in 0 ..< 1000 {
|
||||
if ChatStubURLProtocol.stopped() {
|
||||
break
|
||||
}
|
||||
await Task.yield()
|
||||
}
|
||||
#expect(ChatStubURLProtocol.stopped())
|
||||
}
|
||||
|
||||
@Test func encodesExactChatRequest() throws {
|
||||
let data = try JSONEncoder().encode(request())
|
||||
let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
#expect(Set(object.keys) == ["model", "messages", "stream", "keep_alive", "options"])
|
||||
#expect(object["stream"] as? Bool == true)
|
||||
#expect(object["system"] == nil)
|
||||
#expect(object["images"] == nil)
|
||||
#expect(object["think"] == nil)
|
||||
|
||||
let options = try #require(object["options"] as? [String: Any])
|
||||
#expect(
|
||||
Set(options.keys)
|
||||
== ["temperature", "top_p", "top_k", "repeat_penalty", "num_predict", "num_ctx"]
|
||||
)
|
||||
let messages = try #require(object["messages"] as? [[String: Any]])
|
||||
#expect(messages.count == 1)
|
||||
#expect(messages[0]["role"] as? String == "user")
|
||||
}
|
||||
|
||||
private var testTimeouts: ChatTimeouts {
|
||||
ChatTimeouts(firstToken: .seconds(1), idle: .seconds(2), total: .seconds(3))
|
||||
}
|
||||
|
||||
private func request(model: String = "test-model") -> ChatRequest {
|
||||
ChatRequest(
|
||||
model: model,
|
||||
messages: [ChatMessage(content: "Hello.")],
|
||||
keepAlive: "5m",
|
||||
options: ChatOptions(
|
||||
temperature: 0.7,
|
||||
topP: 0.6,
|
||||
topK: 20,
|
||||
repeatPenalty: 1.05,
|
||||
numPredict: 4096,
|
||||
numCtx: 8192
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private func chatClient(
|
||||
sleeper: ManualSleeper = ManualSleeper(),
|
||||
timeouts: ChatTimeouts = .standard
|
||||
) throws -> OllamaChatClient {
|
||||
try OllamaChatClient(http: makeClient(), sleeper: sleeper, timeouts: timeouts)
|
||||
}
|
||||
|
||||
private func collect(
|
||||
_ stream: AsyncThrowingStream<ChatEvent, any Error>
|
||||
) async throws -> [ChatEvent] {
|
||||
var events: [ChatEvent] = []
|
||||
for try await event in stream {
|
||||
events.append(event)
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
private func chunks(from fixtureName: String) throws -> [Data] {
|
||||
let base = try #require(Bundle.module.resourceURL)
|
||||
let url = base.appendingPathComponent("Fixtures/\(fixtureName)")
|
||||
let text = try String(contentsOf: url, encoding: .utf8)
|
||||
return text.split(separator: "\n", omittingEmptySubsequences: true)
|
||||
.map { Data($0.utf8) + Data("\n".utf8) }
|
||||
}
|
||||
|
||||
private func makeClient() throws -> OllamaHTTPClient {
|
||||
let url = try #require(URL(string: "http://127.0.0.1:11434"))
|
||||
let configuration = OllamaSessionFactory.makeConfiguration()
|
||||
configuration.protocolClasses = [ChatStubURLProtocol.self]
|
||||
let session = URLSession(
|
||||
configuration: configuration,
|
||||
delegate: RedirectRefusingDelegate(),
|
||||
delegateQueue: nil
|
||||
)
|
||||
return try OllamaHTTPClient(baseURL: url, session: session)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import SprachmittlerOllama
|
||||
|
||||
@Suite("Ollama error body")
|
||||
struct OllamaErrorBodyTests {
|
||||
@Test func decodesTheRecordedMissingModelBody() throws {
|
||||
let url = try #require(Bundle.module.resourceURL)
|
||||
.appendingPathComponent("Fixtures/error-missing-model.json")
|
||||
let data = try Data(contentsOf: url)
|
||||
let message = try #require(OllamaErrorBody.message(from: data))
|
||||
#expect(message.localizedCaseInsensitiveContains("not found"))
|
||||
}
|
||||
|
||||
@Test func fallsBackToPlainText() {
|
||||
let message = OllamaErrorBody.message(from: Data("plain error".utf8))
|
||||
#expect(message == "plain error")
|
||||
}
|
||||
|
||||
@Test func truncatesToFiveHundredCharacters() throws {
|
||||
let long = String(repeating: "x", count: 600)
|
||||
let message = try #require(OllamaErrorBody.message(from: Data(long.utf8)))
|
||||
#expect(message.count == 500)
|
||||
}
|
||||
|
||||
@Test func returnsNilForEmptyBody() {
|
||||
#expect(OllamaErrorBody.message(from: Data()) == nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import SprachmittlerOllama
|
||||
|
||||
/// HTTP transport tests share `StubURLProtocol`; the suite is serialized so the static stub
|
||||
/// cannot leak between tests.
|
||||
@Suite("Ollama HTTP transport", .serialized)
|
||||
struct OllamaTransportTests {
|
||||
@Test func sendsGETAndReturnsBody() async throws {
|
||||
StubURLProtocol.reset(.init(chunks: [Data(#"{"version":"0.40.18"}"#.utf8)]))
|
||||
defer { StubURLProtocol.reset() }
|
||||
|
||||
let client = try makeClient()
|
||||
let response = try await client.send(.init(path: "/api/version"))
|
||||
#expect(response.status == 200)
|
||||
#expect(String(data: response.body, encoding: .utf8) == #"{"version":"0.40.18"}"#)
|
||||
}
|
||||
|
||||
@Test func maps404ModelNotFound() async throws {
|
||||
StubURLProtocol.reset(.init(
|
||||
status: 404,
|
||||
chunks: [Data(#"{"error":"model 'missing' not found"}"#.utf8)]
|
||||
))
|
||||
defer { StubURLProtocol.reset() }
|
||||
|
||||
let client = try makeClient()
|
||||
do {
|
||||
_ = try await client.send(.init(path: "/api/chat"), model: "missing")
|
||||
Issue.record("expected modelNotInstalled")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .modelNotInstalled("missing"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func maps400And500() async throws {
|
||||
let client = try makeClient()
|
||||
|
||||
StubURLProtocol.reset(.init(status: 400, chunks: [Data(#"{"error":"bad input"}"#.utf8)]))
|
||||
do {
|
||||
_ = try await client.send(.init(path: "/api/chat"))
|
||||
Issue.record("expected badRequest")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .badRequest("bad input"))
|
||||
}
|
||||
|
||||
StubURLProtocol.reset(.init(status: 500, chunks: [Data(#"{"error":"out of memory"}"#.utf8)]))
|
||||
do {
|
||||
_ = try await client.send(.init(path: "/api/chat"))
|
||||
Issue.record("expected server")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .server(status: 500, message: "out of memory"))
|
||||
}
|
||||
StubURLProtocol.reset()
|
||||
}
|
||||
|
||||
@Test func mapsTransportFailures() async throws {
|
||||
let client = try makeClient()
|
||||
|
||||
StubURLProtocol.reset(.init(error: URLError(.cannotConnectToHost)))
|
||||
do {
|
||||
_ = try await client.send(.init(path: "/api/version"))
|
||||
Issue.record("expected unreachable")
|
||||
} catch let error as OllamaError {
|
||||
guard case .unreachable = error else {
|
||||
Issue.record("expected unreachable, got \(error)")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
StubURLProtocol.reset(.init(error: URLError(.timedOut)))
|
||||
do {
|
||||
_ = try await client.send(.init(path: "/api/version"))
|
||||
Issue.record("expected timeout")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .timeout(.connect))
|
||||
}
|
||||
StubURLProtocol.reset()
|
||||
}
|
||||
|
||||
@Test func decodesJSONAndRejectsMalformedJSON() async throws {
|
||||
StubURLProtocol.reset(.init(chunks: [Data(#"{"version":"0.40.18"}"#.utf8)]))
|
||||
let client = try makeClient()
|
||||
let version = try await client.sendJSON(.init(path: "/api/version"), as: VersionResponse.self)
|
||||
#expect(version.version == "0.40.18")
|
||||
|
||||
StubURLProtocol.reset(.init(chunks: [Data("not json".utf8)]))
|
||||
do {
|
||||
_ = try await client.sendJSON(.init(path: "/api/version"), as: VersionResponse.self)
|
||||
Issue.record("expected decoding error")
|
||||
} catch let error as OllamaError {
|
||||
guard case .decoding = error else {
|
||||
Issue.record("expected decoding, got \(error)")
|
||||
return
|
||||
}
|
||||
}
|
||||
StubURLProtocol.reset()
|
||||
}
|
||||
|
||||
@Test func joinsPathsWithoutDoubleSlash() throws {
|
||||
let client = try makeClient()
|
||||
#expect(
|
||||
try client.makeURL(for: "/api/version").absoluteString
|
||||
== "http://127.0.0.1:11434/api/version"
|
||||
)
|
||||
#expect(
|
||||
try client.makeURL(for: "api/tags").absoluteString
|
||||
== "http://127.0.0.1:11434/api/tags"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func joinsPathsWithTrailingSlashAndBasePath() throws {
|
||||
let trailing = try makeClient(baseURL: "http://127.0.0.1:11434/")
|
||||
#expect(
|
||||
try trailing.makeURL(for: "/api/tags").absoluteString
|
||||
== "http://127.0.0.1:11434/api/tags"
|
||||
)
|
||||
|
||||
let basePath = try makeClient(baseURL: "http://127.0.0.1:11434/ollama/")
|
||||
#expect(
|
||||
try basePath.makeURL(for: "/api/tags").absoluteString
|
||||
== "http://127.0.0.1:11434/ollama/api/tags"
|
||||
)
|
||||
|
||||
let baseNoSlash = try makeClient(baseURL: "http://127.0.0.1:11434/ollama")
|
||||
#expect(
|
||||
try baseNoSlash.makeURL(for: "/api/tags").absoluteString
|
||||
== "http://127.0.0.1:11434/ollama/api/tags"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func setsJSONHeadersOnPOST() async throws {
|
||||
StubURLProtocol.reset(.init(chunks: [Data(#"{"ok":true}"#.utf8)]))
|
||||
defer { StubURLProtocol.reset() }
|
||||
|
||||
let client = try makeClient()
|
||||
_ = try await client.send(.init(
|
||||
method: .post,
|
||||
path: "/api/show",
|
||||
body: Data(#"{"model":"x"}"#.utf8)
|
||||
))
|
||||
let request = try #require(StubURLProtocol.snapshot().lastRequest)
|
||||
#expect(request.httpMethod == "POST")
|
||||
#expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json")
|
||||
#expect(request.value(forHTTPHeaderField: "Accept") == "application/json")
|
||||
}
|
||||
|
||||
@Test func delegatePassesNilToTheCompletionHandler() throws {
|
||||
let url = try #require(URL(string: "http://127.0.0.1:11434/redirect"))
|
||||
let delegate = RedirectRefusingDelegate()
|
||||
let session = URLSession(configuration: .ephemeral)
|
||||
let task = session.dataTask(with: url)
|
||||
let response = try #require(HTTPURLResponse(
|
||||
url: url,
|
||||
statusCode: 302,
|
||||
httpVersion: nil,
|
||||
headerFields: ["Location": "https://example.com/steal"]
|
||||
))
|
||||
let box = RedirectResultBox()
|
||||
|
||||
delegate.urlSession(
|
||||
session,
|
||||
task: task,
|
||||
willPerformHTTPRedirection: response,
|
||||
newRequest: URLRequest(url: url)
|
||||
) { request in
|
||||
box.record(request)
|
||||
}
|
||||
|
||||
#expect(box.wasCalled)
|
||||
#expect(box.request == nil)
|
||||
}
|
||||
|
||||
@Test func clientRefusesA302WithoutRequestingTheTarget() async throws {
|
||||
StubURLProtocol.reset(.init(
|
||||
status: 302,
|
||||
headers: ["Location": "https://example.com/steal"],
|
||||
chunks: []
|
||||
))
|
||||
defer { StubURLProtocol.reset() }
|
||||
|
||||
let client = try makeClient()
|
||||
do {
|
||||
_ = try await client.send(.init(path: "/api/version"))
|
||||
Issue.record("expected redirect rejection")
|
||||
} catch let error as OllamaError {
|
||||
#expect(error == .endpointRejected(.redirect))
|
||||
}
|
||||
|
||||
let snapshot = StubURLProtocol.snapshot()
|
||||
#expect(snapshot.count == 1)
|
||||
#expect(snapshot.lastRequest?.url?.host == "127.0.0.1")
|
||||
#expect(client.session.delegate is RedirectRefusingDelegate)
|
||||
}
|
||||
|
||||
private func makeClient(baseURL: String = "http://127.0.0.1:11434") throws -> OllamaHTTPClient {
|
||||
let url = try #require(URL(string: baseURL))
|
||||
let configuration = OllamaSessionFactory.makeConfiguration()
|
||||
configuration.protocolClasses = [StubURLProtocol.self]
|
||||
let session = URLSession(
|
||||
configuration: configuration,
|
||||
delegate: RedirectRefusingDelegate(),
|
||||
delegateQueue: nil
|
||||
)
|
||||
return try OllamaHTTPClient(baseURL: url, session: session)
|
||||
}
|
||||
}
|
||||
|
||||
private struct VersionResponse: Decodable {
|
||||
let version: String
|
||||
}
|
||||
|
||||
/// A synchronous result box for the delegate callback; the callback is not concurrent here.
|
||||
private final class RedirectResultBox: @unchecked Sendable {
|
||||
private(set) var wasCalled = false
|
||||
private(set) var request: URLRequest?
|
||||
|
||||
func record(_ request: URLRequest?) {
|
||||
wasCalled = true
|
||||
self.request = request
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import SprachmittlerOllama
|
||||
|
||||
@Suite("Warm-up policy")
|
||||
struct OllamaWarmUpPolicyTests {
|
||||
@Test func allowsOnlyEnabledLoopbackEndpoints() throws {
|
||||
let local = try #require(URL(string: "http://127.0.0.1:11434"))
|
||||
let remote = try #require(URL(string: "https://example.com:11434"))
|
||||
#expect(OllamaWarmUpPolicy.shouldWarmUp(endpoint: local, enabled: true))
|
||||
#expect(!OllamaWarmUpPolicy.shouldWarmUp(endpoint: local, enabled: false))
|
||||
#expect(!OllamaWarmUpPolicy.shouldWarmUp(endpoint: remote, enabled: true))
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import Foundation
|
||||
import SprachmittlerTestSupport
|
||||
import Testing
|
||||
@testable import SprachmittlerOllama
|
||||
|
||||
@Suite("Warm-up runner")
|
||||
struct OllamaWarmUpRunnerTests {
|
||||
@Test func consumesAndDiscardsEvents() async throws {
|
||||
let box = RequestBox()
|
||||
let chat = FakeOllamaChat(
|
||||
events: [.delta("ignored"), .done(reason: "length", metrics: .empty)],
|
||||
onRequest: { box.record($0) }
|
||||
)
|
||||
let request = ChatRequest(
|
||||
model: "test-model",
|
||||
messages: [ChatMessage(content: "Hello.")],
|
||||
keepAlive: "30m",
|
||||
options: ChatOptions(
|
||||
temperature: 0.7,
|
||||
topP: 0.6,
|
||||
topK: 20,
|
||||
repeatPenalty: 1.05,
|
||||
numPredict: 8,
|
||||
numCtx: 8192
|
||||
)
|
||||
)
|
||||
|
||||
try await OllamaWarmUpRunner(chat: chat).run(request)
|
||||
#expect(box.request?.messages.first?.content == "Hello.")
|
||||
#expect(box.request?.options.numPredict == 8)
|
||||
}
|
||||
|
||||
@Test func manualSleeperCancellationResumes() async throws {
|
||||
let sleeper = ManualSleeper()
|
||||
let task = Task {
|
||||
try await sleeper.sleep(for: .seconds(1))
|
||||
}
|
||||
await sleeper.waitUntilPending(.seconds(1))
|
||||
task.cancel()
|
||||
|
||||
do {
|
||||
_ = try await task.value
|
||||
Issue.record("expected cancellation")
|
||||
} catch is CancellationError {
|
||||
// Expected.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class RequestBox: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var value: ChatRequest?
|
||||
|
||||
var request: ChatRequest? {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return value
|
||||
}
|
||||
|
||||
func record(_ request: ChatRequest) {
|
||||
lock.lock()
|
||||
value = request
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import SprachmittlerOllama
|
||||
|
||||
@Test func moduleLinks() {
|
||||
#expect(SprachmittlerOllamaModule.moduleName == "SprachmittlerOllama")
|
||||
}
|
||||
|
||||
/// T1.1: the recorded Ollama fixtures are bundled with the test target.
|
||||
@Test func recordedFixturesAreBundled() throws {
|
||||
let base = try #require(Bundle.module.resourceURL).appendingPathComponent("Fixtures")
|
||||
let names = ["version.json", "tags.json", "capture-meta.json"]
|
||||
for name in names {
|
||||
let url = base.appendingPathComponent(name)
|
||||
#expect(FileManager.default.fileExists(atPath: url.path), "missing fixture \(name)")
|
||||
}
|
||||
let chats = try FileManager.default.contentsOfDirectory(atPath: base.path)
|
||||
.filter { $0.hasPrefix("chat-") && $0.hasSuffix(".ndjson") }
|
||||
#expect(!chats.isEmpty)
|
||||
}
|
||||
|
||||
@Test func recordedVersionIsDecodable() throws {
|
||||
let base = try #require(Bundle.module.resourceURL).appendingPathComponent("Fixtures")
|
||||
let data = try Data(contentsOf: base.appendingPathComponent("version.json"))
|
||||
let object = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
let version = try #require(object["version"] as? String)
|
||||
#expect(!version.isEmpty)
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
import Foundation
|
||||
|
||||
/// A chat-only URLProtocol stub. It has its own static state, so the chat suite can run in
|
||||
/// parallel with the HTTP transport suite.
|
||||
final class ChatStubURLProtocol: URLProtocol, @unchecked Sendable {
|
||||
struct Stub: Sendable {
|
||||
var chunks: [Data] = []
|
||||
var hangAfterChunks = false
|
||||
}
|
||||
|
||||
private static let lock = NSLock()
|
||||
private nonisolated(unsafe) static var stub: Stub?
|
||||
private nonisolated(unsafe) static var wasStopped = false
|
||||
private nonisolated(unsafe) static var wasStarted = false
|
||||
|
||||
static func reset(_ stub: Stub? = nil) {
|
||||
lock.lock()
|
||||
self.stub = stub
|
||||
wasStopped = false
|
||||
wasStarted = false
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
static func stopped() -> Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return wasStopped
|
||||
}
|
||||
|
||||
static func started() -> Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return wasStarted
|
||||
}
|
||||
|
||||
private static func beginRequest() -> Stub? {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
wasStarted = true
|
||||
return stub
|
||||
}
|
||||
|
||||
override static func canInit(with request: URLRequest) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
override static func canonicalRequest(for request: URLRequest) -> URLRequest {
|
||||
request
|
||||
}
|
||||
|
||||
override func startLoading() {
|
||||
guard let stub = Self.beginRequest() else {
|
||||
client?.urlProtocol(self, didFailWithError: URLError(.unknown))
|
||||
return
|
||||
}
|
||||
guard let url = request.url,
|
||||
let response = HTTPURLResponse(
|
||||
url: url,
|
||||
statusCode: 200,
|
||||
httpVersion: "HTTP/1.1",
|
||||
headerFields: ["Content-Type": "application/x-ndjson"]
|
||||
)
|
||||
else {
|
||||
client?.urlProtocol(self, didFailWithError: URLError(.badURL))
|
||||
return
|
||||
}
|
||||
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
||||
for chunk in stub.chunks {
|
||||
client?.urlProtocol(self, didLoad: chunk)
|
||||
}
|
||||
if !stub.hangAfterChunks {
|
||||
client?.urlProtocolDidFinishLoading(self)
|
||||
}
|
||||
}
|
||||
|
||||
override func stopLoading() {
|
||||
Self.lock.lock()
|
||||
Self.wasStopped = true
|
||||
Self.lock.unlock()
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
import Foundation
|
||||
|
||||
/// A serialized `URLProtocol` stub for contract tests. Test suites using it must be `.serialized`.
|
||||
final class StubURLProtocol: URLProtocol, @unchecked Sendable {
|
||||
struct Stub: Sendable {
|
||||
var status = 200
|
||||
var headers: [String: String] = ["Content-Type": "application/json"]
|
||||
var chunks: [Data] = []
|
||||
var error: URLError?
|
||||
var hangAfterChunks = false
|
||||
}
|
||||
|
||||
struct Snapshot: Sendable {
|
||||
let count: Int
|
||||
let stopped: Bool
|
||||
let lastRequest: URLRequest?
|
||||
}
|
||||
|
||||
private static let lock = NSLock()
|
||||
private nonisolated(unsafe) static var stub: Stub?
|
||||
private nonisolated(unsafe) static var requestCount = 0
|
||||
private nonisolated(unsafe) static var wasStopped = false
|
||||
private nonisolated(unsafe) static var lastRequestValue: URLRequest?
|
||||
|
||||
static func reset(_ stub: Stub? = nil) {
|
||||
lock.lock()
|
||||
self.stub = stub
|
||||
requestCount = 0
|
||||
wasStopped = false
|
||||
lastRequestValue = nil
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
static func snapshot() -> Snapshot {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return Snapshot(count: requestCount, stopped: wasStopped, lastRequest: lastRequestValue)
|
||||
}
|
||||
|
||||
private static func beginRequest(_ request: URLRequest) -> Stub? {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
requestCount += 1
|
||||
lastRequestValue = request
|
||||
return stub
|
||||
}
|
||||
|
||||
override static func canInit(with request: URLRequest) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
override static func canonicalRequest(for request: URLRequest) -> URLRequest {
|
||||
request
|
||||
}
|
||||
|
||||
override func startLoading() {
|
||||
guard let stub = Self.beginRequest(request) else {
|
||||
client?.urlProtocol(self, didFailWithError: URLError(.unknown))
|
||||
return
|
||||
}
|
||||
if let error = stub.error {
|
||||
client?.urlProtocol(self, didFailWithError: error)
|
||||
return
|
||||
}
|
||||
guard let url = request.url,
|
||||
let response = HTTPURLResponse(
|
||||
url: url,
|
||||
statusCode: stub.status,
|
||||
httpVersion: "HTTP/1.1",
|
||||
headerFields: stub.headers
|
||||
)
|
||||
else {
|
||||
client?.urlProtocol(self, didFailWithError: URLError(.badURL))
|
||||
return
|
||||
}
|
||||
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
||||
for chunk in stub.chunks {
|
||||
client?.urlProtocol(self, didLoad: chunk)
|
||||
}
|
||||
if !stub.hangAfterChunks {
|
||||
client?.urlProtocolDidFinishLoading(self)
|
||||
}
|
||||
}
|
||||
|
||||
override func stopLoading() {
|
||||
Self.lock.lock()
|
||||
Self.wasStopped = true
|
||||
Self.lock.unlock()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user