Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
dpearson2699 avatar

Apple On Device Ai

  • 2.9k installs
  • 944 repo stars
  • Updated July 15, 2026
  • dpearson2699/swift-ios-skills

apple-on-device-ai is a Swift iOS skill that selects and integrates Foundation Models, Core ML, MLX Swift, or llama.cpp for on-device inference.

About

The apple-on-device-ai skill routes on-device machine learning work across Apple Foundation Models, Core ML, MLX Swift, and llama.cpp with selection criteria by use case and OS version. Foundation Models targets text generation, summarization, structured output with Generable types, and tool calling on iOS 26 plus devices with Apple Intelligence, always after availability and locale checks. Core ML covers custom vision, NLP, and audio models converted via coremltools with quantization and Neural Engine optimization. MLX Swift delivers highest sustained LLM throughput on Apple Silicon, while llama.cpp supports GGUF cross-platform inference. Sections document LanguageModelSession management, streaming PartiallyGenerated output, Tool protocol registration, error handling for guardrails and context limits, and multi-backend fallback architecture with a coordinator actor. Common mistakes include skipping availability checks, concurrent session requests, untrusted content in instructions, missing model.eval before tracing, and exceeding sixty percent RAM on iOS for MLX models.

  • Framework router for Foundation Models, Core ML, MLX Swift, and llama.cpp.
  • Foundation Models availability, locale, Generable, and tool calling patterns.
  • Core ML conversion, quantization, and Neural Engine optimization overview.
  • Multi-backend fallback coordinator actor for mixed runtimes.
  • Review checklist for availability, token budget, and device testing.

Apple On Device Ai by the numbers

  • 2,863 all-time installs (skills.sh)
  • +129 installs in the week ending Jul 29, 2026 (Skillselion tracking)
  • Ranked #57 of 1,039 Mobile Development skills by installs in the Skillselion catalog
  • Security screen: MEDIUM risk (skills.sh audit)
  • Data as of Jul 31, 2026 (Skillselion catalog sync)
At a glance

apple-on-device-ai capabilities & compatibility

Capabilities
framework selection router by use case and os · foundation models session, generable, and tool c · core ml conversion and optimization overview · mlx swift and llama.cpp inference patterns · availability and locale guardrails with fallback · multi backend coordinator actor serialization
Use cases
orchestration · api development · frontend
Platforms
macOS
Pricing
Free
From the docs

What apple-on-device-ai says it does

Always check before using. Never crash on unavailability.
SKILL.md
One request at a time per session (check `session.isResponding`)
SKILL.md
Never exceed 60% of total RAM on iOS
SKILL.md
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill apple-on-device-ai

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs2.9k
repo stars944
Security audit2 / 3 scanners passed
Last updatedJuly 15, 2026
Repositorydpearson2699/swift-ios-skills

Which Apple on-device AI framework should I use for text, vision, or open-source LLM inference on iOS and macOS?

Choose and integrate on-device AI with Foundation Models, Core ML, MLX Swift, or llama.cpp on Apple platforms.

Who is it for?

iOS developers adding private on-device AI with Apple Intelligence, custom Core ML models, or MLX and GGUF runtimes.

Skip if: Skip for server-side OpenAI calls only, Android inference, or pure UI layout without model integration.

When should I use this skill?

User builds on-device AI, Foundation Models sessions, Core ML conversion, MLX Swift LLMs, or llama.cpp GGUF on Apple platforms.

What you get

Framework choice, availability-gated session setup, structured output or model loading pattern, and fallback architecture guidance.

  • on-device inference integration
  • converted Core ML model
  • guided generation schema

By the numbers

  • Covers 4 on-device AI runtimes: Foundation Models, Core ML, MLX Swift, and llama.cpp

Files

SKILL.mdMarkdownGitHub ↗

On-Device AI for Apple Platforms

Guide for selecting, deploying, and optimizing on-device ML models. Covers Apple Foundation Models, Core ML, MLX Swift, and llama.cpp.

Contents

