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
@@ -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")
|
||||
}
|
||||
Reference in new issue
Block a user