Back to .md Directory

CLAUDE.md

Guides Claude Code when working with a SwiftUI app that uses Apple's Foundation Models framework for on-device AI.

May 2, 2026
0 downloads
0 views
ai prompt claude workflow safety
View source

What this file does

Guides Claude Code when working with a SwiftUI app that uses Apple's Foundation Models framework for on-device AI.

When to use it

  • You need to set up Claude Code for an Apple Intelligence project
  • You are building a chat app using Foundation Models on iOS 26+
  • You want structured guidance for tool calling and streaming responses
  • You need to enforce availability checks and error handling patterns

Assumes this stack

SwiftSwiftUIApple Foundation ModelsiOS 26.0+

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

iChat is a SwiftUI application demonstrating Apple's Foundation Models framework for on-device AI. The project targets iOS 26.0+ and showcases chat functionality using Apple Intelligence.

Framework Overview

Apple's Foundation Models framework provides on-device large language models that power Apple Intelligence. It's available on iOS 26.0+, iPadOS 26.0+, macOS 26.0+, and visionOS 26.0+.

Key Documentation Files

1. EXAMPLES/FOUNDATION_MODELS_RULES.md

When to use: Start here for understanding core framework principles

  • Availability checking patterns
  • Session management rules
  • Performance optimization guidelines
  • Safety implementation requirements
  • Platform requirements and limitations

2. EXAMPLES/QUICK_REFERENCE.md

When to use: For quick code snippets and common patterns

  • Import statements
  • Basic usage patterns
  • Error handling snippets
  • Common configurations

3. EXAMPLES/01_Basic_Usage.md

When to use: For simple text generation tasks

  • Creating sessions
  • Basic prompting
  • Handling availability states
  • Error handling basics
  • Multi-turn conversations

4. EXAMPLES/02_Structured_Output.md

When to use: When you need structured data from the model

  • @Generable macro usage
  • @Guide annotations
  • Complex nested structures
  • Optional properties
  • Performance considerations

5. EXAMPLES/03_Streaming_Responses.md

When to use: For real-time UI updates during generation

  • Basic streaming implementation
  • Streaming with structured output
  • Progress tracking
  • Error handling in streams
  • SwiftUI integration

6. EXAMPLES/04_Tool_Calling.md

When to use: When the model needs external data/actions

  • Tool protocol implementation
  • Integration with system frameworks (Contacts, Calendar, etc.)
  • Stateful tools
  • Multiple tool usage

7. EXAMPLES/05_Performance_and_Safety.md

When to use: For optimization and safety implementation

  • Prewarming strategies
  • Schema optimization
  • Safety boundaries
  • Context management
  • Performance monitoring

8. EXAMPLES/06_Complete_Chat_App.md

When to use: For understanding the full application structure

  • Complete chat implementation
  • SwiftUI best practices
  • State management
  • UI/UX considerations

Development Workflow

Starting a New Feature

  1. Check FOUNDATION_MODELS_RULES.md for constraints
  2. Reference QUICK_REFERENCE.md for syntax
  3. Find similar examples in the numbered example files
  4. Always check availability first
  5. Implement with proper error handling

Common Tasks Reference

TaskPrimary ReferenceSecondary Reference
Basic text generation01_Basic_Usage.mdQUICK_REFERENCE.md
Structured data extraction02_Structured_Output.md04_Tool_Calling.md
Chat interface06_Complete_Chat_App.md03_Streaming_Responses.md
Adding tools/functions04_Tool_Calling.mdFOUNDATION_MODELS_RULES.md
Performance optimization05_Performance_and_Safety.mdFOUNDATION_MODELS_RULES.md
Safety implementation05_Performance_and_Safety.mdFOUNDATION_MODELS_RULES.md

Critical Rules (Always Remember)

  1. ALWAYS check SystemLanguageModel.default.isAvailable before using
  2. NEVER assume the model is available - provide fallback UI
  3. Handle all error cases, especially:
    • GenerationError.guardrailViolation
    • GenerationError.exceededContextWindowSize
    • GenerationError.unsupportedLanguageOrLocale
  4. Use streaming for responses > 1 sentence for better UX
  5. Prewarm sessions when users show intent to interact
  6. Keep instructions in sessions, not user input (security)

Code Patterns

Standard Session Creation

@available(iOS 26.0, *)
guard SystemLanguageModel.default.isAvailable else { 
    // Show fallback UI
    return 
}

let session = LanguageModelSession(instructions: """
    You are a helpful assistant.
    Be concise and accurate.
    """)

Structured Output Pattern

@Generable
struct Output {
    @Guide(description: "Clear description")
    let field: String
}

let response = try await session.respond(
    to: prompt,
    generating: Output.self
)

Tool Implementation Pattern

struct MyTool: Tool {
    let name = "toolName"
    let description = "What it does"
    
    @Generable
    struct Arguments {
        let param: String
    }
    
    func call(arguments: Arguments) async throws -> ToolOutput {
        // Implementation
        return ToolOutput("result")
    }
}

Debugging Tips

  1. Use Foundation Models Instrument in Xcode
  2. Monitor token counts and response times
  3. Check session.transcript for conversation history
  4. Log availability state changes
  5. Test all error scenarios

When Things Go Wrong

  • Model not available: Check Settings > Apple Intelligence
  • Guardrail violations: Rephrase prompts, add safety instructions
  • Context overflow: Create new session or condense history
  • Poor performance: Check prewarming, schema inclusion settings

Development Best Practices

  • When editing code, always build the project to check for errors and fix them, then rebuild.
  • Always build the project with XcodeBuildMCP to check for error

Remember: This framework prioritizes privacy and runs entirely on-device. No internet connection is required, but the model must be downloaded and Apple Intelligence must be enabled.

What's inside

1 project overview, 1 framework overview, 8 documentation file references, 1 development workflow, 1 common tasks table, 7 critical rules, 3 code patterns, 5 debugging tips, 1 troubleshooting section, 2 best practices

Change this for your project

  • Replace Numi2/ichat with your own repository name
  • Replace iChat with your own project name throughout
  • Replace SystemLanguageModel.default.isAvailable with your own availability check if using a different model

Where it goes

Save as CLAUDE.md in your repository root. Claude Code reads it automatically at the start of every session.

Worth borrowing

  • Linking to numbered example files for each task type keeps the main file short and the examples reusable
  • A common tasks reference table maps each task to primary and secondary references, making navigation fast
  • Critical rules are listed as explicit do/don't statements (ALWAYS/NEVER) to prevent common mistakes

Related Documents