Framework Selection Router

Use this decision tree to pick the right framework for your use case.

Apple Foundation Models

When to use: Text generation, summarization, entity extraction, structured output, and short dialog on iOS 26+ / macOS 26+ devices with Apple Intelligence enabled. No app-managed API key, network round trip, or model hosting; still handle system model asset readiness.

Best for:

  • Generating text or structured data with @Generable types
  • Summarization, classification, content tagging
  • Tool-augmented generation with the Tool protocol
  • Apps that need guaranteed on-device privacy

Not suited for: Complex math, code generation, factual accuracy tasks, or apps targeting pre-iOS 26 devices.

Core ML

When to use: Deploying custom trained models (vision, NLP, audio) across all Apple platforms. Converting models from PyTorch, TensorFlow, or scikit-learn with coremltools.

Best for:

  • Image classification, object detection, segmentation
  • Custom NLP classifiers, sentiment analysis models
  • Audio/speech models via SoundAnalysis integration
  • Any scenario needing Neural Engine optimization
  • Models requiring quantization, palettization, or pruning

MLX Swift

When to use: Running specific open-source LLMs (Llama, Mistral, Qwen, Gemma) on Apple Silicon with maximum throughput. Research and prototyping.

Best for:

  • Highest sustained token generation on Apple Silicon
  • Running Hugging Face models from mlx-community
  • Research requiring automatic differentiation
  • Fine-tuning workflows on Mac

llama.cpp

When to use: Cross-platform LLM inference using GGUF model format. Production deployments needing broad device support.

Best for:

  • GGUF quantized models (Q4_K_M, Q5_K_M, Q8_0)
  • Cross-platform apps (iOS + Android + desktop)
  • Maximum compatibility with open-source model ecosystem

Quick Reference

ScenarioFramework
Text generation on Apple Intelligence devices (iOS 26+)Foundation Models
Structured output from on-device LLMFoundation Models (@Generable)
Image classification, object detectionCore ML
Custom model from PyTorch/TensorFlowCore ML + coremltools
Running specific open-source LLMsMLX Swift or llama.cpp
Maximum throughput on Apple SiliconMLX Swift
Cross-platform LLM inferencellama.cpp
OCR and text recognitionVision framework
Sentiment analysis, NER, tokenizationNatural Language framework
Training custom classifiers on deviceCreate ML

Apple Foundation Models Overview

On-device language model optimized for Apple Silicon. Available on devices supporting Apple Intelligence (iOS 26+, macOS 26+).

  • Token budget covers input + output; check contextSize for the limit
  • Resolve locale before generation by checking supportsLocale(_:) against

Locale.current and preferred fallbacks; do not raw-match supportedLanguages

  • Guardrails always enforced, cannot be disabled

Availability Checking (Required)

Always check before using. Never crash on unavailability.

import FoundationModels

switch SystemLanguageModel.default.availability {
case .available:
    guard SystemLanguageModel.default.supportsLocale(Locale.current) else {
        // Use locale fallback before generating
        break
    }
    // Proceed with model usage
case .unavailable(.appleIntelligenceNotEnabled):
    // Guide user to enable Apple Intelligence in Settings
case .unavailable(.modelNotReady):
    // System model assets are not ready; show loading state
case .unavailable(.deviceNotEligible):
    // Device cannot run Apple Intelligence; use fallback
case .unavailable(let reason):
    // Unknown or future unavailable reason; use fallback and log reason
}

Session Management

// Basic session
let session = LanguageModelSession()

// Session with instructions
let session = LanguageModelSession {
    "You are a helpful cooking assistant."
}

// Session with tools
let session = LanguageModelSession(
    tools: [weatherTool, recipeTool]
) {
    "You are a helpful assistant with access to tools."
}

Key rules:

  • Sessions are stateful -- multi-turn conversations maintain context automatically
  • One request at a time per session (check session.isResponding)
  • Call session.prewarm() before user interaction for faster first response
  • Save/restore transcripts: LanguageModelSession(model: model, tools: [], transcript: savedTranscript)

