[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6E6AS4D51NWXWDM222FZY11":3,"skill-same:01M6E6AS4D51NWXWDM222FZY11":66},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":34,"linkOnly":35,"markdownContent":36,"markdownBody":37,"frontMatter":38,"refName":43,"commitSha":44,"skillDirectory":45,"forksCount":46,"repositoryHtmlUrl":47,"repositoryHomepageUrl":48,"ownerHtmlUrl":49,"ownerBlogUrl":6,"ownerDescription":50,"updatedAt":51,"install":52,"resources":65},"01M6E6AS4D51NWXWDM222FZY11","axiom-foundation-models-ref",null,"Reference — Complete Foundation Models framework guide covering LanguageModelSession, @Generable, @Guide, Tool protocol, streaming, dynamic schemas, built-in use cases, and all WWDC 2025 code examples","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-foundation-models-ref\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33],"models","foundation","axiom foundation models ref","macos","code","protocol","framework","streaming","examples","ios","tool","guide","use","reference","complete","2026-11-10 10:12:30",false,"---\nname: axiom-foundation-models-ref\ndescription: Reference — Complete Foundation Models framework guide covering LanguageModelSession, @Generable, @Guide, Tool protocol, streaming, dynamic schemas, built-in use cases, and all WWDC 2025 code examples\nlicense: MIT\ncompatibility: iOS 26+, macOS 26+, iPadOS 26+, axiom-visionOS 26+\nmetadata:\n  version: \"1.0.0\"\n  last-updated: \"2025-12-03\"\n---\n\n# Foundation Models Framework — Complete API Reference\n\n## Overview\n\nThe Foundation Models framework provides access to Apple's on-device Large Language Model (3 billion parameters, 2-bit quantized) with a Swift API. This reference covers every API, all WWDC 2025 code examples, and comprehensive implementation patterns.\n\n### Model Specifications\n\n3B parameter model, 2-bit quantized, 4096 token context (input + output combined). Optimized for on-device summarization, extraction, classification, and generation. NOT suited for world knowledge, complex reasoning, math, or translation. Runs entirely on-device — no network, no cost, no data leaves device.\n\n---\n\n## When to Use This Reference\n\nUse this reference when:\n- Implementing Foundation Models features\n- Understanding API capabilities\n- Looking up specific code examples\n- Planning architecture with Foundation Models\n- Migrating from prototype to production\n- Debugging implementation issues\n\n**Related Skills**:\n- `axiom-foundation-models` — Discipline skill with anti-patterns, pressure scenarios, decision trees\n- `axiom-foundation-models-diag` — Diagnostic skill for troubleshooting issues\n\n---\n\n## LanguageModelSession\n\n### Overview\n\n`LanguageModelSession` is the core class for interacting with the model. It maintains conversation history (transcript), handles multi-turn interactions, and manages model state.\n\n### Creating a Session\n\n**Basic Creation**:\n```swift\nimport FoundationModels\n\nlet session = LanguageModelSession()\n```\n\n**With Custom Instructions**:\n```swift\nlet session = LanguageModelSession(instructions: \"\"\"\n    You are a friendly barista in a pixel art coffee shop.\n    Respond to the player's question concisely.\n    \"\"\"\n)\n```\n\n#### From WWDC 301:1:05\n\n**With Tools**:\n```swift\nlet session = LanguageModelSession(\n    tools: [GetWeatherTool()],\n    instructions: \"Help user with weather forecasts.\"\n)\n```\n\n#### From WWDC 286:15:03\n\n**With Specific Model\u002FUse Case**:\n```swift\nlet session = LanguageModelSession(\n    model: SystemLanguageModel(useCase: .contentTagging)\n)\n```\n\n#### From WWDC 286:18:39\n\n### Instructions vs Prompts\n\n**Instructions**:\n- Come from **developer**\n- Define model's role, style, constraints\n- Mostly static\n- First entry in transcript\n- Model trained to obey instructions over prompts (security feature)\n\n**Prompts**:\n- Come from **user** (or dynamic app state)\n- Specific requests for generation\n- Dynamic input\n- Each call to `respond(to:)` adds prompt to transcript\n\n**Security Consideration**:\n- **NEVER** interpolate untrusted user input into instructions\n- User input should go in prompts only\n- Prevents prompt injection attacks\n\n### respond(to:) Method\n\n**Basic Text Generation**:\n```swift\nfunc respond(userInput: String) async throws -> String {\n    let session = LanguageModelSession(instructions: \"\"\"\n        You are a friendly barista in a world full of pixels.\n        Respond to the player's question.\n        \"\"\"\n    )\n    let response = try await session.respond(to: userInput)\n    return response.content\n}\n```\n\n#### From WWDC 301:1:05\n\n**Return Type**: `Response\u003CString>` with `.content` property\n\n### respond(to:generating:) Method\n\n**Structured Output with @Generable**:\n```swift\n@Generable\nstruct SearchSuggestions {\n    @Guide(description: \"A list of suggested search terms\", .count(4))\n    var searchTerms: [String]\n}\n\nlet prompt = \"\"\"\n    Generate a list of suggested search terms for an app about visiting famous landmarks.\n    \"\"\"\n\nlet response = try await session.respond(\n    to: prompt,\n    generating: SearchSuggestions.self\n)\n\nprint(response.content) \u002F\u002F SearchSuggestions instance\n```\n\n#### From WWDC 286:5:51\n\n**Return Type**: `Response\u003CSearchSuggestions>` with `.content` property\n\n### Generation Options\n\nSee [Sampling & Generation Options](#sampling--generation-options) for `GenerationOptions` including `sampling:`, `temperature:`, and `includeSchemaInPrompt:`.\n\n---\n\n## Multi-Turn Interactions\n\n### Retaining Context\n\n```swift\nlet session = LanguageModelSession()\n\n\u002F\u002F First turn\nlet firstHaiku = try await session.respond(to: \"Write a haiku about fishing\")\nprint(firstHaiku.content)\n\u002F\u002F Silent waters gleam,\n\u002F\u002F Casting lines in morning mist—\n\u002F\u002F Hope in every cast.\n\n\u002F\u002F Second turn - model remembers context\nlet secondHaiku = try await session.respond(to: \"Do another one about golf\")\nprint(secondHaiku.content)\n\u002F\u002F Silent morning dew,\n\u002F\u002F Caddies guide with gentle words—\n\u002F\u002F Paths of patience tread.\n\nprint(session.transcript) \u002F\u002F Shows full history\n```\n\n#### From WWDC 286:17:46\n\n**How it works**:\n- Each `respond()` call adds entry to transcript\n- Model uses entire transcript for context\n- Enables conversational interactions\n\n### Transcript Property\n\n```swift\nlet transcript = session.transcript\n\nfor entry in transcript.entries {\n    print(\"Entry: \\(entry.content)\")\n}\n```\n\n**Use cases**:\n- Debugging generation issues\n- Displaying conversation history in UI\n- Exporting chat logs\n- Condensing for context management\n\n---\n\n## isResponding Property\n\nGate UI on `session.isResponding` to prevent concurrent requests:\n\n```swift\nButton(\"Go!\") {\n    Task { haiku = try await session.respond(to: prompt).content }\n}\n.disabled(session.isResponding)\n```\n\n#### From WWDC 286:18:22\n\n---\n\n## @Generable Macro\n\n### Overview\n\n`@Generable` enables structured output from the model using Swift types. The macro generates a schema at compile-time and uses **constrained decoding** to guarantee structural correctness.\n\n### Basic Usage\n\n**On Structs**:\n```swift\n@Generable\nstruct Person {\n    let name: String\n    let age: Int\n}\n\nlet response = try await session.respond(\n    to: \"Generate a person\",\n    generating: Person.self\n)\n\nlet person = response.content \u002F\u002F Type-safe Person instance\n```\n\n#### From WWDC 301:8:14\n\n**On Enums**:\n```swift\n@Generable\nstruct NPC {\n    let name: String\n    let encounter: Encounter\n\n    @Generable\n    enum Encounter {\n        case orderCoffee(String)\n        case wantToTalkToManager(complaint: String)\n    }\n}\n```\n\n#### From WWDC 301:10:49\n\n### Supported Types\n\n**Primitives**:\n- `String`\n- `Int`, `Float`, `Double`, `Decimal`\n- `Bool`\n\n**Collections**:\n- `[ElementType]` (arrays)\n\n**Composed Types**:\n```swift\n@Generable\nstruct Itinerary {\n    var destination: String\n    var days: Int\n    var budget: Float\n    var rating: Double\n    var requiresVisa: Bool\n    var activities: [String]\n    var emergencyContact: Person\n    var relatedItineraries: [Itinerary] \u002F\u002F Recursive!\n}\n```\n\n#### From WWDC 286:6:18\n\n### @Guide Constraints\n\n`@Guide` constrains generated properties. Supports `description:` (natural language), `.range()` (numeric bounds), `.count()` \u002F `.maximumCount()` (array length), and `Regex` (pattern matching).\n\n```swift\n@Generable\nstruct NPC {\n    @Guide(description: \"A full name\")\n    let name: String\n\n    @Guide(.range(1...10))\n    let level: Int\n\n    @Guide(.count(3))\n    let attributes: [String]\n}\n```\n\n#### From WWDC 301:11:20\n\n### Constrained Decoding\n\n**How it works**:\n1. `@Generable` macro generates schema at compile-time\n2. Schema defines valid token sequences\n3. During generation, model creates probability distribution for next token\n4. Framework **masks out invalid tokens** based on schema\n5. Model can only pick tokens valid according to schema\n6. Guarantees structural correctness - no hallucinated keys, no invalid JSON\n\n**From WWDC 286**: \"Constrained decoding prevents structural mistakes. Model is prevented from generating invalid field names or wrong types.\"\n\n**Benefits**:\n- Zero parsing code needed\n- No runtime parsing errors\n- Type-safe Swift objects\n- Compile-time safety (changes to struct caught by compiler)\n\n### Property Declaration Order\n\n**Properties generated in order declared**:\n```swift\n@Generable\nstruct Itinerary {\n    var name: String        \u002F\u002F Generated FIRST\n    var days: [DayPlan]     \u002F\u002F Generated SECOND\n    var summary: String     \u002F\u002F Generated LAST\n}\n```\n\n**Why it matters**:\n- Later properties can reference earlier ones\n- Better model quality: Summaries after content\n- Better streaming UX: Important properties first\n\n#### From WWDC 286:11:00\n\n---\n\n## Streaming\n\n### Overview\n\nFoundation Models uses **snapshot streaming** (not delta streaming). Instead of raw deltas, the framework streams `PartiallyGenerated` types with optional properties that fill in progressively.\n\n### PartiallyGenerated Type\n\nThe `@Generable` macro automatically creates a `PartiallyGenerated` nested type:\n\n```swift\n@Generable\nstruct Itinerary {\n    var name: String\n    var days: [DayPlan]\n}\n\n\u002F\u002F Compiler generates:\nextension Itinerary {\n    struct PartiallyGenerated {\n        var name: String?        \u002F\u002F All properties optional!\n        var days: [DayPlan]?\n    }\n}\n```\n\n#### From WWDC 286:9:20\n\n### streamResponse Method\n\n```swift\n@Generable\nstruct Itinerary {\n    var name: String\n    var days: [Day]\n}\n\nlet stream = session.streamResponse(\n    to: \"Craft a 3-day itinerary to Mt. Fuji.\",\n    generating: Itinerary.self\n)\n\nfor try await partial in stream {\n    print(partial) \u002F\u002F Incrementally updated Itinerary.PartiallyGenerated\n}\n```\n\n#### From WWDC 286:9:40\n\n**Return Type**: `AsyncSequence\u003CItinerary.PartiallyGenerated>`\n\n### SwiftUI Integration\n\n```swift\nstruct ItineraryView: View {\n    let session: LanguageModelSession\n    let dayCount: Int\n    let landmarkName: String\n\n    @State\n    private var itinerary: Itinerary.PartiallyGenerated?\n\n    var body: some View {\n        VStack {\n            if let name = itinerary?.name {\n                Text(name).font(.title)\n            }\n\n            if let days = itinerary?.days {\n                ForEach(days, id: \\.self) { day in\n                    DayView(day: day)\n                }\n            }\n\n            Button(\"Start\") {\n                Task {\n                    do {\n                        let prompt = \"\"\"\n                            Generate a \\(dayCount) itinerary \\\n                            to \\(landmarkName).\n                            \"\"\"\n\n                        let stream = session.streamResponse(\n                            to: prompt,\n                            generating: Itinerary.self\n                        )\n\n                        for try await partial in stream {\n                            self.itinerary = partial\n                        }\n                    } catch {\n                        print(error)\n                    }\n                }\n            }\n        }\n    }\n}\n```\n\n#### From WWDC 286:10:05\n\n### Best Practices\n\n**1. Use SwiftUI animations**:\n```swift\nif let name = itinerary?.name {\n    Text(name)\n        .transition(.opacity)\n}\n```\n\n**2. View identity for arrays**:\n```swift\n\u002F\u002F ✅ GOOD - Stable identity\nForEach(days, id: \\.id) { day in\n    DayView(day: day)\n}\n\n\u002F\u002F ❌ BAD - Identity changes\nForEach(days.indices, id: \\.self) { index in\n    DayView(day: days[index])\n}\n```\n\n**3. Property order optimization**:\n```swift\n\u002F\u002F ✅ GOOD - Title first for streaming\n@Generable\nstruct Article {\n    var title: String      \u002F\u002F Shows immediately\n    var summary: String    \u002F\u002F Shows second\n    var fullText: String   \u002F\u002F Shows last\n}\n```\n\n#### From WWDC 286:11:00\n\n---\n\n## Tool Protocol\n\n### Overview\n\nTools let the model autonomously execute your custom code to fetch external data or perform actions. Tools integrate with MapKit, WeatherKit, Contacts, EventKit, or any custom API.\n\n### Protocol Definition\n\n```swift\nprotocol Tool {\n    var name: String { get }\n    var description: String { get }\n\n    associatedtype Arguments: Generable\n\n    func call(arguments: Arguments) async throws -> ToolOutput\n}\n```\n\n### Example: GetWeatherTool\n\n```swift\nimport FoundationModels\nimport WeatherKit\nimport CoreLocation\n\nstruct GetWeatherTool: Tool {\n    let name = \"getWeather\"\n    let description = \"Retrieve the latest weather information for a city\"\n\n    @Generable\n    struct Arguments {\n        @Guide(description: \"The city to fetch the weather for\")\n        var city: String\n    }\n\n    func call(arguments: Arguments) async throws -> ToolOutput {\n        let places = try await CLGeocoder().geocodeAddressString(arguments.city)\n        let weather = try await WeatherService.shared.weather(for: places.first!.location!)\n        let temperature = weather.currentWeather.temperature.value\n\n        let content = GeneratedContent(properties: [\"temperature\": temperature])\n        let output = ToolOutput(content)\n\n        \u002F\u002F Or if your tool's output is natural language:\n        \u002F\u002F let output = ToolOutput(\"\\(arguments.city)'s temperature is \\(temperature) degrees.\")\n\n        return output\n    }\n}\n```\n\n#### From WWDC 286:13:42\n\n### Attaching Tools to Session\n\n```swift\nlet session = LanguageModelSession(\n    tools: [GetWeatherTool()],\n    instructions: \"Help the user with weather forecasts.\"\n)\n\nlet response = try await session.respond(\n    to: \"What is the temperature in Cupertino?\"\n)\n\nprint(response.content)\n\u002F\u002F It's 71˚F in Cupertino!\n```\n\n#### From WWDC 286:15:03\n\n**How it works**:\n1. Session initialized with tools\n2. User prompt: \"What's Tokyo's weather?\"\n3. Model analyzes prompt, decides weather data needed\n4. Model generates tool call: `getWeather(city: \"Tokyo\")`\n5. Framework calls `call()` method\n6. Your code fetches real data from API\n7. Tool output inserted into transcript\n8. Model generates final response using tool output\n\n**From WWDC 301**: \"Model autonomously decides when and how often to call tools. Can call multiple tools per request, even in parallel.\"\n\n### Stateful Tools\n\nUse `class` instead of `struct` to maintain state across tool calls. The tool instance persists for the session lifetime, enabling patterns like tracking previously returned results:\n\n```swift\nclass FindContactTool: Tool {\n    let name = \"findContact\"\n    let description = \"Finds a contact from a specified age generation.\"\n    var pickedContacts = Set\u003CString>()\n\n    @Generable\n    struct Arguments {\n        let generation: Generation\n        @Generable\n        enum Generation { case babyBoomers, genX, millennial, genZ }\n    }\n\n    func call(arguments: Arguments) async throws -> ToolOutput {\n        \u002F\u002F Fetch, filter out already-picked, return new contact\n        pickedContacts.insert(pickedContact.givenName)\n        return ToolOutput(pickedContact.givenName)\n    }\n}\n```\n\n#### From WWDC 301:18:47, 301:21:55\n\n### ToolOutput\n\n**Two forms**:\n\n1. **Natural language** (String):\n```swift\nreturn ToolOutput(\"Temperature is 71°F\")\n```\n\n2. **Structured** (GeneratedContent):\n```swift\nlet content = GeneratedContent(properties: [\"temperature\": 71])\nreturn ToolOutput(content)\n```\n\n### Tool Naming Best Practices\n\n**DO**:\n- Short, readable names: `getWeather`, `findContact`\n- Use verbs: `get`, `find`, `fetch`, `create`\n- One sentence descriptions\n- Keep descriptions concise (they're in prompt)\n\n**DON'T**:\n- Abbreviations: `gtWthr`\n- Implementation details in description\n- Long descriptions (increases token count)\n\n**From WWDC 301**: \"Tool name and description put verbatim in prompt. Longer strings mean more tokens, which increases latency.\"\n\n### Multiple Tools\n\n```swift\nlet session = LanguageModelSession(\n    tools: [\n        GetWeatherTool(),\n        FindRestaurantTool(),\n        FindHotelTool()\n    ],\n    instructions: \"Plan travel itineraries.\"\n)\n\n\u002F\u002F Model autonomously decides which tools to call and when\n```\n\n### Tool Calling Behavior\n\n**Key facts**:\n- Tool can be called **multiple times** per request\n- Multiple tools can be called **in parallel**\n- Model decides **when** to call (not guaranteed to call)\n- Arguments guaranteed valid via @Generable\n\n**From WWDC 301**: \"When tools called in parallel, your call method may execute concurrently. Keep this in mind when accessing data.\"\n\n---\n\n## Dynamic Schemas\n\n### Overview\n\n`DynamicGenerationSchema` enables creating schemas at runtime instead of compile-time. Useful for user-defined structures, level creators, or dynamic forms.\n\n### Creating and Using Dynamic Schemas\n\nBuild properties with `DynamicGenerationSchema.Property`, compose into schemas, then validate with `GenerationSchema`:\n\n```swift\n\u002F\u002F Build schema at runtime\nlet questionProp = DynamicGenerationSchema.Property(\n    name: \"question\", schema: DynamicGenerationSchema(type: String.self)\n)\nlet answersProp = DynamicGenerationSchema.Property(\n    name: \"answers\", schema: DynamicGenerationSchema(\n        arrayOf: DynamicGenerationSchema(referenceTo: \"Answer\")\n    )\n)\n\nlet riddleSchema = DynamicGenerationSchema(name: \"Riddle\", properties: [questionProp, answersProp])\nlet answerSchema = DynamicGenerationSchema(name: \"Answer\", properties: [\u002F* text, isCorrect *\u002F])\n\n\u002F\u002F Validate and use\nlet schema = try GenerationSchema(root: riddleSchema, dependencies: [answerSchema])\nlet response = try await session.respond(to: \"Generate a riddle\", schema: schema)\n\nlet question = try response.content.value(String.self, forProperty: \"question\")\n```\n\n#### From WWDC 301:14:50, 301:15:10\n\n### Dynamic vs Static @Generable\n\n**Use @Generable when**:\n- Structure known at compile-time\n- Want type safety\n- Want automatic parsing\n\n**Use Dynamic Schemas when**:\n- Structure only known at runtime\n- User-defined schemas\n- Maximum flexibility\n\n**From WWDC 301**: \"Compile-time @Generable gives type safety. Dynamic schemas give runtime flexibility. Both use same constrained decoding guarantees.\"\n\n---\n\n## Sampling & Generation Options\n\n**Greedy (deterministic)** — use for tests and demos. Only deterministic within same model version:\n```swift\nlet response = try await session.respond(\n    to: prompt,\n    options: GenerationOptions(sampling: .greedy)\n)\n```\n\n**Temperature** — controls variance. `0.1-0.5` focused, `1.0` default, `1.5-2.0` creative:\n```swift\nlet response = try await session.respond(\n    to: prompt,\n    options: GenerationOptions(temperature: 0.5)\n)\n```\n\n#### From WWDC 301:6:14\n\n---\n\n## Built-in Use Cases\n\n### Content Tagging Adapter\n\n**Specialized adapter for**:\n- Tag generation\n- Entity extraction\n- Topic detection\n\n```swift\n@Generable\nstruct Result {\n    let topics: [String]\n}\n\nlet session = LanguageModelSession(\n    model: SystemLanguageModel(useCase: .contentTagging)\n)\n\nlet response = try await session.respond(\n    to: articleText,\n    generating: Result.self\n)\n```\n\n#### From WWDC 286:19:19\n\n### Custom Use Cases\n\n**With custom instructions**:\n```swift\n@Generable\nstruct Top3ActionEmotionResult {\n    @Guide(.maximumCount(3))\n    let actions: [String]\n    @Guide(.maximumCount(3))\n    let emotions: [String]\n}\n\nlet session = LanguageModelSession(\n    model: SystemLanguageModel(useCase: .contentTagging),\n    instructions: \"Tag the 3 most important actions and emotions in the given input text.\"\n)\n\nlet response = try await session.respond(\n    to: text,\n    generating: Top3ActionEmotionResult.self\n)\n```\n\n#### From WWDC 286:19:35\n\n---\n\n## Error Handling\n\n### GenerationError Types\n\nCatch `LanguageModelSession.GenerationError` cases:\n- **`.exceededContextWindowSize`** — Context limit (4096 tokens) exceeded. Condense transcript or create new session.\n- **`.guardrailViolation`** — Content policy triggered. Show graceful message.\n- **`.unsupportedLanguageOrLocale`** — Language not supported. Check `supportedLanguages`.\n\n#### From WWDC 301:3:37, 301:7:06\n\n### Context Window Management\n\n#### Strategy 1: Fresh Session\n```swift\nvar session = LanguageModelSession()\n\ndo {\n    let response = try await session.respond(to: prompt)\n    print(response.content)\n} catch LanguageModelSession.GenerationError.exceededContextWindowSize {\n    \u002F\u002F New session, no history\n    session = LanguageModelSession()\n}\n```\n\n#### From WWDC 301:3:37\n\n#### Strategy 2: Condensed Session\n```swift\ndo {\n    let response = try await session.respond(to: prompt)\n} catch LanguageModelSession.GenerationError.exceededContextWindowSize {\n    \u002F\u002F New session with some history\n    session = newSession(previousSession: session)\n}\n\nprivate func newSession(previousSession: LanguageModelSession) -> LanguageModelSession {\n    let allEntries = previousSession.transcript.entries\n    var condensedEntries = [Transcript.Entry]()\n\n    if let firstEntry = allEntries.first {\n        condensedEntries.append(firstEntry) \u002F\u002F Instructions\n\n        if allEntries.count > 1, let lastEntry = allEntries.last {\n            condensedEntries.append(lastEntry) \u002F\u002F Recent context\n        }\n    }\n\n    let condensedTranscript = Transcript(entries: condensedEntries)\n    \u002F\u002F Note: transcript includes instructions\n    return LanguageModelSession(transcript: condensedTranscript)\n}\n```\n\n#### From WWDC 301:3:55\n\n### Fallback Architecture\n\nWhen Foundation Models is unavailable (older device, user opted out, unsupported region), provide graceful degradation:\n\n```swift\nfunc summarize(_ text: String) async throws -> String {\n    let model = SystemLanguageModel.default\n    switch model.availability {\n    case .available:\n        let session = LanguageModelSession()\n        let response = try await session.respond(to: \"Summarize: \\(text)\")\n        return response.content\n    case .unavailable:\n        \u002F\u002F Fallback: truncate with ellipsis, or call server API\n        return String(text.prefix(200)) + \"...\"\n    }\n}\n```\n\n**Architecture pattern**: Wrap Foundation Models behind a protocol so you can swap implementations:\n\n```swift\nprotocol TextSummarizer {\n    func summarize(_ text: String) async throws -> String\n}\n\nstruct OnDeviceSummarizer: TextSummarizer { \u002F* Foundation Models *\u002F }\nstruct ServerSummarizer: TextSummarizer { \u002F* Server API fallback *\u002F }\nstruct TruncationSummarizer: TextSummarizer { \u002F* Simple truncation *\u002F }\n```\n\n### Nested @Generable Troubleshooting\n\nNested `@Generable` types must each independently conform to `@Generable`:\n\n```swift\n\u002F\u002F ✅ Both types marked @Generable\n@Generable struct Itinerary {\n    var days: [DayPlan]\n}\n\n@Generable struct DayPlan {\n    var activities: [String]\n}\n\n\u002F\u002F ❌ Will fail — nested type not @Generable\n@Generable struct Itinerary {\n    var days: [DayPlan]  \u002F\u002F DayPlan must also be @Generable\n}\nstruct DayPlan { var activities: [String] }\n```\n\n**Common issue**: Arrays of non-Generable types compile but fail at runtime. Check all types in the graph.\n\n---\n\n## Availability\n\n### Checking Availability\n\n```swift\nstruct AvailabilityExample: View {\n    private let model = SystemLanguageModel.default\n\n    var body: some View {\n        switch model.availability {\n        case .available:\n            Text(\"Model is available\").foregroundStyle(.green)\n        case .unavailable(let reason):\n            Text(\"Model is unavailable\").foregroundStyle(.red)\n            Text(\"Reason: \\(reason)\")\n        }\n    }\n}\n```\n\n#### From WWDC 286:19:56\n\n### Supported Languages\n\n```swift\nlet supportedLanguages = SystemLanguageModel.default.supportedLanguages\nguard supportedLanguages.contains(Locale.current.language) else {\n    \u002F\u002F Show message\n    return\n}\n```\n\n#### From WWDC 301:7:06\n\n### Requirements\n\n**Device Requirements**:\n- Apple Intelligence-enabled device\n- iPhone 15 Pro or later\n- iPad with M1+ chip\n- Mac with Apple silicon\n\n**Region Requirements**:\n- Supported region (check Apple Intelligence availability)\n\n**User Requirements**:\n- User opted in to Apple Intelligence in Settings\n\n---\n\n## Performance & Profiling\n\n### Foundation Models Instrument\n\n**Access**: Instruments app → Foundation Models template\n\n**Metrics**:\n- Initial model load time\n- Token counts (input\u002Foutput)\n- Generation time per request\n- Latency breakdown\n- Optimization opportunities\n\n**From WWDC 286**: \"New Instruments profiling template lets you observe areas of optimization and quantify improvements.\"\n\n### Optimization: Prewarming\n\n**Problem**: First request takes 1-2s to load model\n\n**Solution**: Create session before user interaction\n\n```swift\nclass ViewModel: ObservableObject {\n    private var session: LanguageModelSession?\n\n    init() {\n        \u002F\u002F Prewarm on init\n        Task {\n            self.session = LanguageModelSession(instructions: \"...\")\n        }\n    }\n\n    func generate(prompt: String) async throws -> String {\n        let response = try await session!.respond(to: prompt)\n        return response.content\n    }\n}\n```\n\n**From WWDC 259**: \"Prewarming session before user interaction reduces initial latency.\"\n\n**Time saved**: 1-2 seconds off first generation\n\n### Optimization: includeSchemaInPrompt\n\n**Problem**: Large @Generable schemas increase token count\n\n**Solution**: Skip schema insertion for subsequent requests\n\n```swift\n\u002F\u002F First request - schema inserted\nlet first = try await session.respond(\n    to: \"Generate first person\",\n    generating: Person.self\n)\n\n\u002F\u002F Subsequent requests - skip schema\nlet second = try await session.respond(\n    to: \"Generate another person\",\n    generating: Person.self,\n    options: GenerationOptions(includeSchemaInPrompt: false)\n)\n```\n\n**From WWDC 259**: \"Setting includeSchemaInPrompt to false decreases token count and latency for subsequent requests.\"\n\n**Time saved**: 10-20% per request\n\n### Optimization: Property Order\n\nDeclare important properties first in `@Generable` structs. With streaming, perceived latency drops from 2.5s to 0.2s when title appears before full text. See [Streaming Best Practices](#best-practices) for examples.\n\n---\n\n## Feedback & Analytics\n\n`LanguageModelFeedbackAttachment` lets you report model quality issues to Apple via Feedback Assistant. Create with `input`, `output`, `sentiment` (`.positive`\u002F`.negative`), `issues` (category + explanation), and `desiredOutputExamples`. Encode as JSON and attach to a Feedback Assistant report.\n\n#### From WWDC 286:22:13\n\n---\n\n## Xcode Playgrounds\n\n### Overview\n\nXcode Playgrounds enable rapid iteration on prompts without rebuilding entire app.\n\n### Basic Usage\n\n```swift\nimport FoundationModels\nimport Playgrounds\n\n#Playground {\n    let session = LanguageModelSession()\n    let response = try await session.respond(\n        to: \"What's a good name for a trip to Japan? Respond only with a title\"\n    )\n}\n```\n\n#### From WWDC 286:2:28\n\nPlaygrounds can also access types defined in your app (like @Generable structs).\n\n---\n\n## API Quick Reference\n\n- **`LanguageModelSession`** — Main interface: `respond(to:)` → `Response\u003CString>`, `respond(to:generating:)` → `Response\u003CT>`, `streamResponse(to:generating:)` → `AsyncSequence\u003CT.PartiallyGenerated>`. Properties: `transcript`, `isResponding`.\n- **`SystemLanguageModel`** — `default.availability` (`.available`\u002F`.unavailable(reason)`), `default.supportedLanguages`, `init(useCase:)`\n- **`GenerationOptions`** — `sampling` (`.greedy`\u002F`.random`), `temperature`, `includeSchemaInPrompt`\n- **`@Generable`** — Macro enabling structured output with constrained decoding\n- **`@Guide`** — Property constraints: `description:`, `.range()`, `.count()`, `.maximumCount()`, `Regex`\n- **`Tool` protocol** — `name`, `description`, `Arguments: Generable`, `call(arguments:) → ToolOutput`\n- **`DynamicGenerationSchema`** — Runtime schema definition with `GeneratedContent` output\n- **`GenerationError`** — `.exceededContextWindowSize`, `.guardrailViolation`, `.unsupportedLanguageOrLocale`\n\n---\n\n## Migration Strategies\n\n### From Server LLMs\n\n- **Migrate when**: Privacy required, offline needed, per-request costs are a concern, and use case fits (summarization\u002Fextraction\u002Fclassification)\n- **Stay on server when**: Need world knowledge, complex reasoning, or >4096 token context\n\n### From Manual JSON Parsing\n\nUse `@Generable` with `respond(to:generating:)` instead of prompting for JSON and parsing manually. See `axiom-foundation-models` Scenario 2 for the complete migration pattern.\n\n---\n\n## Resources\n\n**WWDC**: 286, 259, 301\n\n**Skills**: axiom-foundation-models, axiom-foundation-models-diag\n\n---\n\n**Last Updated**: 2025-12-03\n**Version**: 1.0.0\n**Skill Type**: Reference\n**Content**: All WWDC 2025 code examples included\n\n","# Foundation Models Framework — Complete API Reference\n\n## Overview\n\nThe Foundation Models framework provides access to Apple's on-device Large Language Model (3 billion parameters, 2-bit quantized) with a Swift API. This reference covers every API, all WWDC 2025 code examples, and comprehensive implementation patterns.\n\n### Model Specifications\n\n3B parameter model, 2-bit quantized, 4096 token context (input + output combined). Optimized for on-device summarization, extraction, classification, and generation. NOT suited for world knowledge, complex reasoning, math, or translation. Runs entirely on-device — no network, no cost, no data leaves device.\n\n---\n\n## When to Use This Reference\n\nUse this reference when:\n- Implementing Foundation Models features\n- Understanding API capabilities\n- Looking up specific code examples\n- Planning architecture with Foundation Models\n- Migrating from prototype to production\n- Debugging implementation issues\n\n**Related Skills**:\n- `axiom-foundation-models` — Discipline skill with anti-patterns, pressure scenarios, decision trees\n- `axiom-foundation-models-diag` — Diagnostic skill for troubleshooting issues\n\n---\n\n## LanguageModelSession\n\n### Overview\n\n`LanguageModelSession` is the core class for interacting with the model. It maintains conversation history (transcript), handles multi-turn interactions, and manages model state.\n\n### Creating a Session\n\n**Basic Creation**:\n```swift\nimport FoundationModels\n\nlet session = LanguageModelSession()\n```\n\n**With Custom Instructions**:\n```swift\nlet session = LanguageModelSession(instructions: \"\"\"\n    You are a friendly barista in a pixel art coffee shop.\n    Respond to the player's question concisely.\n    \"\"\"\n)\n```\n\n#### From WWDC 301:1:05\n\n**With Tools**:\n```swift\nlet session = LanguageModelSession(\n    tools: [GetWeatherTool()],\n    instructions: \"Help user with weather forecasts.\"\n)\n```\n\n#### From WWDC 286:15:03\n\n**With Specific Model\u002FUse Case**:\n```swift\nlet session = LanguageModelSession(\n    model: SystemLanguageModel(useCase: .contentTagging)\n)\n```\n\n#### From WWDC 286:18:39\n\n### Instructions vs Prompts\n\n**Instructions**:\n- Come from **developer**\n- Define model's role, style, constraints\n- Mostly static\n- First entry in transcript\n- Model trained to obey instructions over prompts (security feature)\n\n**Prompts**:\n- Come from **user** (or dynamic app state)\n- Specific requests for generation\n- Dynamic input\n- Each call to `respond(to:)` adds prompt to transcript\n\n**Security Consideration**:\n- **NEVER** interpolate untrusted user input into instructions\n- User input should go in prompts only\n- Prevents prompt injection attacks\n\n### respond(to:) Method\n\n**Basic Text Generation**:\n```swift\nfunc respond(userInput: String) async throws -> String {\n    let session = LanguageModelSession(instructions: \"\"\"\n        You are a friendly barista in a world full of pixels.\n        Respond to the player's question.\n        \"\"\"\n    )\n    let response = try await session.respond(to: userInput)\n    return response.content\n}\n```\n\n#### From WWDC 301:1:05\n\n**Return Type**: `Response\u003CString>` with `.content` property\n\n### respond(to:generating:) Method\n\n**Structured Output with @Generable**:\n```swift\n@Generable\nstruct SearchSuggestions {\n    @Guide(description: \"A list of suggested search terms\", .count(4))\n    var searchTerms: [String]\n}\n\nlet prompt = \"\"\"\n    Generate a list of suggested search terms for an app about visiting famous landmarks.\n    \"\"\"\n\nlet response = try await session.respond(\n    to: prompt,\n    generating: SearchSuggestions.self\n)\n\nprint(response.content) \u002F\u002F SearchSuggestions instance\n```\n\n#### From WWDC 286:5:51\n\n**Return Type**: `Response\u003CSearchSuggestions>` with `.content` property\n\n### Generation Options\n\nSee [Sampling & Generation Options](#sampling--generation-options) for `GenerationOptions` including `sampling:`, `temperature:`, and `includeSchemaInPrompt:`.\n\n---\n\n## Multi-Turn Interactions\n\n### Retaining Context\n\n```swift\nlet session = LanguageModelSession()\n\n\u002F\u002F First turn\nlet firstHaiku = try await session.respond(to: \"Write a haiku about fishing\")\nprint(firstHaiku.content)\n\u002F\u002F Silent waters gleam,\n\u002F\u002F Casting lines in morning mist—\n\u002F\u002F Hope in every cast.\n\n\u002F\u002F Second turn - model remembers context\nlet secondHaiku = try await session.respond(to: \"Do another one about golf\")\nprint(secondHaiku.content)\n\u002F\u002F Silent morning dew,\n\u002F\u002F Caddies guide with gentle words—\n\u002F\u002F Paths of patience tread.\n\nprint(session.transcript) \u002F\u002F Shows full history\n```\n\n#### From WWDC 286:17:46\n\n**How it works**:\n- Each `respond()` call adds entry to transcript\n- Model uses entire transcript for context\n- Enables conversational interactions\n\n### Transcript Property\n\n```swift\nlet transcript = session.transcript\n\nfor entry in transcript.entries {\n    print(\"Entry: \\(entry.content)\")\n}\n```\n\n**Use cases**:\n- Debugging generation issues\n- Displaying conversation history in UI\n- Exporting chat logs\n- Condensing for context management\n\n---\n\n## isResponding Property\n\nGate UI on `session.isResponding` to prevent concurrent requests:\n\n```swift\nButton(\"Go!\") {\n    Task { haiku = try await session.respond(to: prompt).content }\n}\n.disabled(session.isResponding)\n```\n\n#### From WWDC 286:18:22\n\n---\n\n## @Generable Macro\n\n### Overview\n\n`@Generable` enables structured output from the model using Swift types. The macro generates a schema at compile-time and uses **constrained decoding** to guarantee structural correctness.\n\n### Basic Usage\n\n**On Structs**:\n```swift\n@Generable\nstruct Person {\n    let name: String\n    let age: Int\n}\n\nlet response = try await session.respond(\n    to: \"Generate a person\",\n    generating: Person.self\n)\n\nlet person = response.content \u002F\u002F Type-safe Person instance\n```\n\n#### From WWDC 301:8:14\n\n**On Enums**:\n```swift\n@Generable\nstruct NPC {\n    let name: String\n    let encounter: Encounter\n\n    @Generable\n    enum Encounter {\n        case orderCoffee(String)\n        case wantToTalkToManager(complaint: String)\n    }\n}\n```\n\n#### From WWDC 301:10:49\n\n### Supported Types\n\n**Primitives**:\n- `String`\n- `Int`, `Float`, `Double`, `Decimal`\n- `Bool`\n\n**Collections**:\n- `[ElementType]` (arrays)\n\n**Composed Types**:\n```swift\n@Generable\nstruct Itinerary {\n    var destination: String\n    var days: Int\n    var budget: Float\n    var rating: Double\n    var requiresVisa: Bool\n    var activities: [String]\n    var emergencyContact: Person\n    var relatedItineraries: [Itinerary] \u002F\u002F Recursive!\n}\n```\n\n#### From WWDC 286:6:18\n\n### @Guide Constraints\n\n`@Guide` constrains generated properties. Supports `description:` (natural language), `.range()` (numeric bounds), `.count()` \u002F `.maximumCount()` (array length), and `Regex` (pattern matching).\n\n```swift\n@Generable\nstruct NPC {\n    @Guide(description: \"A full name\")\n    let name: String\n\n    @Guide(.range(1...10))\n    let level: Int\n\n    @Guide(.count(3))\n    let attributes: [String]\n}\n```\n\n#### From WWDC 301:11:20\n\n### Constrained Decoding\n\n**How it works**:\n1. `@Generable` macro generates schema at compile-time\n2. Schema defines valid token sequences\n3. During generation, model creates probability distribution for next token\n4. Framework **masks out invalid tokens** based on schema\n5. Model can only pick tokens valid according to schema\n6. Guarantees structural correctness - no hallucinated keys, no invalid JSON\n\n**From WWDC 286**: \"Constrained decoding prevents structural mistakes. Model is prevented from generating invalid field names or wrong types.\"\n\n**Benefits**:\n- Zero parsing code needed\n- No runtime parsing errors\n- Type-safe Swift objects\n- Compile-time safety (changes to struct caught by compiler)\n\n### Property Declaration Order\n\n**Properties generated in order declared**:\n```swift\n@Generable\nstruct Itinerary {\n    var name: String        \u002F\u002F Generated FIRST\n    var days: [DayPlan]     \u002F\u002F Generated SECOND\n    var summary: String     \u002F\u002F Generated LAST\n}\n```\n\n**Why it matters**:\n- Later properties can reference earlier ones\n- Better model quality: Summaries after content\n- Better streaming UX: Important properties first\n\n#### From WWDC 286:11:00\n\n---\n\n## Streaming\n\n### Overview\n\nFoundation Models uses **snapshot streaming** (not delta streaming). Instead of raw deltas, the framework streams `PartiallyGenerated` types with optional properties that fill in progressively.\n\n### PartiallyGenerated Type\n\nThe `@Generable` macro automatically creates a `PartiallyGenerated` nested type:\n\n```swift\n@Generable\nstruct Itinerary {\n    var name: String\n    var days: [DayPlan]\n}\n\n\u002F\u002F Compiler generates:\nextension Itinerary {\n    struct PartiallyGenerated {\n        var name: String?        \u002F\u002F All properties optional!\n        var days: [DayPlan]?\n    }\n}\n```\n\n#### From WWDC 286:9:20\n\n### streamResponse Method\n\n```swift\n@Generable\nstruct Itinerary {\n    var name: String\n    var days: [Day]\n}\n\nlet stream = session.streamResponse(\n    to: \"Craft a 3-day itinerary to Mt. Fuji.\",\n    generating: Itinerary.self\n)\n\nfor try await partial in stream {\n    print(partial) \u002F\u002F Incrementally updated Itinerary.PartiallyGenerated\n}\n```\n\n#### From WWDC 286:9:40\n\n**Return Type**: `AsyncSequence\u003CItinerary.PartiallyGenerated>`\n\n### SwiftUI Integration\n\n```swift\nstruct ItineraryView: View {\n    let session: LanguageModelSession\n    let dayCount: Int\n    let landmarkName: String\n\n    @State\n    private var itinerary: Itinerary.PartiallyGenerated?\n\n    var body: some View {\n        VStack {\n            if let name = itinerary?.name {\n                Text(name).font(.title)\n            }\n\n            if let days = itinerary?.days {\n                ForEach(days, id: \\.self) { day in\n                    DayView(day: day)\n                }\n            }\n\n            Button(\"Start\") {\n                Task {\n                    do {\n                        let prompt = \"\"\"\n                            Generate a \\(dayCount) itinerary \\\n                            to \\(landmarkName).\n                            \"\"\"\n\n                        let stream = session.streamResponse(\n                            to: prompt,\n                            generating: Itinerary.self\n                        )\n\n                        for try await partial in stream {\n                            self.itinerary = partial\n                        }\n                    } catch {\n                        print(error)\n                    }\n                }\n            }\n        }\n    }\n}\n```\n\n#### From WWDC 286:10:05\n\n### Best Practices\n\n**1. Use SwiftUI animations**:\n```swift\nif let name = itinerary?.name {\n    Text(name)\n        .transition(.opacity)\n}\n```\n\n**2. View identity for arrays**:\n```swift\n\u002F\u002F ✅ GOOD - Stable identity\nForEach(days, id: \\.id) { day in\n    DayView(day: day)\n}\n\n\u002F\u002F ❌ BAD - Identity changes\nForEach(days.indices, id: \\.self) { index in\n    DayView(day: days[index])\n}\n```\n\n**3. Property order optimization**:\n```swift\n\u002F\u002F ✅ GOOD - Title first for streaming\n@Generable\nstruct Article {\n    var title: String      \u002F\u002F Shows immediately\n    var summary: String    \u002F\u002F Shows second\n    var fullText: String   \u002F\u002F Shows last\n}\n```\n\n#### From WWDC 286:11:00\n\n---\n\n## Tool Protocol\n\n### Overview\n\nTools let the model autonomously execute your custom code to fetch external data or perform actions. Tools integrate with MapKit, WeatherKit, Contacts, EventKit, or any custom API.\n\n### Protocol Definition\n\n```swift\nprotocol Tool {\n    var name: String { get }\n    var description: String { get }\n\n    associatedtype Arguments: Generable\n\n    func call(arguments: Arguments) async throws -> ToolOutput\n}\n```\n\n### Example: GetWeatherTool\n\n```swift\nimport FoundationModels\nimport WeatherKit\nimport CoreLocation\n\nstruct GetWeatherTool: Tool {\n    let name = \"getWeather\"\n    let description = \"Retrieve the latest weather information for a city\"\n\n    @Generable\n    struct Arguments {\n        @Guide(description: \"The city to fetch the weather for\")\n        var city: String\n    }\n\n    func call(arguments: Arguments) async throws -> ToolOutput {\n        let places = try await CLGeocoder().geocodeAddressString(arguments.city)\n        let weather = try await WeatherService.shared.weather(for: places.first!.location!)\n        let temperature = weather.currentWeather.temperature.value\n\n        let content = GeneratedContent(properties: [\"temperature\": temperature])\n        let output = ToolOutput(content)\n\n        \u002F\u002F Or if your tool's output is natural language:\n        \u002F\u002F let output = ToolOutput(\"\\(arguments.city)'s temperature is \\(temperature) degrees.\")\n\n        return output\n    }\n}\n```\n\n#### From WWDC 286:13:42\n\n### Attaching Tools to Session\n\n```swift\nlet session = LanguageModelSession(\n    tools: [GetWeatherTool()],\n    instructions: \"Help the user with weather forecasts.\"\n)\n\nlet response = try await session.respond(\n    to: \"What is the temperature in Cupertino?\"\n)\n\nprint(response.content)\n\u002F\u002F It's 71˚F in Cupertino!\n```\n\n#### From WWDC 286:15:03\n\n**How it works**:\n1. Session initialized with tools\n2. User prompt: \"What's Tokyo's weather?\"\n3. Model analyzes prompt, decides weather data needed\n4. Model generates tool call: `getWeather(city: \"Tokyo\")`\n5. Framework calls `call()` method\n6. Your code fetches real data from API\n7. Tool output inserted into transcript\n8. Model generates final response using tool output\n\n**From WWDC 301**: \"Model autonomously decides when and how often to call tools. Can call multiple tools per request, even in parallel.\"\n\n### Stateful Tools\n\nUse `class` instead of `struct` to maintain state across tool calls. The tool instance persists for the session lifetime, enabling patterns like tracking previously returned results:\n\n```swift\nclass FindContactTool: Tool {\n    let name = \"findContact\"\n    let description = \"Finds a contact from a specified age generation.\"\n    var pickedContacts = Set\u003CString>()\n\n    @Generable\n    struct Arguments {\n        let generation: Generation\n        @Generable\n        enum Generation { case babyBoomers, genX, millennial, genZ }\n    }\n\n    func call(arguments: Arguments) async throws -> ToolOutput {\n        \u002F\u002F Fetch, filter out already-picked, return new contact\n        pickedContacts.insert(pickedContact.givenName)\n        return ToolOutput(pickedContact.givenName)\n    }\n}\n```\n\n#### From WWDC 301:18:47, 301:21:55\n\n### ToolOutput\n\n**Two forms**:\n\n1. **Natural language** (String):\n```swift\nreturn ToolOutput(\"Temperature is 71°F\")\n```\n\n2. **Structured** (GeneratedContent):\n```swift\nlet content = GeneratedContent(properties: [\"temperature\": 71])\nreturn ToolOutput(content)\n```\n\n### Tool Naming Best Practices\n\n**DO**:\n- Short, readable names: `getWeather`, `findContact`\n- Use verbs: `get`, `find`, `fetch`, `create`\n- One sentence descriptions\n- Keep descriptions concise (they're in prompt)\n\n**DON'T**:\n- Abbreviations: `gtWthr`\n- Implementation details in description\n- Long descriptions (increases token count)\n\n**From WWDC 301**: \"Tool name and description put verbatim in prompt. Longer strings mean more tokens, which increases latency.\"\n\n### Multiple Tools\n\n```swift\nlet session = LanguageModelSession(\n    tools: [\n        GetWeatherTool(),\n        FindRestaurantTool(),\n        FindHotelTool()\n    ],\n    instructions: \"Plan travel itineraries.\"\n)\n\n\u002F\u002F Model autonomously decides which tools to call and when\n```\n\n### Tool Calling Behavior\n\n**Key facts**:\n- Tool can be called **multiple times** per request\n- Multiple tools can be called **in parallel**\n- Model decides **when** to call (not guaranteed to call)\n- Arguments guaranteed valid via @Generable\n\n**From WWDC 301**: \"When tools called in parallel, your call method may execute concurrently. Keep this in mind when accessing data.\"\n\n---\n\n## Dynamic Schemas\n\n### Overview\n\n`DynamicGenerationSchema` enables creating schemas at runtime instead of compile-time. Useful for user-defined structures, level creators, or dynamic forms.\n\n### Creating and Using Dynamic Schemas\n\nBuild properties with `DynamicGenerationSchema.Property`, compose into schemas, then validate with `GenerationSchema`:\n\n```swift\n\u002F\u002F Build schema at runtime\nlet questionProp = DynamicGenerationSchema.Property(\n    name: \"question\", schema: DynamicGenerationSchema(type: String.self)\n)\nlet answersProp = DynamicGenerationSchema.Property(\n    name: \"answers\", schema: DynamicGenerationSchema(\n        arrayOf: DynamicGenerationSchema(referenceTo: \"Answer\")\n    )\n)\n\nlet riddleSchema = DynamicGenerationSchema(name: \"Riddle\", properties: [questionProp, answersProp])\nlet answerSchema = DynamicGenerationSchema(name: \"Answer\", properties: [\u002F* text, isCorrect *\u002F])\n\n\u002F\u002F Validate and use\nlet schema = try GenerationSchema(root: riddleSchema, dependencies: [answerSchema])\nlet response = try await session.respond(to: \"Generate a riddle\", schema: schema)\n\nlet question = try response.content.value(String.self, forProperty: \"question\")\n```\n\n#### From WWDC 301:14:50, 301:15:10\n\n### Dynamic vs Static @Generable\n\n**Use @Generable when**:\n- Structure known at compile-time\n- Want type safety\n- Want automatic parsing\n\n**Use Dynamic Schemas when**:\n- Structure only known at runtime\n- User-defined schemas\n- Maximum flexibility\n\n**From WWDC 301**: \"Compile-time @Generable gives type safety. Dynamic schemas give runtime flexibility. Both use same constrained decoding guarantees.\"\n\n---\n\n## Sampling & Generation Options\n\n**Greedy (deterministic)** — use for tests and demos. Only deterministic within same model version:\n```swift\nlet response = try await session.respond(\n    to: prompt,\n    options: GenerationOptions(sampling: .greedy)\n)\n```\n\n**Temperature** — controls variance. `0.1-0.5` focused, `1.0` default, `1.5-2.0` creative:\n```swift\nlet response = try await session.respond(\n    to: prompt,\n    options: GenerationOptions(temperature: 0.5)\n)\n```\n\n#### From WWDC 301:6:14\n\n---\n\n## Built-in Use Cases\n\n### Content Tagging Adapter\n\n**Specialized adapter for**:\n- Tag generation\n- Entity extraction\n- Topic detection\n\n```swift\n@Generable\nstruct Result {\n    let topics: [String]\n}\n\nlet session = LanguageModelSession(\n    model: SystemLanguageModel(useCase: .contentTagging)\n)\n\nlet response = try await session.respond(\n    to: articleText,\n    generating: Result.self\n)\n```\n\n#### From WWDC 286:19:19\n\n### Custom Use Cases\n\n**With custom instructions**:\n```swift\n@Generable\nstruct Top3ActionEmotionResult {\n    @Guide(.maximumCount(3))\n    let actions: [String]\n    @Guide(.maximumCount(3))\n    let emotions: [String]\n}\n\nlet session = LanguageModelSession(\n    model: SystemLanguageModel(useCase: .contentTagging),\n    instructions: \"Tag the 3 most important actions and emotions in the given input text.\"\n)\n\nlet response = try await session.respond(\n    to: text,\n    generating: Top3ActionEmotionResult.self\n)\n```\n\n#### From WWDC 286:19:35\n\n---\n\n## Error Handling\n\n### GenerationError Types\n\nCatch `LanguageModelSession.GenerationError` cases:\n- **`.exceededContextWindowSize`** — Context limit (4096 tokens) exceeded. Condense transcript or create new session.\n- **`.guardrailViolation`** — Content policy triggered. Show graceful message.\n- **`.unsupportedLanguageOrLocale`** — Language not supported. Check `supportedLanguages`.\n\n#### From WWDC 301:3:37, 301:7:06\n\n### Context Window Management\n\n#### Strategy 1: Fresh Session\n```swift\nvar session = LanguageModelSession()\n\ndo {\n    let response = try await session.respond(to: prompt)\n    print(response.content)\n} catch LanguageModelSession.GenerationError.exceededContextWindowSize {\n    \u002F\u002F New session, no history\n    session = LanguageModelSession()\n}\n```\n\n#### From WWDC 301:3:37\n\n#### Strategy 2: Condensed Session\n```swift\ndo {\n    let response = try await session.respond(to: prompt)\n} catch LanguageModelSession.GenerationError.exceededContextWindowSize {\n    \u002F\u002F New session with some history\n    session = newSession(previousSession: session)\n}\n\nprivate func newSession(previousSession: LanguageModelSession) -> LanguageModelSession {\n    let allEntries = previousSession.transcript.entries\n    var condensedEntries = [Transcript.Entry]()\n\n    if let firstEntry = allEntries.first {\n        condensedEntries.append(firstEntry) \u002F\u002F Instructions\n\n        if allEntries.count > 1, let lastEntry = allEntries.last {\n            condensedEntries.append(lastEntry) \u002F\u002F Recent context\n        }\n    }\n\n    let condensedTranscript = Transcript(entries: condensedEntries)\n    \u002F\u002F Note: transcript includes instructions\n    return LanguageModelSession(transcript: condensedTranscript)\n}\n```\n\n#### From WWDC 301:3:55\n\n### Fallback Architecture\n\nWhen Foundation Models is unavailable (older device, user opted out, unsupported region), provide graceful degradation:\n\n```swift\nfunc summarize(_ text: String) async throws -> String {\n    let model = SystemLanguageModel.default\n    switch model.availability {\n    case .available:\n        let session = LanguageModelSession()\n        let response = try await session.respond(to: \"Summarize: \\(text)\")\n        return response.content\n    case .unavailable:\n        \u002F\u002F Fallback: truncate with ellipsis, or call server API\n        return String(text.prefix(200)) + \"...\"\n    }\n}\n```\n\n**Architecture pattern**: Wrap Foundation Models behind a protocol so you can swap implementations:\n\n```swift\nprotocol TextSummarizer {\n    func summarize(_ text: String) async throws -> String\n}\n\nstruct OnDeviceSummarizer: TextSummarizer { \u002F* Foundation Models *\u002F }\nstruct ServerSummarizer: TextSummarizer { \u002F* Server API fallback *\u002F }\nstruct TruncationSummarizer: TextSummarizer { \u002F* Simple truncation *\u002F }\n```\n\n### Nested @Generable Troubleshooting\n\nNested `@Generable` types must each independently conform to `@Generable`:\n\n```swift\n\u002F\u002F ✅ Both types marked @Generable\n@Generable struct Itinerary {\n    var days: [DayPlan]\n}\n\n@Generable struct DayPlan {\n    var activities: [String]\n}\n\n\u002F\u002F ❌ Will fail — nested type not @Generable\n@Generable struct Itinerary {\n    var days: [DayPlan]  \u002F\u002F DayPlan must also be @Generable\n}\nstruct DayPlan { var activities: [String] }\n```\n\n**Common issue**: Arrays of non-Generable types compile but fail at runtime. Check all types in the graph.\n\n---\n\n## Availability\n\n### Checking Availability\n\n```swift\nstruct AvailabilityExample: View {\n    private let model = SystemLanguageModel.default\n\n    var body: some View {\n        switch model.availability {\n        case .available:\n            Text(\"Model is available\").foregroundStyle(.green)\n        case .unavailable(let reason):\n            Text(\"Model is unavailable\").foregroundStyle(.red)\n            Text(\"Reason: \\(reason)\")\n        }\n    }\n}\n```\n\n#### From WWDC 286:19:56\n\n### Supported Languages\n\n```swift\nlet supportedLanguages = SystemLanguageModel.default.supportedLanguages\nguard supportedLanguages.contains(Locale.current.language) else {\n    \u002F\u002F Show message\n    return\n}\n```\n\n#### From WWDC 301:7:06\n\n### Requirements\n\n**Device Requirements**:\n- Apple Intelligence-enabled device\n- iPhone 15 Pro or later\n- iPad with M1+ chip\n- Mac with Apple silicon\n\n**Region Requirements**:\n- Supported region (check Apple Intelligence availability)\n\n**User Requirements**:\n- User opted in to Apple Intelligence in Settings\n\n---\n\n## Performance & Profiling\n\n### Foundation Models Instrument\n\n**Access**: Instruments app → Foundation Models template\n\n**Metrics**:\n- Initial model load time\n- Token counts (input\u002Foutput)\n- Generation time per request\n- Latency breakdown\n- Optimization opportunities\n\n**From WWDC 286**: \"New Instruments profiling template lets you observe areas of optimization and quantify improvements.\"\n\n### Optimization: Prewarming\n\n**Problem**: First request takes 1-2s to load model\n\n**Solution**: Create session before user interaction\n\n```swift\nclass ViewModel: ObservableObject {\n    private var session: LanguageModelSession?\n\n    init() {\n        \u002F\u002F Prewarm on init\n        Task {\n            self.session = LanguageModelSession(instructions: \"...\")\n        }\n    }\n\n    func generate(prompt: String) async throws -> String {\n        let response = try await session!.respond(to: prompt)\n        return response.content\n    }\n}\n```\n\n**From WWDC 259**: \"Prewarming session before user interaction reduces initial latency.\"\n\n**Time saved**: 1-2 seconds off first generation\n\n### Optimization: includeSchemaInPrompt\n\n**Problem**: Large @Generable schemas increase token count\n\n**Solution**: Skip schema insertion for subsequent requests\n\n```swift\n\u002F\u002F First request - schema inserted\nlet first = try await session.respond(\n    to: \"Generate first person\",\n    generating: Person.self\n)\n\n\u002F\u002F Subsequent requests - skip schema\nlet second = try await session.respond(\n    to: \"Generate another person\",\n    generating: Person.self,\n    options: GenerationOptions(includeSchemaInPrompt: false)\n)\n```\n\n**From WWDC 259**: \"Setting includeSchemaInPrompt to false decreases token count and latency for subsequent requests.\"\n\n**Time saved**: 10-20% per request\n\n### Optimization: Property Order\n\nDeclare important properties first in `@Generable` structs. With streaming, perceived latency drops from 2.5s to 0.2s when title appears before full text. See [Streaming Best Practices](#best-practices) for examples.\n\n---\n\n## Feedback & Analytics\n\n`LanguageModelFeedbackAttachment` lets you report model quality issues to Apple via Feedback Assistant. Create with `input`, `output`, `sentiment` (`.positive`\u002F`.negative`), `issues` (category + explanation), and `desiredOutputExamples`. Encode as JSON and attach to a Feedback Assistant report.\n\n#### From WWDC 286:22:13\n\n---\n\n## Xcode Playgrounds\n\n### Overview\n\nXcode Playgrounds enable rapid iteration on prompts without rebuilding entire app.\n\n### Basic Usage\n\n```swift\nimport FoundationModels\nimport Playgrounds\n\n#Playground {\n    let session = LanguageModelSession()\n    let response = try await session.respond(\n        to: \"What's a good name for a trip to Japan? Respond only with a title\"\n    )\n}\n```\n\n#### From WWDC 286:2:28\n\nPlaygrounds can also access types defined in your app (like @Generable structs).\n\n---\n\n## API Quick Reference\n\n- **`LanguageModelSession`** — Main interface: `respond(to:)` → `Response\u003CString>`, `respond(to:generating:)` → `Response\u003CT>`, `streamResponse(to:generating:)` → `AsyncSequence\u003CT.PartiallyGenerated>`. Properties: `transcript`, `isResponding`.\n- **`SystemLanguageModel`** — `default.availability` (`.available`\u002F`.unavailable(reason)`), `default.supportedLanguages`, `init(useCase:)`\n- **`GenerationOptions`** — `sampling` (`.greedy`\u002F`.random`), `temperature`, `includeSchemaInPrompt`\n- **`@Generable`** — Macro enabling structured output with constrained decoding\n- **`@Guide`** — Property constraints: `description:`, `.range()`, `.count()`, `.maximumCount()`, `Regex`\n- **`Tool` protocol** — `name`, `description`, `Arguments: Generable`, `call(arguments:) → ToolOutput`\n- **`DynamicGenerationSchema`** — Runtime schema definition with `GeneratedContent` output\n- **`GenerationError`** — `.exceededContextWindowSize`, `.guardrailViolation`, `.unsupportedLanguageOrLocale`\n\n---\n\n## Migration Strategies\n\n### From Server LLMs\n\n- **Migrate when**: Privacy required, offline needed, per-request costs are a concern, and use case fits (summarization\u002Fextraction\u002Fclassification)\n- **Stay on server when**: Need world knowledge, complex reasoning, or >4096 token context\n\n### From Manual JSON Parsing\n\nUse `@Generable` with `respond(to:generating:)` instead of prompting for JSON and parsing manually. See `axiom-foundation-models` Scenario 2 for the complete migration pattern.\n\n---\n\n## Resources\n\n**WWDC**: 286, 259, 301\n\n**Skills**: axiom-foundation-models, axiom-foundation-models-diag\n\n---\n\n**Last Updated**: 2025-12-03\n**Version**: 1.0.0\n**Skill Type**: Reference\n**Content**: All WWDC 2025 code examples included\n\n",{"name":5,"license":15,"metadata":39,"description":7,"compatibility":42},{"version":40,"last-updated":41},"1.0.0","2025-12-03","iOS 26+, macOS 26+, iPadOS 26+, axiom-visionOS 26+","main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-foundation-models-ref",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":64},[54,57,60],{"tool":55,"command":56},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill axiom-foundation-models-ref",{"tool":58,"command":59},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill axiom-foundation-models-ref",{"tool":61,"command":62},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill axiom-foundation-models-ref","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-foundation-models-ref\u002FSKILL.md",true,[],[67,76,85,94,100,106],{"skillNo":68,"name":69,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":34},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[73,74,75],"model","model hierarchy","model hierarchy skill",{"skillNo":77,"name":78,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":34},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[82,83,84],"MCP","zoom","zoom mcp",{"skillNo":86,"name":87,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":34},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[91,92,93,83],"sdk","zoom apps sdk","apps",{"skillNo":95,"name":96,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":34},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[96],{"skillNo":101,"name":102,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":34},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[102],{"skillNo":107,"name":108,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":34},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[108]]