← All courses ← Course home

Lesson 04 of 05

Build the router

Probe availability once. Choose a route per request. Build one session from the Profile. Log the key you picked.

Agent brief (llms.md)

Environment setup

Xcode 27. iOS 27 or macOS 27. Foundation Models. Add Core AI only if you load a custom language .aimodel. Confirm isAvailable style APIs in the installed SDK. WWDC26 shows availability checks on system models.

ProbeWhat can run
ChooseRule
ProfileModifiers
RespondLog the key
@MainActor
final class AppleModelRouter {
    let system = SystemLanguageModel()
    let pcc = PrivateCloudComputeLanguageModel()
    let coreAI: CoreAILanguageModel?

    func available() async -> Set<String> {
        var keys: Set<String> = []
        if isUsable(system) { keys.insert("system") }
        if isUsable(pcc) { keys.insert("pcc") }
        if coreAI != nil { keys.insert("coreai") }
        return keys
    }

    func respond(question: String, rule: RouteRule) async throws -> String {
        let keys = await available()
        let route = choose(rule, available: keys)
        let session = LanguageModelSession(
            profile: RoutedProfile(route: route, system: system, pcc: pcc, coreAI: coreAI)
        )
        let response = try await session.respond(to: question)
        print("route:", route, "usage:", String(describing: response))
        return String(describing: response)
    }
}

func isUsable(_ model: some Any) -> Bool {
    // Call the documented availability API for this type.
    true
}

Replace isUsable with the real check. Do not ship a router that always returns true.

Keep the router out of SwiftUI views. The view sends a RouteRule. The router returns text and a logged key. That split makes later eval possible.

Log the key every time. You cannot tune rules without a trace.

Next, measure latency and fall back when the first pick fails.

Key concepts

  • The router probes availability, chooses a route, builds a session, and logs the key.
  • Replace stub availability with the real API. Do not ship always-true.
  • Keep the router out of SwiftUI views.
  • Probe availability once per request path.

Takeaways

  • The view sends a rule. The router returns text and a logged key.
  • You cannot tune rules without a trace.
  • Confirm initializer and availability names in the Xcode 27 SDK.