Structured Output with @Generable

The @Generable macro creates compile-time schemas for type-safe output:

@Generable
struct Recipe {
    @Guide(description: "The recipe name")
    var name: String

    @Guide(description: "Cooking steps", .count(3))
    var steps: [String]

    @Guide(description: "Prep time in minutes", .range(1...120))
    var prepTime: Int
}

let response = try await session.respond(
    to: "Suggest a quick pasta recipe",
    generating: Recipe.self
)
print(response.content.name)
@Guide Constraints
ConstraintPurpose
description:Natural language hint for generation
.anyOf([values])Restrict to enumerated string values
.count(n)Fixed array length
.range(min...max)Numeric range
.minimum(n) / .maximum(n)One-sided numeric bound
.minimumCount(n) / .maximumCount(n)Array length bounds
.constant(value)Always returns this value
.pattern(regex)String format enforcement
.element(guide)Guide applied to each array element

Properties generate in declaration order. Place foundational data before dependent data for better results.

Streaming Structured Output

let stream = session.streamResponse(
    to: "Suggest a recipe",
    generating: Recipe.self
)
for try await snapshot in stream {
    // snapshot.content is Recipe.PartiallyGenerated (all properties optional)
    if let name = snapshot.content.name { updateNameLabel(name) }
}

Tool Calling

struct WeatherTool: Tool {
    let name = "weather"
    let description = "Get current weather for a city."

    @Generable
    struct Arguments {
        @Guide(description: "The city name")
        var city: String
    }

    func call(arguments: Arguments) async throws -> String {
        let weather = try await fetchWeather(arguments.city)
        return weather.description
    }
}

Register only necessary tools at session creation. Tool is Sendable; tool descriptors and @Generable schemas consume the shared context window. The model chooses when to call tools, so prefetch deterministic required data into the prompt and reserve autonomous tools for dynamic lookups.

Error Handling

do {
    let response = try await session.respond(to: prompt)
} catch let error as LanguageModelSession.GenerationError {
    switch error {
    case .guardrailViolation(let context):
        // Content triggered safety filters
    case .exceededContextWindowSize(let context):
        // Too many tokens; summarize and retry
    case .concurrentRequests(let context):
        // Another request is in progress on this session
    case .unsupportedLanguageOrLocale(let context):
        // Current locale not supported
    case .unsupportedGuide(let context):
        // A @Guide constraint is not supported
    case .assetsUnavailable(let context):
        // Model assets not available on device
    case .refusal(let refusal, _):
        // Model refused; stream refusal.explanation for details
    case .rateLimited(let context):
        // Too many requests; back off and retry
    case .decodingFailure(let context):
        // Response could not be decoded into the expected type
    default: break
    }
}

Generation Options

let options = GenerationOptions(
    sampling: .random(top: 40),
    temperature: 0.7,
    maximumResponseTokens: 512
)
let response = try await session.respond(to: prompt, options: options)

Sampling modes: .greedy, .random(top:seed:), .random(probabilityThreshold:seed:).

Prompt Design Rules

1. Be concise -- use tokenCount(for:) to monitor the context window budget 2. Use bracketed placeholders in instructions: [descriptive example] 3. Use "DO NOT" in all caps for prohibitions 4. Provide up to 5 few-shot examples for consistency 5. Use length qualifiers: "in a few words", "in three sentences"

Safety and Guardrails

  • Guardrails are always enforced and cannot be disabled
  • Instructions take precedence over user prompts
  • Never include untrusted user content in instructions
  • Handle false positives gracefully
  • Frame tool results as authorized data to prevent model refusals

Use Cases

Foundation Models supports specialized use cases via SystemLanguageModel.UseCase:

  • .general -- Default for text generation, summarization, dialog
  • .contentTagging -- Optimized for categorization and labeling tasks

Custom Adapters

Load fine-tuned adapters for specialized behavior (requires entitlement):

