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