Sitemap
Devamuthan Sankar

Devamuthan Sankar

Building Smarter iOS Apps: Implementing Apple Intelligence with Foundation Model Framework

6 min readAug 1, 2025

--

Press enter or click to view image in full size

Generative AI has rapidly transformed the landscape of modern app development, empowering applications with unprecedented intelligence, context-awareness, and responsiveness. Apple’s Foundation Model Framework is at the forefront of this shift, enabling developers to seamlessly integrate powerful generative capabilities directly into their iOS applications. Whether your goal is to enhance user personalization, automate content creation, or develop smarter interactive experiences, this practical guide will clearly walk you through the implementation process. Dive in to learn the essentials of managing sessions, handling errors gracefully, crafting effective prompts, and customizing generative models, helping you bring the full power of Apple Intelligence to your apps.

Implementing Apple Intelligence in Apps

Developers can begin interacting with Apple Intelligence using the Foundation Model Framework, which provides APIs to run on-device models and manage conversation sessions. Key components include:

SystemLanguageModel:

  • The default model available on-device, capable of text generation.

LanguageModelSession:

  • Supports multi-turn conversations with persistent state.
  • Handles only one request at a time (subsequent calls before completion trigger errors).
  • Supports system prompts for defining model behaviour.
  • Context window limited to 4096 tokens — not ideal for chatbot-scale memory.

Transcript:

  • Logs all session activity, allowing for replay or analysis of past interactions.

Prompting:

  • Prompt interaction with Apple’s models is handled primarily through two functions: respond and streamRespond.
  • The respond function is used for standard interactions, allowing developers to submit prompts and receive generated outputs in a single completion.
  • The streamRespond function enables developers to handle generated outputs incrementally, useful for real-time interfaces.
import Playgrounds
import FoundationModels

#Playground {
// Default On-Device Language model
let model = SystemLanguageModel.default
// Check for model availability
switch model.availability {
case .available:
print("Foundation Models are available")
case .unavailable(.modelNotReady):
print("Foundation Model not ready")
case .unavailable(.deviceNotEligible):
print("Device not eligible")
case .unavailable(.appleIntelligenceNotEnabled):
print("Apple Intelligence not enabled")
case .unavailable(let reason):
print("Model Unavailable: \(reason)")
}

if model.isAvailable {
// Create Language Model session
let modelSession = LanguageModelSession(model: model)

do {
// Standard usage of session
try await modelSession.respond(to: "Hi Model")
// Streaming the model response
let stream = try modelSession.streamResponse(to: "Let's get a little deeper into the world of iOS")
for try await streamData in stream {
print(streamData)
}
} catch {...}

// Transcript records all the input prompts and output responses
print("Session Transcripts: \(modelSession.transcript)")
}
}

Error Handling:

While interacting with Foundation Models, developers should be aware of specific runtime errors and handle them gracefully within their applications:

  • GuardRailViolation: Apple’s built-in guardrails automatically scan content for safety concerns. If potentially unsafe content is detected, the model throws a guardRailViolation error. Developers have limited direct control over this process, but can manage such errors to maintain app stability.
  • RateLimited: Each LanguageModelSession instance can only process one request at a time. If another prompt is sent before the previous request completes, a rateLimited error is triggered. Proper management of request sequencing is essential to avoid this.
  • ExceededContextWindowSize: Every session instance has a fixed context window of 4096 tokens. Attempting to exceed this limit results in an exceededContextWindowSize error. Developers should monitor prompt lengths and session states closely to remain within context limits.
import Playgrounds
import FoundationModels

#Playground {
let model = SystemLanguageModel.default

switch model.availability {
...
}

if model.isAvailable {
let modelSession = LanguageModelSession(model: model)

do {
...
} catch LanguageModelSession.GenerationError.guardrailViolation {
print("The content contains some inappropriate language. Please try again with a different request.")
} catch LanguageModelSession.GenerationError.rateLimited {
print("A session can handle only one request at a time.")
} catch LanguageModelSession.GenerationError.exceededContextWindowSize {
print("Prompt exceeds context window, create a new session.")
}
}
}

Tools:

  • Foundation Models can invoke Tools — specialised actions or external data calls executed at runtime — to extend their capabilities beyond standard text generation.
  • These tools allow models to interact dynamically with app-specific logic or gather external information seamlessly within a conversation flow.

Guided Generation:

Get Devamuthan Sankar’s stories in your inbox

Join Medium for free to get updates from this writer.

Developers can precisely shape the model’s outputs using guided generation techniques provided by Apple using two Macros:

  • @Generable: Applied to Swift structs and enums to automatically map generated outputs into custom-defined Swift data structures.
  • @Guide: Used to specify detailed instructions at the attribute level, enabling fine-grained control over how specific parts of the generated content should be structured or formatted.