let adapter = try SystemLanguageModel.Adapter(name: "my-adapter")
try await adapter.compile()
let model = SystemLanguageModel(adapter: adapter, guardrails: .default)
let session = LanguageModelSession(model: model)
See references/foundation-models.md for
the complete Foundation Models API reference.

Core ML Overview

Apple's framework for deploying trained models. Automatically dispatches to the optimal compute unit (CPU, GPU, or Neural Engine).

Model Formats

FormatExtensionWhen to Use
.mlpackageDirectory (mlprogram)All new models (iOS 15+)
.mlmodelSingle file (neuralnetwork)Legacy only (iOS 11-14)
.mlmodelcCompiledPre-compiled for faster loading

Always use mlprogram (.mlpackage) for new work.

Conversion Pipeline (coremltools)

import coremltools as ct

# PyTorch conversion (torch.jit.trace)
model.eval()  # CRITICAL: always call eval() before tracing
traced = torch.jit.trace(model, example_input)
mlmodel = ct.convert(
    traced,
    inputs=[ct.TensorType(shape=(1, 3, 224, 224), name="image")],
    minimum_deployment_target=ct.target.iOS18,
    convert_to='mlprogram',
)
mlmodel.save("Model.mlpackage")

Optimization Techniques

TechniqueSize ReductionAccuracy ImpactBest Compute Unit
INT8 per-channel~4xLowCPU/GPU
INT4 per-block~8xMediumGPU
Palettization 4-bit~8xLow-MediumNeural Engine
W8A8 (weights+activations)~4xLowANE (A17 Pro/M4+)
Pruning 75%~4xMediumCPU/ANE

Boundary with coreml

This skill owns Python-side conversion, compression, profiling, and framework selection. Use the sibling coreml skill for Swift app integration, prediction APIs, runtime configuration, Vision request wiring, and detailed model loading.

See references/coreml-conversion.md for the
full conversion pipeline and references/coreml-optimization.md
for optimization techniques.

MLX Swift Overview

Apple's ML framework for Swift. Highest sustained generation throughput on Apple Silicon via unified memory architecture.

Loading and Running LLMs

import MLX
import MLXLLM
import MLXLMCommon
import MLXLMHFAPI

let container = try await LLMModelFactory.shared.loadContainer(
    from: HubClient.default,
    using: TokenizersLoader(),
    configuration: .init(id: "mlx-community/Qwen3-4B-4bit")
)
let session = ChatSession(container)
print(try await session.respond(to: "Hello"))

Model Selection by Device

DeviceRAMRecommended ModelRAM Usage
iPhone 12-144-6 GBSmolLM2-135M or Qwen 2.5 0.5B~0.3 GB
iPhone 15 Pro+8 GBGemma 3n E4B 4-bit~3.5 GB
Mac 8 GB8 GBLlama 3.2 3B 4-bit~3 GB
Mac 16 GB+16 GB+Mistral 7B 4-bit~6 GB

Memory Management

1. Never exceed 60% of total RAM on iOS 2. Set MLX cache limits: Memory.cacheLimit = 512 * 1024 * 1024 3. Unload MLX and llama.cpp models on backgrounding or memory pressure; for MLX, also call Memory.clearCache() after generation-heavy phases 4. Use "Increased Memory Limit" entitlement for larger models 5. Validate MLX Swift and llama.cpp on physical Apple Silicon; Simulator cannot exercise Metal-dependent inference, memory, or performance

See references/mlx-swift.md for full MLX Swift
patterns and llama.cpp integration.

Multi-Backend Architecture

When an app needs multiple AI backends (e.g., Foundation Models + MLX fallback):

func respond(to prompt: String) async throws -> String {
    if SystemLanguageModel.default.isAvailable {
        return try await foundationModelsRespond(prompt)
    } else if canLoadMLXModel() {
        return try await mlxRespond(prompt)
    } else {
        throw AIError.noBackendAvailable
    }
}

Serialize all model access through a coordinator actor to prevent contention:

