Swift 6.4 SDK for TypeSafe AI, following the Python SDK's 0.7.6 API. Supports macOS 26+, iOS 26+, tvOS 26+, watchOS 26+, visionOS 26+, and Linux.
Uses Apple's experimental HTTPClient package, pinned to 0.2.1. The proposal may change; its Swift 6.4 and OS requirements apply to this SDK.
Add swift-typesafe to your Swift package dependencies:
.package(url: "https://github.com/ainame/swift-typesafe.git", from: "0.7.5")Add the TypeSafe product to your target:
.product(name: "TypeSafe", package: "swift-typesafe")Set TYPESAFE_API_KEY or pass apiKey to TypeSafeClient, then choose the question style that fits your application.
import TypeSafe
enum Category: String, CaseIterable, Codable, Sendable {
case billing, technical, other
}
@QuestionSet
struct TicketQuestions {
@Choice("What is this ticket about?")
var category: Category
@Noul("Does this need urgent attention?")
var urgent: Double
@Score("How severe is the issue?", criteria: ["minor", "moderate", "severe"])
var severity: Double
}
let client = try TypeSafeClient()
let result = try await client.systemOne(
state: "I was charged twice.",
questions: TicketQuestions.self
)
print(result.answers.category.choice) // Category
print(result.answers.urgent.noul) // Probability, 0...1
print(result.answers.severity.score) // Expected score; may be fractionalPass a @QuestionSet type to get reusable questions with concrete typed answers.
For local judgments, use a result-builder closure instead of declaring a schema:
let (category, urgent, severity) = try await client.systemOne(state: "I was charged twice.") {
Choice<Category>("What is this ticket about?")
Noul("Does this need urgent attention?")
Score("How severe is the issue?", criteria: ["minor", "moderate", "severe"])
}.answers
print(category.choice) // Category
print(urgent.noul) // Probability, 0...1
print(severity.score) // Expected score; may be fractionalThe builder returns typed answers in declaration order; use it when questions are local to one call.
For questions whose names or choices are determined at runtime:
let result = try await client.systemOne(
state: ["document": "I was charged twice."],
questions: [
"category": .choice(
instructions: "What is this ticket about?",
criteria: ["billing": nil, "technical": nil, "other": nil]
),
"urgent": .noul(instructions: "Does this need urgent attention?")
]
)
print(result.choices["category"]?.choice) // String?
print(result.nouls["urgent"]?.noul)The dynamic API accepts questions built at runtime and returns answers by name.
Option order can affect the model's probabilities. Choice and Noul criteria: dictionary literals preserve their written order by default, including in macros and builders. When choice criteria are omitted, @Choice and Choice<Label> send options in Label.allCases order.
For runtime options with a known order, pass Criteria(keyValuePairs) or Criteria(pairs: entries) for an array of (String, JSONValue) pairs to criteria:. Repeated keys keep their first position and last description. Existing [String: JSONValue] variables remain accepted: dynamic Choice and Noul sort their keys; enum-backed choices use enum order with extra keys sorted afterward. A dictionary variable has already lost its insertion order, so use Criteria to retain a particular sequence.
This ordering guarantee applies to requests sent by TypeSafeClient. Raw JSON and extraBody objects use ordinary dictionaries, and direct Foundation JSONEncoder encoding of Question does not guarantee object-key order.
let response = try await client.models.list()
print(response.models)
print(response.requestID as Any)
print(response.rawHTTPResponse?.status as Any)Responses expose request metadata and raw HTTP data; use responseModel: to decode into your own Decodable & Sendable type.
struct SpamResponse: Decodable, Sendable {
struct Answers: Decodable, Sendable { let spam: NoulAnswer }
let model: String
let answers: Answers
}
let typed = try await client.systemOne(
state: "Buy now!", questions: ["spam": .noul(instructions: "Spam?")], responseModel: SpamResponse.self
)
print(typed.answers.spam.noul)Available in Swift 0.7.5. Images and Box require the experimental TypeSafe-Danger-Zone-Images: true header. Box needs Jev 1.14; the examples pin jev-1.14.0.
import Foundation
let photo = Image(fileURL: URL(fileURLWithPath: "product.jpg"))
let located = try await client.systemOne(
state: photo, model: "jev-1.14.0",
options: .init(headers: ["TypeSafe-Danger-Zone-Images": "true"])
) {
Box("The product")
}
print(located.answers.box) // BoxCoordinates: top, bottom, left, rightAlready loaded the image? Wrap its bytes in Image and pass it as state with any question API:
let photo = Image(data: imageData)
let located = try await client.systemOne(
state: photo, model: "jev-1.14.0",
options: .init(headers: ["TypeSafe-Danger-Zone-Images": "true"])
) {
Box("The product")
}Data means encoded image file bytes, such as PNG or JPEG. For structured content, use state: ["photo": .image(imageData)]. The same .image(data) form works in instructions and criteria. Keep an Image value when reusing one image under multiple references or attaching it to interpolated text.
Use Image(data:), Image(fileURL:), or Image.fromBase64(_:). Put .image(photo) anywhere in state, instructions, or criteria. File URLs are read when preparing each new request; retries reuse the prepared bytes. To reuse the same bytes across requests, load Data once and use Image(data:). Box coordinates are fractions of image height and width; confidence can be nil. Dynamic calls use .box(instructions:) and result.boxes; reusable schemas use @Box("The product") var product: BoxCoordinates.
For named references, pass assets: ["<photo>": photo] and use <photo> in content. To interpolate an image into text, attach it for the duration of the call:
let checked = try await client.withAttachedAssets([photo]) {
try await client.systemOne(state: .string("Inspect \(photo)")) {
Noul("Is the product damaged?")
}
}Attachments are shared by calls on the same client while the scope is active. Unattached image references remain plain text, following Python. An explicit extraBody["assets"] overrides automatic uploads.
Explicit configuration takes precedence over TYPESAFE_API_KEY, TYPESAFE_BASE_URL, and TYPESAFE_DEFAULT_MODEL. Blank environment values are ignored. Defaults are https://api.typesafe.ai, model jev-latest, and a 10-second timeout per attempt.
let client = try TypeSafeClient(
apiKey: apiKey,
timeout: 10,
retry: RetryPolicy(maxRetries: 2, timeout: 30)
)
let models = try await client.models.list(
options: RequestOptions(
timeout: 5,
retry: RetryPolicy(maxRetries: 0),
headers: ["x-project": "demo"]
)
)Retries follow Python: two retries by default for connection errors, timeouts, HTTP 408/429/5xx; exponential backoff from 0.5 to 5 seconds with subtractive jitter; retry-after-ms and Retry-After support. A per-call retry policy replaces the client policy. A predicate can opt additional errors into retries.
The retry budget prevents scheduling an attempt whose delay reaches or exceeds the budget; it does not cut off an attempt already running. Swift's request timeout covers the entire attempt, including the response body. Task cancellation stops requests and backoff and is never retried.
SDK authentication, identification, and retry headers are protected from caller overrides. Per-call custom headers override client headers without regard to case.
Request bodies of at least 1 KiB use zstd compression by default, including multipart image uploads. Pass compression: .disabled to TypeSafeClient for gateways that do not accept compressed requests. The package builds the official facebook/zstd library from source; no system zstd installation is required. Debug body logging is limited to 4096 bytes. Multipart bodies retain image buffers as separate segments. Compression reads those segments directly; uncompressed uploads send them in bounded chunks. Retries reuse the prepared bytes and multipart boundary. Custom transports can use request.bodySegments to avoid flattening; request.body remains available as a buffered compatibility view.
Choice requires at least one criterion. Noul requires instructions or at least one non-null outcome description; a bare Noul() or .noul() fails before sending. Non-finite numbers in content serialize as "NaN", "Infinity", and "-Infinity" strings.
do {
_ = try await client.models.list()
} catch TypeSafeError.api(let error) {
print(error.kind, error.status, error.requestID as Any)
} catch TypeSafeError.responseValidation(_, let fieldPath) {
print("Invalid response at", fieldPath)
} catch TypeSafeError.timeout(let seconds) {
print("Timed out after", seconds)
}APIError.kind distinguishes bad request, authentication, permission, not found, validation, rate limit, server, and other statuses. API errors retain the parsed JSON or plain-text body and headers. Connection failures use TypeSafeError.connection; cancellation uses CancellationError.
Logging uses swift-log. Inject a Logger or set TYPESAFE_LOG_LEVEL to debug, info, warning, error, or off. Credential headers are redacted. Debug logging includes request and response bodies, which are not redacted.
The default transport is backed by one HTTP implementation from Apple's proposal, selected with package traits so the other is not compiled:
| Trait | Backend |
|---|---|
URLSession (default) |
URLSessionHTTPClient on Apple platforms. Linux uses AsyncHTTPClient because URLSession backing is Darwin-only. |
AsyncHTTPClient |
AsyncHTTPClient (SwiftNIO) on every platform. Takes precedence over URLSession when both are enabled. |
To use AsyncHTTPClient instead:
.package(url: "https://github.com/ainame/swift-typesafe.git", from: "0.7.5", traits: ["AsyncHTTPClient"])With traits: [], neither backend is compiled. Inject a transport or client (see Custom HTTP clients); the default transport throws TypeSafeError.configuration.
HTTPClientTransport(client:options:maximumResponseBytes:) accepts a copyable client conforming to Apple's HTTPAPIs.HTTPClient protocol, allowing custom TLS and connection-pool settings. Inject it through TypeSafeClient(transport:). The adapter borrows the client; manage a scoped or owned client's lifetime outside the SDK. The default uses the shared client of the backend selected by the HTTP backend traits and a 16 MiB response limit.
For example, a server that already owns an AsyncHTTPClient.HTTPClient can share that instance with TypeSafe:
import AHCHTTPClient // Adds HTTPAPIs.HTTPClient conformance to AsyncHTTPClient.HTTPClient.
import AsyncHTTPClient
import TypeSafe
func makeTypeSafeClient(httpClient: AsyncHTTPClient.HTTPClient, apiKey: String) throws -> TypeSafeClient {
try TypeSafeClient(
apiKey: apiKey,
transport: HTTPClientTransport(client: httpClient)
)
}Enable the AsyncHTTPClient package trait and pass the server's existing client to this function. Keep that client alive while TypeSafe requests are in flight; the server remains responsible for its shutdown. The trait selects the default backend, while transport: selects the actual client instance used here.
For tests or other integrations, implement the Sendable TypeSafeTransport protocol. Custom transports must respond to task cancellation so timeout and cancellation cleanup can finish.
Releases use Semantic Versioning tags without a v prefix, such as 0.7.2.
- MAJOR.MINOR follows the Python SDK. Swift
0.7.ximplements the Python SDK 0.7 API. A new upstream minor or major release becomes the next Swift MAJOR.MINOR, starting at patch 0 (for example, Python 0.8.0 becomes Swift 0.8.0). - PATCH is owned by this package. Patch releases carry Swift-side fixes and improvements and upstream patch fixes that affect Swift. Python-specific upstream patches may be skipped. A Swift patch number does not have to match the Python patch number. For example, Swift 0.7.2 still implements Python 0.7.1.
- Each CHANGELOG entry names the Python release it implements. UPSTREAM.md keeps the full mapping and exact upstream commits. The parity record lists verified behavior and Swift adaptations.
TypeSafeClient.version, sent in theuser-agentandx-typesafe-sdkheaders, reports the implemented Python SDK version, not this package's tag.
from: "0.7.5" resolves new patch and minor releases below 1.0.0. While the SDK is 0.x, a new MINOR can contain breaking changes, following upstream. To stay on one Python API generation, use .upToNextMinor(from: "0.7.5").
During local development:
.package(path: "/path/to/swift-typesafe")Install Swift 6.4.0 with swiftly. The .swift-version file selects it.
swiftly install 6.4.0
swiftly run swift test --disable-xctest
swiftly run swift build --package-path Examples
git diff --checkTests use Swift Testing and Python 3 for ephemeral loopback HTTP servers. They do not need an API key. The example executable makes real API calls and requires credentials. The repository includes a pinned upstream submodule and an upstream sync skill.
With TYPESAFE_API_KEY set in your environment, run:
swiftly run swift run --package-path Examples Example --imagesThis opt-in mode makes six paid requests to jev-1.14.0 with the image opt-in header. It uses a bundled synthetic 512×512 PNG with a centered red square and checks returned Box bounds against the known location. Each scenario runs with zstd enabled and disabled:
- Loaded
Datawith builder questions. - A file-backed
Imagewith macro questions. - Scoped references with dynamic questions.
These are integration smoke checks, not a general image-accuracy benchmark. Running without --images keeps the existing text examples.