import FoundationModels

@Generable // Structs or Enums has to be defines Generable
struct RequirementAnalysisPlan {
// A Generatble structure may or may not contain Guided variables
// Guided variables helps the model provide user intended generated response
@Guide(description: "A concise, engaging, and relevant title for the proposed business idea.")
var title: String

@Guide(description: "An in-depth and comprehensive description outlining the purpose, key features, and potential impact of the proposed business idea.")
var expandedDescription: String
// Nested Generable Structure
@Guide(description: "A structured list of implementation phases detailing essential tasks, responsibilities, and timelines required to successfully deliver the project.")
var phases: [Phase]

@Guide(description: "A carefully selected list of five technology recommendations that prioritize cost-efficiency, scalability, ease of maintenance, and alignment with the project's goals.")
@Guide(.count(5)) // Limiting the number of response
var techStackRecommendation: [String]
@Guide(description: "Recommended cloud technologies suitable for this project, ensuring services are relevant, compatible, and necessary. Specify 'None' if cloud services are not applicable.")
var cloudTechRecommendation: [String]
@Guide(description: "Overall estimated duration to complete the project, provided in weeks or months, adjusted realistically according to the team size.")
var estimatedTimeToCompletion: String
@Guide(description: "Total estimated number of personnel needed across the entire lifecycle of the project, adjusted realistically based on team size and project complexity.")
var totalTeamSizeEstimate: Int
}
@Generable
struct Phase {
@Guide(description: "The clear, descriptive name for this phase of the project, such as 'Planning', 'Design', or 'Deployment'.")
var name: String

@Guide(description: "Detailed summary of key responsibilities, objectives, and activities to be accomplished during this project phase.")
var description: String
@Guide(description: "Projected duration required to complete this specific phase, specified in weeks or months.")
var duration: String
// Nested Generable Structure
@Guide(description: "Detailed tasks required to accomplish this phase.")
var tasks: [RequirementTask]
}
@Generable
struct RequirementTask {
@Guide(description: "A clear, succinct title describing the main objective of this task.")
var title: String

@Guide(description: "An explicit explanation detailing what actions or outcomes this task aims to achieve.")
var description: String
@Guide(description: "Time estimated to complete this task, clearly specified in hours, days, or weeks.")
var timeEstimate: String
// Generable Enum used as guided property
@Guide(description: "Professional roles essential to complete this task (e.g., 'iOS Developer', 'UI Designer', 'Product Manager').")
var roles: [Roles]
@Guide(description: "The specific number of personnel required to efficiently execute and complete this task.")
var peopleRequired: Int
}
// Generable Enum
@Generable
enum Roles: String, CaseIterable {
case iosDeveloper
case productManager
case buisnessAnalyst
case uiDesigner
case qaTester
}

Usage:

// modelSession: Instance of LanguageModelSession
func generateRequirement(text: String) async {
guard text != "" else { return }
do {
let prompt: Prompt = .init("You are a business requirement analyst. Analyze the following idea: \(text)")
let generation = try await modelSession.respond(
generating: RequirementAnalysisPlan.self // Provide the Generable type
) { prompt }
// Utilise the generated content
} catch {
// Handle Error
}
}

Building Custom Adapters

For more advanced use cases, developers can build their own custom adapters using Apple’s Adapter Training Kit, which supports training in Python.

The typical workflow includes:

  1. Downloading and setting up the toolkit
  2. Preparing and preprocessing custom data
  3. Training the adapter
  4. Testing its performance
  5. Exporting the adapter
  6. Deploying it using the necessary entitlements
Press enter or click to view image in full size

Trade-offs and Limitations

Despite their flexibility, custom adapters come with constraints:

  • A new adapter must be built for each Foundation Model version
  • Older adapters become incompatible with newer model updates
  • Adapters significantly increase app size, making them impractical for small to mid-size apps

Using the custom adapter:

import Playgrounds
import FoundationModels

#Playground {
// Use the custom built adapter for Language model
let customModel = SystemLanguageModel(adapter: .init(name: "custom-adapter"))

if model.isAvailable {
// Language session using the custom adapter language model
let customModelSession = LanguageModelSession(model: customModel)

do {
try await customModelSession.respond(to: "Hi custom model")
...
} catch {
//Handle Error
}
}
}

Conclusion:

Implementing Apple Intelligence with the Foundation Model Framework equips developers with the tools to create intelligent, context-aware apps that redefine user experience standards. By thoughtfully managing sessions, error handling, prompting, guided generation, and custom adapters, developers can effectively harness the power of on-device generative AI. This practical guide provides a solid foundation to experiment, innovate, and unlock new possibilities — positioning your iOS apps at the forefront of Apple’s evolving intelligent ecosystem.

References:

--

--