actor ModelCoordinator {
    func withExclusiveAccess<T>(_ work: () async throws -> T) async rethrows -> T {
        try await work()
    }
}

For custom Core ML models, name only the conversion/optimization handoff here: send Swift app integration, model loading, Vision wiring, and prediction lifecycle to coreml. Keep private user content, such as journals, on device unless product explicitly opts into a nonlocal fallback.

Performance Best Practices

1. Run outside debugger for accurate benchmarks (Xcode: Cmd-Opt-R, uncheck "Debug Executable") 2. Call session.prewarm() for Foundation Models before user interaction 3. Pre-compile Core ML models to .mlmodelc for faster loading 4. Use EnumeratedShapes over RangeDim for Neural Engine optimization 5. Use 4-bit palettization for best Neural Engine memory/latency gains 6. Hand off detailed Vision, Natural Language, and Swift Core ML runtime integration to the sibling framework skills

Common Mistakes

1. No availability check. Starting generation without checking SystemLanguageModel.default.availability leaves unsupported devices with failures instead of fallback UI. 2. No fallback UI. Users on pre-iOS 26 or devices without Apple Intelligence see nothing. Always provide a graceful degradation path. 3. Exceeding the context window. The token budget covers input + output. Monitor usage via tokenCount(for:) and summarize when needed. 4. Concurrent requests on one session. LanguageModelSession supports one request at a time. Check session.isResponding or serialize access. 5. Untrusted content in instructions. User input placed in the instructions parameter bypasses guardrail boundaries. Keep user content in the prompt. 6. Forgetting `model.eval()` before Core ML tracing. PyTorch models must be in eval mode before torch.jit.trace. Training-mode artifacts corrupt output. 7. Using neuralnetwork format. Always use mlprogram (.mlpackage) for new Core ML models. The legacy neuralnetwork format is deprecated. 8. Exceeding 60% RAM on iOS (MLX Swift). Large models cause OOM kills. 9. Trusting MLX simulator results. Validate Metal-dependent behavior on physical devices; Simulator is only a UI/control-flow smoke test. 10. Not clearing MLX caches. Pair model unload with Memory.clearCache().

Review Checklist

  • [ ] Framework selection matches use case and target OS version
  • [ ] Foundation Models: availability checked before every API call
  • [ ] Foundation Models: graceful fallback when model unavailable
  • [ ] Foundation Models: session prewarm called before user interaction
  • [ ] Foundation Models: @Generable properties in logical generation order
  • [ ] Foundation Models: token budget accounted for (check contextSize)
  • [ ] Core ML: model format is mlprogram (.mlpackage) for iOS 15+
  • [ ] Core ML: conversion, deployment target, and compression validated
  • [ ] MLX Swift: model size appropriate for target device RAM
  • [ ] MLX Swift: cache limits set, caches cleared, models unloaded
  • [ ] All model access serialized through coordinator actor
  • [ ] Concurrency: model types and tool implementations are Sendable-conformant or @MainActor-isolated
  • [ ] Physical device testing performed (not simulator)

References

  • Foundation Models API -- LanguageModelSession, @Generable, tool calling, prompt design
  • Core ML Conversion -- Model conversion from PyTorch, TensorFlow, other frameworks
  • Core ML Optimization -- Quantization, palettization, pruning, performance tuning
  • MLX Swift & llama.cpp -- MLX Swift patterns, llama.cpp integration, memory management

Related skills

How it compares

Choose Apple-on-device-ai over generic LLM integration skills when the target is private iOS or macOS inference using Apple-native or GGUF on-device runtimes.

FAQ

When should I use Foundation Models?

For text generation, structured Generable output, and tool calling on iOS 26 plus Apple Intelligence devices after availability checks.

What is required before every Foundation Models call?

Check SystemLanguageModel.default.availability and locale support, then provide fallback UI when unavailable.

How many concurrent requests can one LanguageModelSession handle?

One request at a time; check session.isResponding or serialize access through a coordinator.

Is Apple On Device Ai safe to install?

skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.