Turn model probabilities into typed decisions your Swift app can act on.
SwiftDecision gives applications a small, composable decision layer for AI-powered classification, routing, yes/no checks, and rubric scoring. Ask a model to choose from your options; get a typed value with its probabilities, confidence, and an explicit outcome. If a result does not meet your policy, SwiftDecision can abstain or return your chosen fallback.
Use hosted providers such as SwiftJev, run the English Laya model locally with native Apple MLX, or provide your own backend. SpecificationCore powers request and output validation, ordered policy routing, and decision composition inside the package.
Models propose. Your application keeps control of policy and action.
- Use model decisions as Swift values.
choicepreserves your typed labels;noulreturnsBool;scorereturns a selected rubric level and an expected numeric value. - Handle uncertainty explicitly. Configure acceptance thresholds and choose between an accepted result, abstention for review, or an application-defined fallback.
- Keep backends replaceable. Use Jev, local Laya with the optional
MLXtrait, or any type that conforms toDecisionBackend. - Compose with SpecificationCore. Async specifications validate inputs and predictions, select policies in order, and wrap backend evaluation.
- Own operational behavior. SwiftDecision checks cancellation, supports inference timeouts, and can emit content-free traces and metrics.
Embed typed decisions in the workflows your app already owns. Connect the result to your UI, queue, or next action in application code.
In your Package.swift:
dependencies: [
.package(url: "https://github.com/SoundBlaster/SwiftDecision.git", from: "0.7.0")
],If your app still supports iOS 13 or 14, constrain resolution to the compatible 0.3 series. The up-to-next-minor requirement excludes 0.4.0 and later:
dependencies: [
.package(
url: "https://github.com/SoundBlaster/SwiftDecision.git",
.upToNextMinor(from: "0.3.0")
)
],Add the product to your target:
.product(name: "SwiftDecision", package: "SwiftDecision")If you use OpenAI's Decisions API, also add its optional product to the target:
.product(name: "SwiftDecisionOpenAI", package: "SwiftDecision")Set TYPESAFE_API_KEY in your environment, then use a backend and engine:
export TYPESAFE_API_KEY="your-api-key"import SwiftDecision
enum InboxRoute: Sendable, Hashable {
case billing
case support
case manualReview
}
@main
struct InboxTriage {
static func main() async throws {
let backend = ClosureDecisionBackend { _ in
DecisionPrediction(probabilities: [0.05, 0.90, 0.05], modelIdentifier: "fixture")
}
let engine = DecisionEngine(
backend: backend,
configuration: .init(timeout: 8)
)
let result = try await engine.choice(
instructions: "Choose the best team for this customer message.",
context: "I was charged twice for my subscription.",
options: [
ChoiceOption(label: InboxRoute.billing, description: "billing: invoices, refunds, and charges"),
ChoiceOption(label: InboxRoute.support, description: "support: account access and product use"),
ChoiceOption(label: InboxRoute.manualReview, description: "manual review: the right team is unclear")
],
fallback: .manualReview
)
switch result.outcome {
case let .accepted(route):
print("Route to: \(route)")
case let .abstained(reason):
print("Review required: \(reason)")
case let .fallback(route, reason):
print("Use \(route); model result did not meet policy: \(reason)")
}
}
}choice returns DecisionResult<InboxRoute>. The model never has to generate or parse your app's enum: SwiftDecision maps the winning option back to its original typed label. noul evaluates a Boolean statement; score evaluates an ordered rubric and also reports the probability-weighted expected value.
For a no-network example that runs with deterministic fixture responses:
swift run InboxTriageExampleEvery decision is resolved against the policy configured for its kind:
- Accepted: the best option satisfies your probability and confidence thresholds.
- Abstained: no result satisfies policy and no fallback was supplied; route it to a person or another system.
- Fallback: no result satisfies policy, so SwiftDecision returns the fallback you explicitly provided.
- Thrown error: invalid input, invalid backend output, provider errors, cancellation, and timeouts remain errors. They are not disguised as abstentions.
Set independent thresholds for each decision kind:
let policies = DecisionPolicies(
noul: DecisionPolicy(minimumProbability: 0.7),
choice: DecisionPolicy(minimumProbability: 0.75, minimumConfidence: 0.1),
score: DecisionPolicy(minimumProbability: 0.6)
)
let engine = DecisionEngine(
backend: backend,
configuration: .init(policies: policies, timeout: 8)
)SwiftDecision validates that backend probabilities match the request, are finite and nonnegative, and are normalized. These checks protect the decision boundary. Evaluate model accuracy and tune thresholds and fallbacks on your own data.
TypeSafe Jev is available as the separate SwiftJev package. It conforms to DecisionBackend and keeps the hosted provider and HTTP transport outside the core decision library.
OpenAI's Decisions API is available through the optional SwiftDecisionOpenAI product in this package. It uses the native /v1/decisions REST API without adding an OpenAI SDK or network dependency to the core SwiftDecision product. See OpenAI Decisions for setup and the current text-only mapping.
The non-default MLX SwiftPM Trait enables LayaMLXBackend, which runs the English aac6fef/laya-mlx checkpoint published by Convai Innovations locally with MLX. It does not invoke Python or download model weights at runtime. Provide a local checkpoint directory. The backend requires Apple Silicon, macOS 14+ or iOS 17+, and SwiftPM 6.3+. SwiftPM can still resolve or fetch optional packages during dependency resolution when the trait is disabled; the trait controls whether the MLX API and products are enabled for the target.
Enable the trait in the consuming package:
.package(
url: "https://github.com/SoundBlaster/SwiftDecision.git",
from: "0.7.0",
traits: ["MLX"]
)Build and test the MLX configuration on Apple Silicon:
swift build --traits MLX --triple arm64-apple-macosx14.0
swift test --traits MLX --triple arm64-apple-macosx14.0For a local checkpoint smoke test, set SWIFTDECISION_LAYA_CHECKPOINT to its directory. For numerical parity against Python Laya-MLX, also provide SWIFTDECISION_LAYA_REFERENCE_JSON with fixed Noul, Choice, and Score reference outputs:
Generate a reference file with the Python implementation and the same checkpoint:
python3 -m pip install laya-mlx
python3 Scripts/generate_laya_reference.py \
--checkpoint /path/to/laya-mlx \
--output /path/to/laya-reference.json \
--dtype float16SWIFTDECISION_LAYA_CHECKPOINT=/path/to/laya-mlx \
SWIFTDECISION_LAYA_REFERENCE_JSON=/path/to/laya-reference.json \
SWIFTDECISION_LAYA_PRECISION=float16 \
swift test --traits MLX --triple arm64-apple-macosx14.0 --filter LayaParityTestsThe parity check requires matching selected option identifiers and compares probabilities within 0.0001 for FP32 or 0.02 for FP16. It verifies runtime compatibility for those test inputs, not model quality on arbitrary application data. See the Laya MLX inference pipeline for the model input and native forward pass. The model weights are not redistributed; see NOTICE and the model card for terms.
The optional SwiftDecisionGLiNER product and GLiNER trait provide
GLiNERCoreMLBackend for a locally provisioned fastino/gliner2.5-small-v1
classification export, on macOS 14+ and iOS 17+. Neither weights nor Python,
PyTorch, or MLX are linked into an app by this adapter. The default INT8 export
is about 78 MB plus an 8.3 MB tokenizer; download/provision these assets separately
if the application must stay small.
This is a classification pilot, not a calibrated or general-purpose Jev replacement. See setup, output contract, measurements, and known errors.
Implement DecisionBackend to connect another provider or an application-owned model. ClosureDecisionBackend is available for simple adapters, deterministic tests, and offline examples:
let backend = ClosureDecisionBackend { prompt in
// Return one probability per prompt option, in the original order.
DecisionPrediction(probabilities: [0.08, 0.92], modelIdentifier: "my-provider")
}Tracing is enabled by default. result.trace records content-free decision lifecycle checkpoints and model identifiers; result.specificationTrace retains nested SpecificationCore events for request validation, ordered policy routing, backend evaluation, output validation, and acceptance policy checks. Use result.orderedTrace when you need their actual interleaving: lifecycle events have a point position, while Core events retain start and completion positions.
let result = try await engine.choice(
instructions: "Choose a team.",
context: "The customer was charged twice.",
options: options
)
for record in result.orderedTrace.records {
switch record {
case let .lifecycle(event):
print(event.position.sequence, "checkpoint", event.stage)
case let .specification(event):
print(
event.startPosition?.sequence as Any,
"span",
event.name,
event.outcome,
event.completionPosition?.sequence as Any
)
}
}Timeline sequence numbers order events only within one decision invocation. Render lifecycle checkpoints distinctly from evaluated rules: a checkpoint records that the pipeline reached a stage, while a SpecificationCore span records a rule's outcome. Both trace streams omit request and prediction contents. See Decision tracing for merged order, spans, thrown calls, and cancellation.
Disable event collection when a call site does not need traces:
let engine = DecisionEngine(
backend: backend,
configuration: .init(traceMode: .disabled)
)If a decision throws and there is no DecisionResult to inspect, provide decisionTraceHandler to receive the full ordered snapshot, or keep using specificationTraceHandler for Core-only events. The merged callback runs once per traced invocation, including validation failures, provider errors, and cancellation; an early failure may produce an empty snapshot. Stable Core span names include request validation, policy routing, backend prediction, output validation, and acceptance policy. traceMode: .disabled suppresses both trace callbacks and trace collections.
An optional DecisionMetricsHandler receives one measurement per completed or failed decision. Metrics contain decision kind, monotonic elapsed time, and status; they omit prompts, model outputs, request identifiers, and error text. The callback may run concurrently, so keep it thread-safe and fast. SwiftDecision does not include an exporter or telemetry dependency; applications can forward measurements to their own systems.
Local model backends include native Laya MLX and the experimental small GLiNER Core ML adapter. Hosted providers such as TypeSafe Jev are maintained as separate provider packages. The mock backend is for examples and contract tests, not a model benchmark.
| Backend | Example workload | Correctness evidence | P50 / P95 latency | Throughput |
|---|---|---|---|---|
| Native Laya MLX | Outage impact (Noul), duplicate-charge routing (Choice), answer quality (Score) | Optional local Python parity test in FP16 and FP32 | Not measured | Not measured |
| Experimental GLiNER Core ML | 41 English diagnostic inputs, including reversed labels and missing evidence | Exact token parity; native INT8 runtime parity; 32/37 labeled cases correct on a small diagnostic set | About 38 ms P50 on M4 Pro CPU; P95 not measured | Not measured |
ClosureDecisionBackend |
Deterministic Noul, Choice, Score fixtures | Request/response contracts covered in CI | Not applicable | Not applicable |
- Swift tools 6.3 or newer.
- Base package deployment targets: macOS 10.15, iOS 15, tvOS 13, and watchOS 6.
- Native MLX backend: Apple Silicon, macOS 14+ or iOS 17+, and the
MLXtrait. - Experimental GLiNER backend: macOS 14+ or iOS 17+, the
GLiNERtrait and separately provisioned assets.
Build and test without optional traits:
swift build --disable-default-traits
swift test --disable-default-traitsCI builds and tests on Swift 6.3.3 and Swift 6.4. The MLX CI lane compiles and tests the native backend on Apple Silicon without downloading model weights.
SwiftDecision 0.3.x supports iOS 13 and 14. SwiftDecision 0.4.0 raised the minimum deployment target to iOS 15; 0.5.0 retains that minimum and adds the unified decision trace timeline. Apps that need iOS 13 or 14 should constrain SwiftPM to the 0.3 series with .upToNextMinor(from: "0.3.0"). Foundation Models / Apple Intelligence adapters, built-in batch scheduling, and agent tool orchestration are not included in 0.5.0.
SwiftDecision is available under the Apache License 2.0. Model weights have their own terms and are not included in this repository.
Create try DecisionBudget(timeout: seconds) once per logical operation and pass
that same value as budget: to choice, noul, and score. Its monotonic deadline
starts at initialization and is never reset by a call or a copy. Each inference
uses the smaller of the remaining budget and Configuration.timeout; omitting a
budget preserves the existing per-inference timeout behavior. An expired budget
throws DecisionError.timedOut without calling the backend. Cancellation still
propagates. A budget bounds inference waiting, not application work after it.
DecisionClock supplies monotonic now values and cancellable sleep(until:)
waiting. Both DecisionBudget(timeout:clock:) and DecisionEngine(..., clock:)
accept a custom clock; existing calls use SystemDecisionClock, backed by system
uptime. A supplied budget owns the clock used for its deadline and timeout waiting,
including any smaller per-inference limit from the engine configuration. Without a
budget, the engine uses its own clock. Calendar time changes do not affect the
production clock. Tests can inject a manually advanced clock to check deadlines
without depending on scheduler timing; the package keeps its existing deployment
targets.
DecisionFailureCategory provides provider-independent categories. Provider
adapters can refine errors; consumers retain retry and fallback policy.
The optional local GLiNER backend has a separately downloaded licensed Core ML model asset. See asset delivery and integration; no weights are bundled in SwiftPM.