[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6E6AMQTRWN7TSDYS93XBDBZ":3,"skill-same:01M6E6AMQTRWN7TSDYS93XBDBZ":74},{"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":36,"linkOnly":37,"markdownContent":38,"markdownBody":39,"frontMatter":40,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":50,"ownerHtmlUrl":51,"ownerBlogUrl":6,"ownerDescription":52,"updatedAt":53,"install":54,"resources":67},"01M6E6AMQTRWN7TSDYS93XBDBZ","axiom-foundation-models-diag",null,"Use when debugging Foundation Models issues — context exceeded, guardrail violations, slow generation, availability problems, unsupported language, or unexpected output. Systematic diagnostics with production crisis defense.","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-diag\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35],"axiom foundation models diag","foundation","models","use","guardrail","systematic","generation","crisis","language","macos","context","defense","Production","ios","issues","debugging","diagnostics","2026-11-10 10:12:30",false,"---\nname: axiom-foundation-models-diag\ndescription: Use when debugging Foundation Models issues — context exceeded, guardrail violations, slow generation, availability problems, unsupported language, or unexpected output. Systematic diagnostics with production crisis defense.\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 Diagnostics\n\n## Overview\n\nFoundation Models issues manifest as context window exceeded errors, guardrail violations, slow generation, availability failures, and unexpected output. **Core principle** 80% of Foundation Models problems stem from misunderstanding model capabilities (3B parameter device-scale model, not world knowledge), context limits (4096 tokens), or availability requirements—not framework bugs.\n\n## Red Flags — Suspect Foundation Models Issue\n\nIf you see ANY of these, suspect a Foundation Models misunderstanding, not framework breakage:\n- Generation takes >5 seconds\n- Error: `exceededContextWindowSize`\n- Error: `guardrailViolation`\n- Error: `unsupportedLanguageOrLocale`\n- Model gives hallucinated\u002Fwrong output\n- UI freezes during generation\n- Feature works in simulator but not on device\n- ❌ **FORBIDDEN** \"Foundation Models is broken, we need a different AI\"\n  - Foundation Models powers Apple Intelligence across millions of devices\n  - Wrong output = wrong use case (world knowledge vs summarization)\n  - Do not rationalize away the issue—diagnose it\n\n**Critical distinction** Foundation Models is a **device-scale model** (3B parameters) optimized for summarization, extraction, classification—NOT world knowledge or complex reasoning. Using it for the wrong task guarantees poor results.\n\n## Mandatory First Steps\n\n**ALWAYS run these FIRST** (before changing code):\n\n```swift\n\u002F\u002F 1. Check availability\nlet availability = SystemLanguageModel.default.availability\n\nswitch availability {\ncase .available:\n    print(\"✅ Available\")\ncase .unavailable(let reason):\n    print(\"❌ Unavailable: \\(reason)\")\n    \u002F\u002F Possible reasons:\n    \u002F\u002F - Device not Apple Intelligence-capable\n    \u002F\u002F - Region not supported\n    \u002F\u002F - User not opted in\n}\n\n\u002F\u002F Record: \"Available? Yes\u002Fno, reason if not\"\n\n\u002F\u002F 2. Check supported languages\nlet supported = SystemLanguageModel.default.supportedLanguages\nprint(\"Supported languages: \\(supported)\")\nprint(\"Current locale: \\(Locale.current.language)\")\n\nif !supported.contains(Locale.current.language) {\n    print(\"⚠️ Current language not supported!\")\n}\n\n\u002F\u002F Record: \"Language supported? Yes\u002Fno\"\n\n\u002F\u002F 3. Check context usage\nlet session = LanguageModelSession()\n\u002F\u002F After some interactions:\nprint(\"Transcript entries: \\(session.transcript.entries.count)\")\n\n\u002F\u002F Rough estimation (not exact):\nlet transcriptText = session.transcript.entries\n    .map { $0.content }\n    .joined()\nprint(\"Approximate chars: \\(transcriptText.count)\")\nprint(\"Rough token estimate: \\(transcriptText.count \u002F 3)\")\n\u002F\u002F 4096 token limit ≈ 12,000 characters\n\n\u002F\u002F Record: \"Approaching context limit? Yes\u002Fno\"\n\n\u002F\u002F 4. Profile with Instruments\n\u002F\u002F Run with Foundation Models Instrument template\n\u002F\u002F Check:\n\u002F\u002F - Initial model load time\n\u002F\u002F - Token counts (input\u002Foutput)\n\u002F\u002F - Generation time per request\n\u002F\u002F - Areas for optimization\n\n\u002F\u002F Record: \"Latency profile: [numbers from Instruments]\"\n\n\u002F\u002F 5. Inspect transcript for debugging\nprint(\"Full transcript:\")\nfor entry in session.transcript.entries {\n    print(\"Entry: \\(entry.content.prefix(100))...\")\n}\n\n\u002F\u002F Record: \"Any unusual entries? Repeated content?\"\n```\n\n#### What this tells you\n- **Unavailable** → Proceed to Pattern 1a\u002F1b\u002F1c (availability issues)\n- **Context exceeded** → Proceed to Pattern 2a (token limit)\n- **Guardrail error** → Proceed to Pattern 2b (content policy)\n- **Language error** → Proceed to Pattern 2c (unsupported language)\n- **Wrong output** → Proceed to Pattern 3a\u002F3b\u002F3c (output quality)\n- **Slow generation** → Proceed to Pattern 4a\u002F4b\u002F4c\u002F4d (performance)\n- **UI frozen** → Proceed to Pattern 5a (main thread blocking)\n\n#### MANDATORY INTERPRETATION\n\nBefore changing ANY code, identify ONE of these:\n\n1. If `availability = .unavailable` → Device\u002Fregion\u002Fopt-in issue (not code bug)\n2. If error is `exceededContextWindowSize` → Too many tokens (condense transcript)\n3. If error is `guardrailViolation` → Content policy triggered (not model failure)\n4. If error is `unsupportedLanguageOrLocale` → Language not supported (check supported list)\n5. If output is hallucinated → Wrong use case (world knowledge vs extraction)\n6. If generation >5 seconds → Not streaming or need optimization\n7. If UI frozen → Calling on main thread (use Task {})\n\n#### If diagnostics are contradictory or unclear\n- STOP. Do NOT proceed to patterns yet\n- Add detailed logging to every `respond()` call\n- Run with Instruments Foundation Models template\n- Establish baseline: what's actually happening vs what you assumed\n\n## Decision Tree\n\n```\nFoundation Models problem?\n│\n├─ Won't start?\n│  ├─ .unavailable → Availability issue\n│  │  ├─ Device not capable? → Pattern 1a (device requirement)\n│  │  ├─ Region restriction? → Pattern 1b (regional availability)\n│  │  └─ User not opted in? → Pattern 1c (Settings check)\n│  │\n├─ Generation fails?\n│  ├─ exceededContextWindowSize → Context limit\n│  │  └─ Long conversation or verbose prompts? → Pattern 2a (condense)\n│  │\n│  ├─ guardrailViolation → Content policy\n│  │  └─ Sensitive or inappropriate content? → Pattern 2b (handle gracefully)\n│  │\n│  ├─ unsupportedLanguageOrLocale → Language issue\n│  │  └─ Non-English or unsupported language? → Pattern 2c (language check)\n│  │\n│  └─ Other error → General error handling\n│     └─ Unknown error type? → Pattern 2d (catch-all)\n│\n├─ Output wrong?\n│  ├─ Hallucinated facts → Wrong model use\n│  │  └─ Asking for world knowledge? → Pattern 3a (use case mismatch)\n│  │\n│  ├─ Wrong structure → Parsing issue\n│  │  └─ Manual JSON parsing? → Pattern 3b (use @Generable)\n│  │\n│  ├─ Missing data → Tool needed\n│  │  └─ Need external information? → Pattern 3c (tool calling)\n│  │\n│  └─ Inconsistent output → Sampling issue\n│     └─ Different results each time? → Pattern 3d (temperature\u002Fgreedy)\n│\n├─ Too slow?\n│  ├─ Initial delay (1-2s) → Model loading\n│  │  └─ First request slow? → Pattern 4a (prewarm)\n│  │\n│  ├─ Long wait for results → Not streaming\n│  │  └─ User waits 3-5s? → Pattern 4b (streaming)\n│  │\n│  ├─ Verbose schema → Token overhead\n│  │  └─ Large @Generable type? → Pattern 4c (includeSchemaInPrompt)\n│  │\n│  └─ Complex prompt → Too much processing\n│     └─ Massive prompt or task? → Pattern 4d (break down)\n│\n└─ UI frozen?\n   └─ Main thread blocked → Async issue\n      └─ App unresponsive during generation? → Pattern 5a (Task {})\n```\n\n## Diagnostic Patterns\n\n### Pattern 1a: Device Not Capable\n\n**Symptom**:\n- `SystemLanguageModel.default.availability = .unavailable`\n- Reason: Device not Apple Intelligence-capable\n\n**Diagnosis**:\n```swift\nlet availability = SystemLanguageModel.default.availability\n\nswitch availability {\ncase .available:\n    print(\"✅ Available\")\ncase .unavailable(let reason):\n    print(\"❌ Reason: \\(reason)\")\n    \u002F\u002F Check if device-related\n}\n```\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - No availability UI\nlet session = LanguageModelSession() \u002F\u002F Crashes on unsupported devices\n\n\u002F\u002F ✅ GOOD - Graceful UI\nstruct AIFeatureView: View {\n    @State private var availability = SystemLanguageModel.default.availability\n\n    var body: some View {\n        switch availability {\n        case .available:\n            AIContentView()\n        case .unavailable:\n            VStack {\n                Image(systemName: \"cpu\")\n                Text(\"AI features require Apple Intelligence\")\n                    .font(.headline)\n                Text(\"Available on iPhone 15 Pro and later\")\n                    .font(.caption)\n                    .foregroundColor(.secondary)\n            }\n        }\n    }\n}\n```\n\n**Time cost**: 5-10 minutes to add UI\n\n---\n\n### Pattern 1b: Regional Availability\n\n**Symptom**:\n- Feature works for some users, not others\n- .unavailable due to region restrictions\n\n**Diagnosis**:\nFoundation Models requires:\n- Supported region (e.g., US, UK, Australia initially)\n- May expand over time\n\n**Fix**:\n```swift\n\u002F\u002F ✅ GOOD - Clear messaging\nswitch SystemLanguageModel.default.availability {\ncase .available:\n    \u002F\u002F proceed\ncase .unavailable(let reason):\n    \u002F\u002F Show region-specific message\n    Text(\"AI features not yet available in your region\")\n    Text(\"Check Settings → Apple Intelligence for availability\")\n}\n```\n\n**Time cost**: 5 minutes\n\n---\n\n### Pattern 1c: User Not Opted In\n\n**Symptom**:\n- Device capable, region supported\n- Still .unavailable\n\n**Diagnosis**:\nUser must opt in to Apple Intelligence in Settings\n\n**Fix**:\n```swift\n\u002F\u002F ✅ GOOD - Direct user to settings\nswitch SystemLanguageModel.default.availability {\ncase .available:\n    \u002F\u002F proceed\ncase .unavailable:\n    VStack {\n        Text(\"Enable Apple Intelligence\")\n        Text(\"Settings → Apple Intelligence → Enable\")\n        Button(\"Open Settings\") {\n            if let url = URL(string: UIApplication.openSettingsURLString) {\n                UIApplication.shared.open(url)\n            }\n        }\n    }\n}\n```\n\n**Time cost**: 10 minutes\n\n---\n\n### Pattern 2a: Context Window Exceeded\n\n**Symptom**:\n```\nError: LanguageModelSession.GenerationError.exceededContextWindowSize\n```\n\n**Diagnosis**:\n- 4096 token limit (input + output)\n- Long conversations accumulate tokens\n- Verbose prompts eat into limit\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - Unhandled error\nlet response = try await session.respond(to: prompt)\n\u002F\u002F Crashes after ~10-15 turns\n\n\u002F\u002F ✅ GOOD - Condense transcript\nvar session = LanguageModelSession()\n\ndo {\n    let response = try await session.respond(to: prompt)\n} catch LanguageModelSession.GenerationError.exceededContextWindowSize {\n    \u002F\u002F Condense and continue\n    session = condensedSession(from: session)\n    let response = try await session.respond(to: prompt)\n}\n\nfunc condensedSession(from previous: LanguageModelSession) -> LanguageModelSession {\n    let entries = previous.transcript.entries\n\n    guard entries.count > 2 else {\n        return LanguageModelSession(transcript: previous.transcript)\n    }\n\n    \u002F\u002F Keep: first (instructions) + last (recent context)\n    var condensed = [entries.first!, entries.last!]\n\n    let transcript = Transcript(entries: condensed)\n    return LanguageModelSession(transcript: transcript)\n}\n```\n\n**Time cost**: 15-20 minutes to implement condensing\n\n---\n\n### Pattern 2b: Guardrail Violation\n\n**Symptom**:\n```\nError: LanguageModelSession.GenerationError.guardrailViolation\n```\n\n**Diagnosis**:\n- User input triggered content policy\n- Violence, hate speech, illegal activities\n- Model refuses to generate\n\n**Fix**:\n```swift\n\u002F\u002F ✅ GOOD - Graceful handling\ndo {\n    let response = try await session.respond(to: userInput)\n    print(response.content)\n} catch LanguageModelSession.GenerationError.guardrailViolation {\n    \u002F\u002F Show user-friendly message\n    print(\"I can't help with that request\")\n    \u002F\u002F Log for review (but don't show user input to avoid storing harmful content)\n}\n```\n\n**Time cost**: 5-10 minutes\n\n---\n\n### Pattern 2c: Unsupported Language\n\n**Symptom**:\n```\nError: LanguageModelSession.GenerationError.unsupportedLanguageOrLocale\n```\n\n**Diagnosis**:\nUser input in language model doesn't support\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - No language check\nlet response = try await session.respond(to: userInput)\n\u002F\u002F Crashes if unsupported language\n\n\u002F\u002F ✅ GOOD - Check first\nlet supported = SystemLanguageModel.default.supportedLanguages\n\nguard supported.contains(Locale.current.language) else {\n    \u002F\u002F Show disclaimer\n    print(\"Language not supported. Currently supports: \\(supported)\")\n    return\n}\n\n\u002F\u002F Also handle errors\ndo {\n    let response = try await session.respond(to: userInput)\n} catch LanguageModelSession.GenerationError.unsupportedLanguageOrLocale {\n    print(\"Please use English or another supported language\")\n}\n```\n\n**Time cost**: 10 minutes\n\n---\n\n### Pattern 2d: General Error Handling\n\n**Symptom**:\nUnknown error types\n\n**Fix**:\n```swift\n\u002F\u002F ✅ GOOD - Comprehensive error handling\ndo {\n    let response = try await session.respond(to: prompt)\n    print(response.content)\n} catch LanguageModelSession.GenerationError.exceededContextWindowSize {\n    \u002F\u002F Handle context overflow\n    session = condensedSession(from: session)\n} catch LanguageModelSession.GenerationError.guardrailViolation {\n    \u002F\u002F Handle content policy\n    showMessage(\"Cannot generate that content\")\n} catch LanguageModelSession.GenerationError.unsupportedLanguageOrLocale {\n    \u002F\u002F Handle language issue\n    showMessage(\"Language not supported\")\n} catch {\n    \u002F\u002F Catch-all for unexpected errors\n    print(\"Unexpected error: \\(error)\")\n    showMessage(\"Something went wrong. Please try again.\")\n}\n```\n\n**Time cost**: 10-15 minutes\n\n---\n\n### Pattern 3a: Hallucinated Output (Wrong Use Case)\n\n**Symptom**:\n- Model gives factually incorrect answers\n- Makes up information\n\n**Diagnosis**:\nUsing model for world knowledge (wrong use case)\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - Wrong use case\nlet prompt = \"Who is the president of France?\"\nlet response = try await session.respond(to: prompt)\n\u002F\u002F Will hallucinate or give outdated info\n\n\u002F\u002F ✅ GOOD - Use server LLM for world knowledge\n\u002F\u002F Foundation Models is for:\n\u002F\u002F - Summarization\n\u002F\u002F - Extraction\n\u002F\u002F - Classification\n\u002F\u002F - Content generation\n\n\u002F\u002F OR: Use Tool calling with external data source\nstruct GetFactTool: Tool {\n    let name = \"getFact\"\n    let description = \"Fetch factual information from verified source\"\n\n    @Generable\n    struct Arguments {\n        let query: String\n    }\n\n    func call(arguments: Arguments) async throws -> ToolOutput {\n        \u002F\u002F Fetch from Wikipedia API, news API, etc.\n        let fact = await fetchFactFromAPI(arguments.query)\n        return ToolOutput(fact)\n    }\n}\n```\n\n**Time cost**: 20-30 minutes to implement tool OR switch to appropriate AI\n\n---\n\n### Pattern 3b: Wrong Structure (Not Using @Generable)\n\n**Symptom**:\n- Parsing errors\n- Invalid JSON\n- Wrong keys\n\n**Diagnosis**:\nManual JSON parsing instead of @Generable\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - Manual parsing\nlet prompt = \"Generate person as JSON\"\nlet response = try await session.respond(to: prompt)\nlet data = response.content.data(using: .utf8)!\nlet person = try JSONDecoder().decode(Person.self, from: data) \u002F\u002F CRASHES\n\n\u002F\u002F ✅ GOOD - @Generable\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\u002F\u002F response.content is type-safe Person, guaranteed structure\n```\n\n**Time cost**: 10 minutes to convert to @Generable\n\n---\n\n### Pattern 3c: Missing Data (Need Tool)\n\n**Symptom**:\n- Model doesn't have required information\n- Output is vague or generic\n\n**Diagnosis**:\nNeed external data (weather, locations, contacts)\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - No external data\nlet response = try await session.respond(\n    to: \"What's the weather in Tokyo?\"\n)\n\u002F\u002F Will make up weather data\n\n\u002F\u002F ✅ GOOD - Tool calling\nimport WeatherKit\n\nstruct GetWeatherTool: Tool {\n    let name = \"getWeather\"\n    let description = \"Get current weather for a city\"\n\n    @Generable\n    struct Arguments {\n        let city: String\n    }\n\n    func call(arguments: Arguments) async throws -> ToolOutput {\n        \u002F\u002F Fetch real weather\n        let weather = await WeatherService.shared.weather(for: arguments.city)\n        return ToolOutput(\"Temperature: \\(weather.temperature)°F\")\n    }\n}\n\nlet session = LanguageModelSession(tools: [GetWeatherTool()])\nlet response = try await session.respond(to: \"What's the weather in Tokyo?\")\n\u002F\u002F Uses real weather data\n```\n\n**Time cost**: 20-30 minutes to implement tool\n\n---\n\n### Pattern 3d: Inconsistent Output (Sampling)\n\n**Symptom**:\n- Different output every time for same prompt\n- Need consistent results for testing\n\n**Diagnosis**:\nRandom sampling (default behavior)\n\n**Fix**:\n```swift\n\u002F\u002F Default: Random sampling\nlet response1 = try await session.respond(to: \"Write a haiku\")\nlet response2 = try await session.respond(to: \"Write a haiku\")\n\u002F\u002F Different every time\n\n\u002F\u002F ✅ For deterministic output (testing\u002Fdemos)\nlet response = try await session.respond(\n    to: \"Write a haiku\",\n    options: GenerationOptions(sampling: .greedy)\n)\n\u002F\u002F Same output for same prompt (given same model version)\n\n\u002F\u002F ✅ For low variance\nlet response = try await session.respond(\n    to: \"Classify this article\",\n    options: GenerationOptions(temperature: 0.5)\n)\n\u002F\u002F Slightly varied but focused\n\n\u002F\u002F ✅ For high creativity\nlet response = try await session.respond(\n    to: \"Write a creative story\",\n    options: GenerationOptions(temperature: 2.0)\n)\n\u002F\u002F Very diverse output\n```\n\n**Time cost**: 2-5 minutes\n\n---\n\n### Pattern 4a: Initial Latency (Prewarm)\n\n**Symptom**:\n- First generation takes 1-2 seconds to start\n- Subsequent requests faster\n\n**Diagnosis**:\nModel loading time\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - Load on user interaction\nButton(\"Generate\") {\n    Task {\n        let session = LanguageModelSession() \u002F\u002F 1-2s delay here\n        let response = try await session.respond(to: prompt)\n    }\n}\n\n\u002F\u002F ✅ GOOD - Prewarm on init\nclass ViewModel: ObservableObject {\n    private var session: LanguageModelSession?\n\n    init() {\n        \u002F\u002F Prewarm before user interaction\n        Task {\n            self.session = LanguageModelSession(instructions: \"...\")\n        }\n    }\n\n    func generate(prompt: String) async throws -> String {\n        guard let session = session else {\n            \u002F\u002F Fallback if not ready\n            self.session = LanguageModelSession()\n            return try await self.session!.respond(to: prompt).content\n        }\n        return try await session.respond(to: prompt).content\n    }\n}\n```\n\n**Time cost**: 10 minutes\n**Latency saved**: 1-2 seconds on first request\n\n---\n\n### Pattern 4b: Long Generation (Streaming)\n\n**Symptom**:\n- User waits 3-5 seconds seeing nothing\n- Then entire result appears at once\n\n**Diagnosis**:\nNot streaming long generations\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - No streaming\nlet response = try await session.respond(\n    to: \"Generate 5-day itinerary\",\n    generating: Itinerary.self\n)\n\u002F\u002F User waits 4 seconds seeing nothing\n\n\u002F\u002F ✅ GOOD - Streaming\n@Generable\nstruct Itinerary {\n    var destination: String\n    var days: [DayPlan]\n}\n\nlet stream = session.streamResponse(\n    to: \"Generate 5-day itinerary to Tokyo\",\n    generating: Itinerary.self\n)\n\nfor try await partial in stream {\n    \u002F\u002F Update UI incrementally\n    self.itinerary = partial\n}\n\u002F\u002F User sees destination in 0.5s, then days progressively\n```\n\n**Time cost**: 15-20 minutes\n**Perceived latency**: 0.5s vs 4s\n\n---\n\n### Pattern 4c: Large Schema Overhead\n\n**Symptom**:\n- Subsequent requests with same @Generable type slow\n\n**Diagnosis**:\nSchema re-inserted into prompt every time\n\n**Fix**:\n```swift\n\u002F\u002F First request - schema inserted automatically\nlet first = try await session.respond(\n    to: \"Generate first person\",\n    generating: Person.self\n)\n\n\u002F\u002F ✅ Subsequent requests - skip schema insertion\nlet second = try await session.respond(\n    to: \"Generate another person\",\n    generating: Person.self,\n    options: GenerationOptions(includeSchemaInPrompt: false)\n)\n```\n\n**Time cost**: 2 minutes\n**Latency saved**: 10-20% per request\n\n---\n\n### Pattern 4d: Complex Prompt (Break Down)\n\n**Symptom**:\n- Generation takes >5 seconds\n- Poor quality results\n\n**Diagnosis**:\nPrompt too complex for single generation\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - One massive prompt\nlet prompt = \"\"\"\n    Generate complete 7-day itinerary with hotels, restaurants,\n    activities, transportation, budget, tips, and local customs\n    \"\"\"\n\u002F\u002F 5-8 seconds, poor quality\n\n\u002F\u002F ✅ GOOD - Break into steps\nlet overview = try await session.respond(\n    to: \"Generate high-level 7-day plan for Tokyo\"\n)\n\nvar dayDetails: [DayPlan] = []\nfor day in 1...7 {\n    let detail = try await session.respond(\n        to: \"Detail activities and restaurants for day \\(day) in Tokyo\",\n        generating: DayPlan.self\n    )\n    dayDetails.append(detail.content)\n}\n\u002F\u002F Total time similar, but better quality and progressive results\n```\n\n**Time cost**: 20-30 minutes\n**Quality improvement**: Significantly better\n\n---\n\n### Pattern 5a: UI Frozen (Main Thread Blocking)\n\n**Symptom**:\n- App unresponsive during generation\n- UI freezes for seconds\n\n**Diagnosis**:\nCalling `respond()` on main thread synchronously\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - Blocking main thread\nButton(\"Generate\") {\n    let response = try await session.respond(to: prompt)\n    \u002F\u002F UI frozen for 2-5 seconds!\n}\n\n\u002F\u002F ✅ GOOD - Async task\nButton(\"Generate\") {\n    Task {\n        do {\n            let response = try await session.respond(to: prompt)\n            \u002F\u002F Update UI on main thread\n            await MainActor.run {\n                self.result = response.content\n            }\n        } catch {\n            print(\"Error: \\(error)\")\n        }\n    }\n}\n```\n\n**Time cost**: 5 minutes\n**UX improvement**: Massive (no frozen UI)\n\n---\n\n## Production Crisis Scenario\n\n### Context\n\n**Situation**: You just launched an AI-powered feature using Foundation Models. Within 2 hours:\n- 20% of users report \"AI feature doesn't work\"\n- App Store reviews dropping: \"New AI broken\"\n- VP of Product emailing: \"What's the ETA on fix?\"\n- Engineering manager: \"Should we roll back?\"\n\n**Pressure Signals**:\n- ? **Revenue impact**: Feature is key selling point for new app version\n- ⏰ **Time pressure**: \"Fix it NOW\"\n- ? **Executive visibility**: VP watching\n- ? **Public reputation**: App Store reviews visible to all\n\n### Rationalization Traps\n\n**DO NOT** fall into these traps:\n\n1. **\"Disable the feature\"**\n   - Loses product differentiation\n   - Admits defeat\n   - Doesn't learn what went wrong\n\n2. **\"Roll back to previous version\"**\n   - Loses weeks of work\n   - Doesn't fix root cause\n   - Users still angry\n\n3. **\"It works for me\"**\n   - Simulator ≠ real devices\n   - Your device ≠ all devices\n   - Ignores real problem\n\n4. **\"Switch to ChatGPT API\"**\n   - Violates privacy\n   - Expensive at scale\n   - Doesn't address availability issue\n\n### MANDATORY Protocol\n\n#### Phase 1: Identify (5 minutes)\n\n```swift\n\u002F\u002F Check error distribution\n\u002F\u002F What percentage seeing what error?\n\n\u002F\u002F Run this on test devices:\nlet availability = SystemLanguageModel.default.availability\n\nswitch availability {\ncase .available:\n    print(\"✅ Available\")\ncase .unavailable(let reason):\n    print(\"❌ Unavailable: \\(reason)\")\n}\n\n\u002F\u002F Hypothesis:\n\u002F\u002F - If 20% unavailable → Availability issue (device\u002Fregion\u002Fopt-in)\n\u002F\u002F - If 20% getting errors → Code bug\n\u002F\u002F - If 20% seeing wrong results → Use case mismatch\n```\n\n**Results**: Discover that 20% of users have devices without Apple Intelligence support.\n\n---\n\n#### Phase 2: Confirm (5 minutes)\n\n```swift\n\u002F\u002F Check which devices affected\n\u002F\u002F iPhone 15 Pro+ = ✅ Available\n\u002F\u002F iPhone 15 = ❌ Unavailable\n\u002F\u002F iPhone 14 = ❌ Unavailable\n\n\u002F\u002F Conclusion: Availability issue, not code bug\n```\n\n**Root cause**: Feature assumes all users have Apple Intelligence. 20% don't.\n\n---\n\n#### Phase 3: Device Requirements (5 minutes)\n\nVerify:\n- Apple Intelligence requires iPhone 15 Pro or later\n- Or iPad with M1+ chip\n- Or Mac with Apple silicon\n\n#### 20% of user base = older devices\n\n---\n\n#### Phase 4: Implement Fix (15 minutes)\n\n```swift\n\u002F\u002F ✅ Add availability check + graceful UI\nstruct AIFeatureView: View {\n    @State private var availability = SystemLanguageModel.default.availability\n\n    var body: some View {\n        switch availability {\n        case .available:\n            \u002F\u002F Show AI feature\n            AIContentView()\n\n        case .unavailable:\n            \u002F\u002F Graceful fallback\n            VStack {\n                Image(systemName: \"sparkles\")\n                    .font(.largeTitle)\n                    .foregroundColor(.secondary)\n\n                Text(\"AI-Powered Features\")\n                    .font(.headline)\n\n                Text(\"Available on iPhone 15 Pro and later\")\n                    .font(.subheadline)\n                    .foregroundColor(.secondary)\n                    .multilineTextAlignment(.center)\n\n                \u002F\u002F Offer alternative\n                Button(\"Use Standard Mode\") {\n                    \u002F\u002F Show non-AI fallback\n                }\n            }\n        }\n    }\n}\n```\n\n---\n\n#### Phase 5: Deploy (20 minutes)\n\n1. Test on multiple devices (15 min)\n   - iPhone 15 Pro: ✅ Shows AI feature\n   - iPhone 14: ✅ Shows graceful message\n   - iPad Pro M1: ✅ Shows AI feature\n\n2. Submit hotfix build (5 min)\n\n---\n\n### Communication Template\n\n**To VP of Product (immediate)**:\n```\nRoot cause identified:\n\nThe AI feature requires Apple Intelligence (iPhone 15 Pro+).\n20% of our users have older devices. We didn't check availability.\n\nFix: Added availability check with graceful fallback UI.\n\nTimeline:\n- Hotfix ready: Now\n- TestFlight: 10 minutes\n- App Store submission: 30 minutes\n- Review: 24-48 hours (requesting expedited)\n\nImpact mitigation:\n- 80% of users see working AI feature\n- 20% see clear message + standard mode fallback\n- No functionality lost, just graceful degradation\n```\n\n**To Engineering Team**:\n```\nPost-mortem items:\n1. Add availability check to launch checklist\n2. Test on non-Apple-Intelligence devices\n3. Document device requirements clearly\n4. Add analytics for availability status\n```\n\n### Time Saved\n\n- **Panic path (disable\u002Frollback)**: 2 hours of meetings + lost work\n- **Proper diagnosis**: 45 minutes root cause → fix → deploy\n\n### What We Learned\n\n1. **Always check availability** before creating session\n2. **Test on real devices** across device generations\n3. **Graceful degradation** better than feature removal\n4. **Clear messaging** to users about requirements\n\n---\n\n## Quick Reference Table\n\n| Symptom | Cause | Check | Pattern | Time |\n|---------|-------|-------|---------|------|\n| Won't start | .unavailable | SystemLanguageModel.default.availability | 1a | 5 min |\n| Region issue | Not supported region | Check supported regions | 1b | 5 min |\n| Not opted in | Apple Intelligence disabled | Settings check | 1c | 10 min |\n| Context exceeded | >4096 tokens | Transcript length | 2a | 15 min |\n| Guardrail error | Content policy | User input type | 2b | 10 min |\n| Language error | Unsupported language | supportedLanguages | 2c | 10 min |\n| Hallucinated output | Wrong use case | Task type check | 3a | 20 min |\n| Wrong structure | No @Generable | Manual parsing? | 3b | 10 min |\n| Missing data | No tool | External data needed? | 3c | 30 min |\n| Inconsistent | Random sampling | Need deterministic? | 3d | 5 min |\n| Initial delay | Model loading | First request slow? | 4a | 10 min |\n| Long wait | No streaming | >1s generation? | 4b | 20 min |\n| Schema overhead | Re-inserting schema | Subsequent requests? | 4c | 2 min |\n| Complex prompt | Too much at once | >5s generation? | 4d | 30 min |\n| UI frozen | Main thread | Thread check | 5a | 5 min |\n\n---\n\n## Cross-References\n\n**Related Axiom Skills**:\n- `axiom-foundation-models` — Discipline skill for anti-patterns, proper usage patterns, pressure scenarios\n- `axiom-foundation-models-ref` — Complete API reference with all WWDC 2025 code examples\n\n**Apple Resources**:\n- Foundation Models Framework Documentation\n- WWDC 2025-286: Meet the Foundation Models framework\n- WWDC 2025-301: Deep dive into the Foundation Models framework\n- Instruments Foundation Models Template\n\n---\n\n**Last Updated**: 2025-12-03\n**Version**: 1.0.0\n**Skill Type**: Diagnostic\n\n","# Foundation Models Diagnostics\n\n## Overview\n\nFoundation Models issues manifest as context window exceeded errors, guardrail violations, slow generation, availability failures, and unexpected output. **Core principle** 80% of Foundation Models problems stem from misunderstanding model capabilities (3B parameter device-scale model, not world knowledge), context limits (4096 tokens), or availability requirements—not framework bugs.\n\n## Red Flags — Suspect Foundation Models Issue\n\nIf you see ANY of these, suspect a Foundation Models misunderstanding, not framework breakage:\n- Generation takes >5 seconds\n- Error: `exceededContextWindowSize`\n- Error: `guardrailViolation`\n- Error: `unsupportedLanguageOrLocale`\n- Model gives hallucinated\u002Fwrong output\n- UI freezes during generation\n- Feature works in simulator but not on device\n- ❌ **FORBIDDEN** \"Foundation Models is broken, we need a different AI\"\n  - Foundation Models powers Apple Intelligence across millions of devices\n  - Wrong output = wrong use case (world knowledge vs summarization)\n  - Do not rationalize away the issue—diagnose it\n\n**Critical distinction** Foundation Models is a **device-scale model** (3B parameters) optimized for summarization, extraction, classification—NOT world knowledge or complex reasoning. Using it for the wrong task guarantees poor results.\n\n## Mandatory First Steps\n\n**ALWAYS run these FIRST** (before changing code):\n\n```swift\n\u002F\u002F 1. Check availability\nlet availability = SystemLanguageModel.default.availability\n\nswitch availability {\ncase .available:\n    print(\"✅ Available\")\ncase .unavailable(let reason):\n    print(\"❌ Unavailable: \\(reason)\")\n    \u002F\u002F Possible reasons:\n    \u002F\u002F - Device not Apple Intelligence-capable\n    \u002F\u002F - Region not supported\n    \u002F\u002F - User not opted in\n}\n\n\u002F\u002F Record: \"Available? Yes\u002Fno, reason if not\"\n\n\u002F\u002F 2. Check supported languages\nlet supported = SystemLanguageModel.default.supportedLanguages\nprint(\"Supported languages: \\(supported)\")\nprint(\"Current locale: \\(Locale.current.language)\")\n\nif !supported.contains(Locale.current.language) {\n    print(\"⚠️ Current language not supported!\")\n}\n\n\u002F\u002F Record: \"Language supported? Yes\u002Fno\"\n\n\u002F\u002F 3. Check context usage\nlet session = LanguageModelSession()\n\u002F\u002F After some interactions:\nprint(\"Transcript entries: \\(session.transcript.entries.count)\")\n\n\u002F\u002F Rough estimation (not exact):\nlet transcriptText = session.transcript.entries\n    .map { $0.content }\n    .joined()\nprint(\"Approximate chars: \\(transcriptText.count)\")\nprint(\"Rough token estimate: \\(transcriptText.count \u002F 3)\")\n\u002F\u002F 4096 token limit ≈ 12,000 characters\n\n\u002F\u002F Record: \"Approaching context limit? Yes\u002Fno\"\n\n\u002F\u002F 4. Profile with Instruments\n\u002F\u002F Run with Foundation Models Instrument template\n\u002F\u002F Check:\n\u002F\u002F - Initial model load time\n\u002F\u002F - Token counts (input\u002Foutput)\n\u002F\u002F - Generation time per request\n\u002F\u002F - Areas for optimization\n\n\u002F\u002F Record: \"Latency profile: [numbers from Instruments]\"\n\n\u002F\u002F 5. Inspect transcript for debugging\nprint(\"Full transcript:\")\nfor entry in session.transcript.entries {\n    print(\"Entry: \\(entry.content.prefix(100))...\")\n}\n\n\u002F\u002F Record: \"Any unusual entries? Repeated content?\"\n```\n\n#### What this tells you\n- **Unavailable** → Proceed to Pattern 1a\u002F1b\u002F1c (availability issues)\n- **Context exceeded** → Proceed to Pattern 2a (token limit)\n- **Guardrail error** → Proceed to Pattern 2b (content policy)\n- **Language error** → Proceed to Pattern 2c (unsupported language)\n- **Wrong output** → Proceed to Pattern 3a\u002F3b\u002F3c (output quality)\n- **Slow generation** → Proceed to Pattern 4a\u002F4b\u002F4c\u002F4d (performance)\n- **UI frozen** → Proceed to Pattern 5a (main thread blocking)\n\n#### MANDATORY INTERPRETATION\n\nBefore changing ANY code, identify ONE of these:\n\n1. If `availability = .unavailable` → Device\u002Fregion\u002Fopt-in issue (not code bug)\n2. If error is `exceededContextWindowSize` → Too many tokens (condense transcript)\n3. If error is `guardrailViolation` → Content policy triggered (not model failure)\n4. If error is `unsupportedLanguageOrLocale` → Language not supported (check supported list)\n5. If output is hallucinated → Wrong use case (world knowledge vs extraction)\n6. If generation >5 seconds → Not streaming or need optimization\n7. If UI frozen → Calling on main thread (use Task {})\n\n#### If diagnostics are contradictory or unclear\n- STOP. Do NOT proceed to patterns yet\n- Add detailed logging to every `respond()` call\n- Run with Instruments Foundation Models template\n- Establish baseline: what's actually happening vs what you assumed\n\n## Decision Tree\n\n```\nFoundation Models problem?\n│\n├─ Won't start?\n│  ├─ .unavailable → Availability issue\n│  │  ├─ Device not capable? → Pattern 1a (device requirement)\n│  │  ├─ Region restriction? → Pattern 1b (regional availability)\n│  │  └─ User not opted in? → Pattern 1c (Settings check)\n│  │\n├─ Generation fails?\n│  ├─ exceededContextWindowSize → Context limit\n│  │  └─ Long conversation or verbose prompts? → Pattern 2a (condense)\n│  │\n│  ├─ guardrailViolation → Content policy\n│  │  └─ Sensitive or inappropriate content? → Pattern 2b (handle gracefully)\n│  │\n│  ├─ unsupportedLanguageOrLocale → Language issue\n│  │  └─ Non-English or unsupported language? → Pattern 2c (language check)\n│  │\n│  └─ Other error → General error handling\n│     └─ Unknown error type? → Pattern 2d (catch-all)\n│\n├─ Output wrong?\n│  ├─ Hallucinated facts → Wrong model use\n│  │  └─ Asking for world knowledge? → Pattern 3a (use case mismatch)\n│  │\n│  ├─ Wrong structure → Parsing issue\n│  │  └─ Manual JSON parsing? → Pattern 3b (use @Generable)\n│  │\n│  ├─ Missing data → Tool needed\n│  │  └─ Need external information? → Pattern 3c (tool calling)\n│  │\n│  └─ Inconsistent output → Sampling issue\n│     └─ Different results each time? → Pattern 3d (temperature\u002Fgreedy)\n│\n├─ Too slow?\n│  ├─ Initial delay (1-2s) → Model loading\n│  │  └─ First request slow? → Pattern 4a (prewarm)\n│  │\n│  ├─ Long wait for results → Not streaming\n│  │  └─ User waits 3-5s? → Pattern 4b (streaming)\n│  │\n│  ├─ Verbose schema → Token overhead\n│  │  └─ Large @Generable type? → Pattern 4c (includeSchemaInPrompt)\n│  │\n│  └─ Complex prompt → Too much processing\n│     └─ Massive prompt or task? → Pattern 4d (break down)\n│\n└─ UI frozen?\n   └─ Main thread blocked → Async issue\n      └─ App unresponsive during generation? → Pattern 5a (Task {})\n```\n\n## Diagnostic Patterns\n\n### Pattern 1a: Device Not Capable\n\n**Symptom**:\n- `SystemLanguageModel.default.availability = .unavailable`\n- Reason: Device not Apple Intelligence-capable\n\n**Diagnosis**:\n```swift\nlet availability = SystemLanguageModel.default.availability\n\nswitch availability {\ncase .available:\n    print(\"✅ Available\")\ncase .unavailable(let reason):\n    print(\"❌ Reason: \\(reason)\")\n    \u002F\u002F Check if device-related\n}\n```\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - No availability UI\nlet session = LanguageModelSession() \u002F\u002F Crashes on unsupported devices\n\n\u002F\u002F ✅ GOOD - Graceful UI\nstruct AIFeatureView: View {\n    @State private var availability = SystemLanguageModel.default.availability\n\n    var body: some View {\n        switch availability {\n        case .available:\n            AIContentView()\n        case .unavailable:\n            VStack {\n                Image(systemName: \"cpu\")\n                Text(\"AI features require Apple Intelligence\")\n                    .font(.headline)\n                Text(\"Available on iPhone 15 Pro and later\")\n                    .font(.caption)\n                    .foregroundColor(.secondary)\n            }\n        }\n    }\n}\n```\n\n**Time cost**: 5-10 minutes to add UI\n\n---\n\n### Pattern 1b: Regional Availability\n\n**Symptom**:\n- Feature works for some users, not others\n- .unavailable due to region restrictions\n\n**Diagnosis**:\nFoundation Models requires:\n- Supported region (e.g., US, UK, Australia initially)\n- May expand over time\n\n**Fix**:\n```swift\n\u002F\u002F ✅ GOOD - Clear messaging\nswitch SystemLanguageModel.default.availability {\ncase .available:\n    \u002F\u002F proceed\ncase .unavailable(let reason):\n    \u002F\u002F Show region-specific message\n    Text(\"AI features not yet available in your region\")\n    Text(\"Check Settings → Apple Intelligence for availability\")\n}\n```\n\n**Time cost**: 5 minutes\n\n---\n\n### Pattern 1c: User Not Opted In\n\n**Symptom**:\n- Device capable, region supported\n- Still .unavailable\n\n**Diagnosis**:\nUser must opt in to Apple Intelligence in Settings\n\n**Fix**:\n```swift\n\u002F\u002F ✅ GOOD - Direct user to settings\nswitch SystemLanguageModel.default.availability {\ncase .available:\n    \u002F\u002F proceed\ncase .unavailable:\n    VStack {\n        Text(\"Enable Apple Intelligence\")\n        Text(\"Settings → Apple Intelligence → Enable\")\n        Button(\"Open Settings\") {\n            if let url = URL(string: UIApplication.openSettingsURLString) {\n                UIApplication.shared.open(url)\n            }\n        }\n    }\n}\n```\n\n**Time cost**: 10 minutes\n\n---\n\n### Pattern 2a: Context Window Exceeded\n\n**Symptom**:\n```\nError: LanguageModelSession.GenerationError.exceededContextWindowSize\n```\n\n**Diagnosis**:\n- 4096 token limit (input + output)\n- Long conversations accumulate tokens\n- Verbose prompts eat into limit\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - Unhandled error\nlet response = try await session.respond(to: prompt)\n\u002F\u002F Crashes after ~10-15 turns\n\n\u002F\u002F ✅ GOOD - Condense transcript\nvar session = LanguageModelSession()\n\ndo {\n    let response = try await session.respond(to: prompt)\n} catch LanguageModelSession.GenerationError.exceededContextWindowSize {\n    \u002F\u002F Condense and continue\n    session = condensedSession(from: session)\n    let response = try await session.respond(to: prompt)\n}\n\nfunc condensedSession(from previous: LanguageModelSession) -> LanguageModelSession {\n    let entries = previous.transcript.entries\n\n    guard entries.count > 2 else {\n        return LanguageModelSession(transcript: previous.transcript)\n    }\n\n    \u002F\u002F Keep: first (instructions) + last (recent context)\n    var condensed = [entries.first!, entries.last!]\n\n    let transcript = Transcript(entries: condensed)\n    return LanguageModelSession(transcript: transcript)\n}\n```\n\n**Time cost**: 15-20 minutes to implement condensing\n\n---\n\n### Pattern 2b: Guardrail Violation\n\n**Symptom**:\n```\nError: LanguageModelSession.GenerationError.guardrailViolation\n```\n\n**Diagnosis**:\n- User input triggered content policy\n- Violence, hate speech, illegal activities\n- Model refuses to generate\n\n**Fix**:\n```swift\n\u002F\u002F ✅ GOOD - Graceful handling\ndo {\n    let response = try await session.respond(to: userInput)\n    print(response.content)\n} catch LanguageModelSession.GenerationError.guardrailViolation {\n    \u002F\u002F Show user-friendly message\n    print(\"I can't help with that request\")\n    \u002F\u002F Log for review (but don't show user input to avoid storing harmful content)\n}\n```\n\n**Time cost**: 5-10 minutes\n\n---\n\n### Pattern 2c: Unsupported Language\n\n**Symptom**:\n```\nError: LanguageModelSession.GenerationError.unsupportedLanguageOrLocale\n```\n\n**Diagnosis**:\nUser input in language model doesn't support\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - No language check\nlet response = try await session.respond(to: userInput)\n\u002F\u002F Crashes if unsupported language\n\n\u002F\u002F ✅ GOOD - Check first\nlet supported = SystemLanguageModel.default.supportedLanguages\n\nguard supported.contains(Locale.current.language) else {\n    \u002F\u002F Show disclaimer\n    print(\"Language not supported. Currently supports: \\(supported)\")\n    return\n}\n\n\u002F\u002F Also handle errors\ndo {\n    let response = try await session.respond(to: userInput)\n} catch LanguageModelSession.GenerationError.unsupportedLanguageOrLocale {\n    print(\"Please use English or another supported language\")\n}\n```\n\n**Time cost**: 10 minutes\n\n---\n\n### Pattern 2d: General Error Handling\n\n**Symptom**:\nUnknown error types\n\n**Fix**:\n```swift\n\u002F\u002F ✅ GOOD - Comprehensive error handling\ndo {\n    let response = try await session.respond(to: prompt)\n    print(response.content)\n} catch LanguageModelSession.GenerationError.exceededContextWindowSize {\n    \u002F\u002F Handle context overflow\n    session = condensedSession(from: session)\n} catch LanguageModelSession.GenerationError.guardrailViolation {\n    \u002F\u002F Handle content policy\n    showMessage(\"Cannot generate that content\")\n} catch LanguageModelSession.GenerationError.unsupportedLanguageOrLocale {\n    \u002F\u002F Handle language issue\n    showMessage(\"Language not supported\")\n} catch {\n    \u002F\u002F Catch-all for unexpected errors\n    print(\"Unexpected error: \\(error)\")\n    showMessage(\"Something went wrong. Please try again.\")\n}\n```\n\n**Time cost**: 10-15 minutes\n\n---\n\n### Pattern 3a: Hallucinated Output (Wrong Use Case)\n\n**Symptom**:\n- Model gives factually incorrect answers\n- Makes up information\n\n**Diagnosis**:\nUsing model for world knowledge (wrong use case)\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - Wrong use case\nlet prompt = \"Who is the president of France?\"\nlet response = try await session.respond(to: prompt)\n\u002F\u002F Will hallucinate or give outdated info\n\n\u002F\u002F ✅ GOOD - Use server LLM for world knowledge\n\u002F\u002F Foundation Models is for:\n\u002F\u002F - Summarization\n\u002F\u002F - Extraction\n\u002F\u002F - Classification\n\u002F\u002F - Content generation\n\n\u002F\u002F OR: Use Tool calling with external data source\nstruct GetFactTool: Tool {\n    let name = \"getFact\"\n    let description = \"Fetch factual information from verified source\"\n\n    @Generable\n    struct Arguments {\n        let query: String\n    }\n\n    func call(arguments: Arguments) async throws -> ToolOutput {\n        \u002F\u002F Fetch from Wikipedia API, news API, etc.\n        let fact = await fetchFactFromAPI(arguments.query)\n        return ToolOutput(fact)\n    }\n}\n```\n\n**Time cost**: 20-30 minutes to implement tool OR switch to appropriate AI\n\n---\n\n### Pattern 3b: Wrong Structure (Not Using @Generable)\n\n**Symptom**:\n- Parsing errors\n- Invalid JSON\n- Wrong keys\n\n**Diagnosis**:\nManual JSON parsing instead of @Generable\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - Manual parsing\nlet prompt = \"Generate person as JSON\"\nlet response = try await session.respond(to: prompt)\nlet data = response.content.data(using: .utf8)!\nlet person = try JSONDecoder().decode(Person.self, from: data) \u002F\u002F CRASHES\n\n\u002F\u002F ✅ GOOD - @Generable\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\u002F\u002F response.content is type-safe Person, guaranteed structure\n```\n\n**Time cost**: 10 minutes to convert to @Generable\n\n---\n\n### Pattern 3c: Missing Data (Need Tool)\n\n**Symptom**:\n- Model doesn't have required information\n- Output is vague or generic\n\n**Diagnosis**:\nNeed external data (weather, locations, contacts)\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - No external data\nlet response = try await session.respond(\n    to: \"What's the weather in Tokyo?\"\n)\n\u002F\u002F Will make up weather data\n\n\u002F\u002F ✅ GOOD - Tool calling\nimport WeatherKit\n\nstruct GetWeatherTool: Tool {\n    let name = \"getWeather\"\n    let description = \"Get current weather for a city\"\n\n    @Generable\n    struct Arguments {\n        let city: String\n    }\n\n    func call(arguments: Arguments) async throws -> ToolOutput {\n        \u002F\u002F Fetch real weather\n        let weather = await WeatherService.shared.weather(for: arguments.city)\n        return ToolOutput(\"Temperature: \\(weather.temperature)°F\")\n    }\n}\n\nlet session = LanguageModelSession(tools: [GetWeatherTool()])\nlet response = try await session.respond(to: \"What's the weather in Tokyo?\")\n\u002F\u002F Uses real weather data\n```\n\n**Time cost**: 20-30 minutes to implement tool\n\n---\n\n### Pattern 3d: Inconsistent Output (Sampling)\n\n**Symptom**:\n- Different output every time for same prompt\n- Need consistent results for testing\n\n**Diagnosis**:\nRandom sampling (default behavior)\n\n**Fix**:\n```swift\n\u002F\u002F Default: Random sampling\nlet response1 = try await session.respond(to: \"Write a haiku\")\nlet response2 = try await session.respond(to: \"Write a haiku\")\n\u002F\u002F Different every time\n\n\u002F\u002F ✅ For deterministic output (testing\u002Fdemos)\nlet response = try await session.respond(\n    to: \"Write a haiku\",\n    options: GenerationOptions(sampling: .greedy)\n)\n\u002F\u002F Same output for same prompt (given same model version)\n\n\u002F\u002F ✅ For low variance\nlet response = try await session.respond(\n    to: \"Classify this article\",\n    options: GenerationOptions(temperature: 0.5)\n)\n\u002F\u002F Slightly varied but focused\n\n\u002F\u002F ✅ For high creativity\nlet response = try await session.respond(\n    to: \"Write a creative story\",\n    options: GenerationOptions(temperature: 2.0)\n)\n\u002F\u002F Very diverse output\n```\n\n**Time cost**: 2-5 minutes\n\n---\n\n### Pattern 4a: Initial Latency (Prewarm)\n\n**Symptom**:\n- First generation takes 1-2 seconds to start\n- Subsequent requests faster\n\n**Diagnosis**:\nModel loading time\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - Load on user interaction\nButton(\"Generate\") {\n    Task {\n        let session = LanguageModelSession() \u002F\u002F 1-2s delay here\n        let response = try await session.respond(to: prompt)\n    }\n}\n\n\u002F\u002F ✅ GOOD - Prewarm on init\nclass ViewModel: ObservableObject {\n    private var session: LanguageModelSession?\n\n    init() {\n        \u002F\u002F Prewarm before user interaction\n        Task {\n            self.session = LanguageModelSession(instructions: \"...\")\n        }\n    }\n\n    func generate(prompt: String) async throws -> String {\n        guard let session = session else {\n            \u002F\u002F Fallback if not ready\n            self.session = LanguageModelSession()\n            return try await self.session!.respond(to: prompt).content\n        }\n        return try await session.respond(to: prompt).content\n    }\n}\n```\n\n**Time cost**: 10 minutes\n**Latency saved**: 1-2 seconds on first request\n\n---\n\n### Pattern 4b: Long Generation (Streaming)\n\n**Symptom**:\n- User waits 3-5 seconds seeing nothing\n- Then entire result appears at once\n\n**Diagnosis**:\nNot streaming long generations\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - No streaming\nlet response = try await session.respond(\n    to: \"Generate 5-day itinerary\",\n    generating: Itinerary.self\n)\n\u002F\u002F User waits 4 seconds seeing nothing\n\n\u002F\u002F ✅ GOOD - Streaming\n@Generable\nstruct Itinerary {\n    var destination: String\n    var days: [DayPlan]\n}\n\nlet stream = session.streamResponse(\n    to: \"Generate 5-day itinerary to Tokyo\",\n    generating: Itinerary.self\n)\n\nfor try await partial in stream {\n    \u002F\u002F Update UI incrementally\n    self.itinerary = partial\n}\n\u002F\u002F User sees destination in 0.5s, then days progressively\n```\n\n**Time cost**: 15-20 minutes\n**Perceived latency**: 0.5s vs 4s\n\n---\n\n### Pattern 4c: Large Schema Overhead\n\n**Symptom**:\n- Subsequent requests with same @Generable type slow\n\n**Diagnosis**:\nSchema re-inserted into prompt every time\n\n**Fix**:\n```swift\n\u002F\u002F First request - schema inserted automatically\nlet first = try await session.respond(\n    to: \"Generate first person\",\n    generating: Person.self\n)\n\n\u002F\u002F ✅ Subsequent requests - skip schema insertion\nlet second = try await session.respond(\n    to: \"Generate another person\",\n    generating: Person.self,\n    options: GenerationOptions(includeSchemaInPrompt: false)\n)\n```\n\n**Time cost**: 2 minutes\n**Latency saved**: 10-20% per request\n\n---\n\n### Pattern 4d: Complex Prompt (Break Down)\n\n**Symptom**:\n- Generation takes >5 seconds\n- Poor quality results\n\n**Diagnosis**:\nPrompt too complex for single generation\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - One massive prompt\nlet prompt = \"\"\"\n    Generate complete 7-day itinerary with hotels, restaurants,\n    activities, transportation, budget, tips, and local customs\n    \"\"\"\n\u002F\u002F 5-8 seconds, poor quality\n\n\u002F\u002F ✅ GOOD - Break into steps\nlet overview = try await session.respond(\n    to: \"Generate high-level 7-day plan for Tokyo\"\n)\n\nvar dayDetails: [DayPlan] = []\nfor day in 1...7 {\n    let detail = try await session.respond(\n        to: \"Detail activities and restaurants for day \\(day) in Tokyo\",\n        generating: DayPlan.self\n    )\n    dayDetails.append(detail.content)\n}\n\u002F\u002F Total time similar, but better quality and progressive results\n```\n\n**Time cost**: 20-30 minutes\n**Quality improvement**: Significantly better\n\n---\n\n### Pattern 5a: UI Frozen (Main Thread Blocking)\n\n**Symptom**:\n- App unresponsive during generation\n- UI freezes for seconds\n\n**Diagnosis**:\nCalling `respond()` on main thread synchronously\n\n**Fix**:\n```swift\n\u002F\u002F ❌ BAD - Blocking main thread\nButton(\"Generate\") {\n    let response = try await session.respond(to: prompt)\n    \u002F\u002F UI frozen for 2-5 seconds!\n}\n\n\u002F\u002F ✅ GOOD - Async task\nButton(\"Generate\") {\n    Task {\n        do {\n            let response = try await session.respond(to: prompt)\n            \u002F\u002F Update UI on main thread\n            await MainActor.run {\n                self.result = response.content\n            }\n        } catch {\n            print(\"Error: \\(error)\")\n        }\n    }\n}\n```\n\n**Time cost**: 5 minutes\n**UX improvement**: Massive (no frozen UI)\n\n---\n\n## Production Crisis Scenario\n\n### Context\n\n**Situation**: You just launched an AI-powered feature using Foundation Models. Within 2 hours:\n- 20% of users report \"AI feature doesn't work\"\n- App Store reviews dropping: \"New AI broken\"\n- VP of Product emailing: \"What's the ETA on fix?\"\n- Engineering manager: \"Should we roll back?\"\n\n**Pressure Signals**:\n- ? **Revenue impact**: Feature is key selling point for new app version\n- ⏰ **Time pressure**: \"Fix it NOW\"\n- ? **Executive visibility**: VP watching\n- ? **Public reputation**: App Store reviews visible to all\n\n### Rationalization Traps\n\n**DO NOT** fall into these traps:\n\n1. **\"Disable the feature\"**\n   - Loses product differentiation\n   - Admits defeat\n   - Doesn't learn what went wrong\n\n2. **\"Roll back to previous version\"**\n   - Loses weeks of work\n   - Doesn't fix root cause\n   - Users still angry\n\n3. **\"It works for me\"**\n   - Simulator ≠ real devices\n   - Your device ≠ all devices\n   - Ignores real problem\n\n4. **\"Switch to ChatGPT API\"**\n   - Violates privacy\n   - Expensive at scale\n   - Doesn't address availability issue\n\n### MANDATORY Protocol\n\n#### Phase 1: Identify (5 minutes)\n\n```swift\n\u002F\u002F Check error distribution\n\u002F\u002F What percentage seeing what error?\n\n\u002F\u002F Run this on test devices:\nlet availability = SystemLanguageModel.default.availability\n\nswitch availability {\ncase .available:\n    print(\"✅ Available\")\ncase .unavailable(let reason):\n    print(\"❌ Unavailable: \\(reason)\")\n}\n\n\u002F\u002F Hypothesis:\n\u002F\u002F - If 20% unavailable → Availability issue (device\u002Fregion\u002Fopt-in)\n\u002F\u002F - If 20% getting errors → Code bug\n\u002F\u002F - If 20% seeing wrong results → Use case mismatch\n```\n\n**Results**: Discover that 20% of users have devices without Apple Intelligence support.\n\n---\n\n#### Phase 2: Confirm (5 minutes)\n\n```swift\n\u002F\u002F Check which devices affected\n\u002F\u002F iPhone 15 Pro+ = ✅ Available\n\u002F\u002F iPhone 15 = ❌ Unavailable\n\u002F\u002F iPhone 14 = ❌ Unavailable\n\n\u002F\u002F Conclusion: Availability issue, not code bug\n```\n\n**Root cause**: Feature assumes all users have Apple Intelligence. 20% don't.\n\n---\n\n#### Phase 3: Device Requirements (5 minutes)\n\nVerify:\n- Apple Intelligence requires iPhone 15 Pro or later\n- Or iPad with M1+ chip\n- Or Mac with Apple silicon\n\n#### 20% of user base = older devices\n\n---\n\n#### Phase 4: Implement Fix (15 minutes)\n\n```swift\n\u002F\u002F ✅ Add availability check + graceful UI\nstruct AIFeatureView: View {\n    @State private var availability = SystemLanguageModel.default.availability\n\n    var body: some View {\n        switch availability {\n        case .available:\n            \u002F\u002F Show AI feature\n            AIContentView()\n\n        case .unavailable:\n            \u002F\u002F Graceful fallback\n            VStack {\n                Image(systemName: \"sparkles\")\n                    .font(.largeTitle)\n                    .foregroundColor(.secondary)\n\n                Text(\"AI-Powered Features\")\n                    .font(.headline)\n\n                Text(\"Available on iPhone 15 Pro and later\")\n                    .font(.subheadline)\n                    .foregroundColor(.secondary)\n                    .multilineTextAlignment(.center)\n\n                \u002F\u002F Offer alternative\n                Button(\"Use Standard Mode\") {\n                    \u002F\u002F Show non-AI fallback\n                }\n            }\n        }\n    }\n}\n```\n\n---\n\n#### Phase 5: Deploy (20 minutes)\n\n1. Test on multiple devices (15 min)\n   - iPhone 15 Pro: ✅ Shows AI feature\n   - iPhone 14: ✅ Shows graceful message\n   - iPad Pro M1: ✅ Shows AI feature\n\n2. Submit hotfix build (5 min)\n\n---\n\n### Communication Template\n\n**To VP of Product (immediate)**:\n```\nRoot cause identified:\n\nThe AI feature requires Apple Intelligence (iPhone 15 Pro+).\n20% of our users have older devices. We didn't check availability.\n\nFix: Added availability check with graceful fallback UI.\n\nTimeline:\n- Hotfix ready: Now\n- TestFlight: 10 minutes\n- App Store submission: 30 minutes\n- Review: 24-48 hours (requesting expedited)\n\nImpact mitigation:\n- 80% of users see working AI feature\n- 20% see clear message + standard mode fallback\n- No functionality lost, just graceful degradation\n```\n\n**To Engineering Team**:\n```\nPost-mortem items:\n1. Add availability check to launch checklist\n2. Test on non-Apple-Intelligence devices\n3. Document device requirements clearly\n4. Add analytics for availability status\n```\n\n### Time Saved\n\n- **Panic path (disable\u002Frollback)**: 2 hours of meetings + lost work\n- **Proper diagnosis**: 45 minutes root cause → fix → deploy\n\n### What We Learned\n\n1. **Always check availability** before creating session\n2. **Test on real devices** across device generations\n3. **Graceful degradation** better than feature removal\n4. **Clear messaging** to users about requirements\n\n---\n\n## Quick Reference Table\n\n| Symptom | Cause | Check | Pattern | Time |\n|---------|-------|-------|---------|------|\n| Won't start | .unavailable | SystemLanguageModel.default.availability | 1a | 5 min |\n| Region issue | Not supported region | Check supported regions | 1b | 5 min |\n| Not opted in | Apple Intelligence disabled | Settings check | 1c | 10 min |\n| Context exceeded | >4096 tokens | Transcript length | 2a | 15 min |\n| Guardrail error | Content policy | User input type | 2b | 10 min |\n| Language error | Unsupported language | supportedLanguages | 2c | 10 min |\n| Hallucinated output | Wrong use case | Task type check | 3a | 20 min |\n| Wrong structure | No @Generable | Manual parsing? | 3b | 10 min |\n| Missing data | No tool | External data needed? | 3c | 30 min |\n| Inconsistent | Random sampling | Need deterministic? | 3d | 5 min |\n| Initial delay | Model loading | First request slow? | 4a | 10 min |\n| Long wait | No streaming | >1s generation? | 4b | 20 min |\n| Schema overhead | Re-inserting schema | Subsequent requests? | 4c | 2 min |\n| Complex prompt | Too much at once | >5s generation? | 4d | 30 min |\n| UI frozen | Main thread | Thread check | 5a | 5 min |\n\n---\n\n## Cross-References\n\n**Related Axiom Skills**:\n- `axiom-foundation-models` — Discipline skill for anti-patterns, proper usage patterns, pressure scenarios\n- `axiom-foundation-models-ref` — Complete API reference with all WWDC 2025 code examples\n\n**Apple Resources**:\n- Foundation Models Framework Documentation\n- WWDC 2025-286: Meet the Foundation Models framework\n- WWDC 2025-301: Deep dive into the Foundation Models framework\n- Instruments Foundation Models Template\n\n---\n\n**Last Updated**: 2025-12-03\n**Version**: 1.0.0\n**Skill Type**: Diagnostic\n\n",{"name":5,"license":15,"metadata":41,"description":7,"compatibility":44},{"version":42,"last-updated":43},"1.0.0","2025-12-03","iOS 26+, macOS 26+, iPadOS 26+, axiom-visionOS 26+","main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-foundation-models-diag",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":55,"prompt":65,"zipAvailable":66},[56,59,62],{"tool":57,"command":58},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill axiom-foundation-models-diag",{"tool":60,"command":61},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill axiom-foundation-models-diag",{"tool":63,"command":64},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill axiom-foundation-models-diag","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-foundation-models-diag\u002FSKILL.md",true,[68],{"path":69,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":72,"sourceHtmlUrl":73},"SKILL.md.tmpl","OTHER","其他",5594,"https:\u002F\u002Fgithub.com\u002Fmarshadgani\u002FArshad.AI\u002Fblob\u002Fclaude\u002Fai-personal-assistant-main\u002F.claude\u002Fskills\u002Fgstack\u002Flearn\u002FSKILL.md.tmpl",[75,84,93,102,108,114],{"skillNo":76,"name":77,"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":78,"categories":79,"keywords":80,"publishedAt":36},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[81,82,83],"model","model hierarchy","model hierarchy skill",{"skillNo":85,"name":86,"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":87,"categories":88,"keywords":89,"publishedAt":36},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[90,91,92],"MCP","zoom","zoom mcp",{"skillNo":94,"name":95,"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":96,"categories":97,"keywords":98,"publishedAt":36},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[99,100,101,91],"sdk","zoom apps sdk","apps",{"skillNo":103,"name":104,"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":105,"categories":106,"keywords":107,"publishedAt":36},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[104],{"skillNo":109,"name":110,"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":111,"categories":112,"keywords":113,"publishedAt":36},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[110],{"skillNo":115,"name":116,"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":117,"categories":118,"keywords":119,"publishedAt":36},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[116]]