### Swift Language Model Session with Instructions Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Demonstrates how to create a `LanguageModelSession` with custom instructions to guide the model's responses. Includes an example prompt and response. ```swift let instructions = """ Suggest related topics. Keep them concise (three to seven words) and make sure they \ build naturally from the person's topic. """ let session = LanguageModelSession(instructions: instructions) let prompt = "Making homemade bread" let response = try await session.respond(to: prompt) ``` -------------------------------- ### Homebrew Installation Command Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/FoundationLabCLI/README.md After a formula is committed to a tap repository, users can install the FoundationLabCLI using this Homebrew command. ```bash brew install rudrankriyam/homebrew-tap/fm ``` -------------------------------- ### GameCharacter with Level Range Guide Example Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Example demonstrating the use of the `.range` generation guide for an Int property within a struct. ```swift @Generable struct GameCharacter { @Guide(description: "A creative name appropriate for a fantasy RPG character") var name: String @Guide(description: "A level for the character", .range(1...100)) var level: Int } ``` -------------------------------- ### GameCharacter with Level Minimum Guide Example Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Example demonstrating the use of the `.minimum` generation guide for an Int property within a struct. ```swift @Generable struct GameCharacter { @Guide(description: "A creative name appropriate for a fantasy RPG character") var name: String @Guide(description: "A level for the character", .minimum(1)) var level: Int } ``` -------------------------------- ### GameCharacter with Level Maximum Guide Example Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Example demonstrating the use of the `.maximum` generation guide for an Int property within a struct. ```swift @Generable struct GameCharacter { @Guide(description: "A creative name appropriate for a fantasy RPG character") var name: String @Guide(description: "A level for the character", .maximum(100)) var level: Int } ``` -------------------------------- ### fm CLI: Schema Demonstrations (Bash) Source: https://context7.com/rudrankriyam/foundation-models-framework-example/llms.txt Commands to list available schema examples and run them using the `fm` CLI, including specifying presets, custom inputs, choices, and constraints. ```bash # Schema demos fm schemas list fm schemas run basic-object --preset person fm schemas run basic-object --input "Marie Curie, physicist, age 35" fm schemas run array-schema --preset todo --min-items 3 --max-items 6 fm schemas run enum-schema --preset sentiment --choice positive --choice negative --choice neutral ``` -------------------------------- ### Initialize LanguageModelSession with Instructions Object Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Start a new session with a pre-defined `Instructions` object. This is useful when instructions are generated or managed elsewhere. ```swift public convenience init(model: SystemLanguageModel = .default, tools: [any Tool] = [], instructions: Instructions? = nil) ``` -------------------------------- ### Initialize LanguageModelSession with Instructions Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Create a new session with specific instructions to guide the model's behavior. This is useful for setting a role or persona for the language model. ```swift let session = LanguageModelSession(instructions: """ You are a motivational workout coach that provides quotes to inspire \ and motivate athletes. """) let prompt = "Generate a motivational quote for my next workout." let response = try await session.respond(to: prompt) ``` -------------------------------- ### Dynamic Runtime Schemas (Swift) Source: https://context7.com/rudrankriyam/foundation-models-framework-example/llms.txt Demonstrates using `DynamicGenerationSchema` with `RunSchemaExampleUseCase` for runtime schema generation. Includes examples for basic objects, arrays, and enums. Requires `FoundationLabCore` import. ```swift import FoundationLabCore // List all schema examples and their presets for example in FoundationSchemaExample.allCases { print("\(example.title): \(example.summary)") example.presets.forEach { print(" • \($0.title): \($0.defaultInput)") } } // Run a basic object schema (person extraction) let result = try await RunSchemaExampleUseCase().execute( RunSchemaExampleRequest( example: .basicObject, presetIndex: 0, // "Person" preset input: "Sarah Connor is 29, works as a software engineer and plays chess.", context: CapabilityInvocationContext(source: .app) ) ) print(result.content) // {"name": "Sarah Connor", "age": 29, "occupation": "software engineer"} // Run an enum schema with custom choices (sentiment analysis) let enumResult = try await RunSchemaExampleUseCase().execute( RunSchemaExampleRequest( example: .enumSchema, presetIndex: 0, // "Sentiment Analysis" preset input: "The delivery was late and the packaging was damaged.", customChoices: ["positive", "negative", "neutral", "mixed"], context: CapabilityInvocationContext(source: .app) ) ) print(enumResult.content) // "negative" ``` -------------------------------- ### Initialize LanguageModelSession with Model and Tools Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Start a new session with a specified language model and a list of available tools. This allows for customized model behavior and functionality. ```swift public convenience init(model: SystemLanguageModel = .default, tools: [any Tool] = [], instructions: String? = nil) ``` -------------------------------- ### Property Initializers Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Initializers for creating a `Property` object, defining its name, description, type, and optional guides (regex patterns). ```APIDOC ## Property Initializers ### Description Initializers for creating a `Property` object, defining its name, description, type, and optional guides (regex patterns). ### Initializers #### `init(name: String, description: String?, type: String.Type, guides: [Regex] = [])` Creates a property with a specified name, description, type, and an array of regex guides. - **name** (String) - Required - The property's name. - **description** (String?) - Optional - A natural language description of what content should be generated for this property. - **type** (String.Type) - Required - The type this property represents. - **guides** ([Regex] = []) - Optional - An array of regexes to be applied to this string. If there are multiple regexes, only the last one will be applied. #### `init(name: String, description: String?, type: String?.Type, guides: [Regex] = [])` Creates an optional property that contains a generable type. - **name** (String) - Required - The property's name. - **description** (String?) - Optional - A natural language description of what content should be generated for this property. - **type** (String?.Type) - Required - The type this property represents. - **guides** ([Regex] = []) - Optional - An array of regexes to be applied to this string. If there are multiple regexes, only the last one will be applied. ``` -------------------------------- ### Enforce Minimum Float Value with Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `minimum` generation guide to ensure a Float value is greater than or equal to a specified minimum. Useful for setting baseline values like starting character levels. ```swift @Generable struct GameCharacter { @Guide(description: "A creative name appropriate for a fantasy RPG character") var name: String @Guide(description: "A level for the character", .minimum(1.0)) var level: Float } ``` -------------------------------- ### Enforce Minimum Decimal Value with Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `minimum` generation guide to ensure a Decimal value is greater than or equal to a specified minimum. Applicable for precise numerical requirements. ```swift @Generable struct GameCharacter { @Guide(description: "A creative name appropriate for a fantasy RPG character") var name: String @Guide(description: "A level for the character", .minimum(0.75)) var level: Decimal } ``` -------------------------------- ### Enforce Maximum Decimal Value with Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `maximum` generation guide to ensure a Decimal value is less than or equal to a specified maximum. Useful for precise upper bounds. ```swift @Generable struct GameCharacter { @Guide(description: "A creative name appropriate for a fantasy RPG character") var name: String @Guide(description: "A level for the character", .maximum(99.9)) var level: Decimal } ``` -------------------------------- ### Swift: Define Minimum Value Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `minimum` generation guide to ensure the model produces a value greater than or equal to a specified minimum. This is useful for setting lower bounds on numerical properties. ```swift public static func minimum(_ value: Double) -> GenerationGuide ``` -------------------------------- ### GenerationGuide.element Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Applies guides to the elements within an array. ```APIDOC ## element ### Description Applies guides to the elements within an array. ### Method `func element() -> GenerationGuide where Value == [T]` ``` -------------------------------- ### fm CLI: Tool Commands (Bash) Source: https://context7.com/rudrankriyam/foundation-models-framework-example/llms.txt Examples of invoking tool-based capabilities like weather, web search, and web page summarization directly from the `fm` command-line interface. ```bash # Tool commands fm tools weather get --location "Tokyo" fm tools web search --query "Swift 6 migration guide" fm tools web summary --url "https://swift.org/blog/" ``` -------------------------------- ### Basic Chat with LanguageModelSession Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/README.md Initiates a basic chat session to get a response from the language model. Requires setting up a LanguageModelSession. ```swift let session = LanguageModelSession() let response = try await session.respond( to: "Suggest a catchy name for a new coffee shop." ) print(response.content) ``` -------------------------------- ### Voice Interface: Speech Recognition and Synthesis Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/README.md Provides examples for implementing voice capabilities, including speech recognition using SpeechRecognizer and text-to-speech using SpeechSynthesizer. ```swift // Speech recognition let recognizer = SpeechRecognizer() try recognizer.startRecognition() // Text-to-speech try await SpeechSynthesizer.shared.synthesizeAndSpeak(text: "Hello, how can I help you?") ``` -------------------------------- ### fm CLI: One-shot and Streaming Responses (Bash) Source: https://context7.com/rudrankriyam/foundation-models-framework-example/llms.txt Examples of using the `fm` CLI for single-turn responses and streaming output. The `--prompt` argument is used to provide input. ```bash # One-shot response fm session respond --prompt "Suggest an uplifting science fiction novel" # Streaming response fm session stream --prompt "Write a haiku about concurrency" ``` -------------------------------- ### Custom String Convertible Example Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Demonstrates how to implement the `CustomStringConvertible` protocol to provide a custom string representation for a struct. Use `String(describing:)` to convert instances to strings. ```swift struct Point: CustomStringConvertible { let x: Int, y: Int var description: String { return "(\x), (\y))" } } let p = Point(x: 21, y: 30) let s = String(describing: p) print(s) // Prints "(21, 30)" ``` -------------------------------- ### Swift: Define Maximum Value Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `maximum` generation guide to ensure the model produces a value less than or equal to a specified maximum. This is useful for setting upper bounds on numerical properties, like a character's level. ```swift public static func maximum(_ value: Double) -> GenerationGuide ``` -------------------------------- ### Initialize LanguageModelSession from Transcript Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Start a new session by rehydrating from an existing `Transcript`. This allows for resuming a previous conversation or context. ```swift /// Start a session by rehydrating from a transcript. /// ``` -------------------------------- ### GenerationGuide AnyOf String Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Enforces that a string value must be one of the provided values. ```swift public static func anyOf(_ values: [String]) -> GenerationGuide ``` -------------------------------- ### Homebrew Formula Build Strategy Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/FoundationLabCLI/README.md This Ruby code snippet outlines the build strategy for the FoundationLabCLI within a Homebrew formula. It navigates to the CLI directory, builds the release version, and installs the executable. ```ruby cd "FoundationLabCLI" do system "swift", "build", "--configuration", "release", "--disable-sandbox" bin.install ".build/release/fm" end ``` -------------------------------- ### GenerationGuide Minimum Int Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Enforces a minimum inclusive value for an Int. Use this to ensure generated integers are greater than or equal to a specified value. ```swift public static func minimum(_ value: Int) -> GenerationGuide ``` -------------------------------- ### GenerationGuide Maximum Int Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Enforces a maximum inclusive value for an Int. Use this to ensure generated integers are less than or equal to a specified value. ```swift public static func maximum(_ value: Int) -> GenerationGuide ``` -------------------------------- ### GenerationGuide Pattern String Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Enforces that a string value must follow the specified regular expression pattern. ```swift public static func pattern(_ regex: Regex) -> GenerationGuide ``` -------------------------------- ### GenerationGuide Constant String Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Enforces that a string value must be exactly the specified constant value. ```swift public static func constant(_ value: String) -> GenerationGuide ``` -------------------------------- ### LanguageModelSession Initialization Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Initializes a new LanguageModelSession. You can provide system-level instructions to guide the model's behavior throughout the session. These instructions are essential for setting the model's role and response guidelines. ```APIDOC ## LanguageModelSession(model: SystemLanguageModel, tools: [any Tool], instructions: String?) ### Description Starts a new session with a blank slate and string-based instructions. ### Parameters - **model** (SystemLanguageModel) - The language model to use for this session. - **tools** ([any Tool]) - Tools to make available to the model for this session. - **instructions** (String?) - Instructions that control the model's behavior. ## LanguageModelSession(model: SystemLanguageModel, tools: [any Tool], instructions: InstructionsBuilder) ### Description Starts a new session with a blank slate and instructions provided via an InstructionsBuilder. ### Parameters - **model** (SystemLanguageModel) - The language model to use for this session. - **tools** ([any Tool]) - Tools to make available to the model for this session. - **instructions** (@InstructionsBuilder () -> Instructions) - Instructions that control the model's behavior. ## LanguageModelSession(model: SystemLanguageModel, tools: [any Tool], instructions: Instructions?) ### Description Starts a new session with a blank slate and a structured Instructions object. ### Parameters - **model** (SystemLanguageModel) - The language model to use for this session. - **tools** ([any Tool]) - Tools to make available to the model for this session. - **instructions** (Instructions?) - Instructions that control the model's behavior. ## LanguageModelSession(transcript: Transcript) ### Description Starts a session by rehydrating from an existing transcript, allowing the conversation to continue from a previous state. ``` -------------------------------- ### Call Tool-Backed Capabilities (Swift) Source: https://context7.com/rudrankriyam/foundation-models-framework-example/llms.txt Demonstrates how to invoke capabilities that wrap underlying tools for weather, web search, and web page summarization. Requires `FoundationLabCore` import. ```swift import FoundationLabCore let ctx = CapabilityInvocationContext(source: .app) // Weather (OpenMeteo, no API key required) let weather = try await GetWeatherUseCase().execute( GetWeatherRequest(location: "Cupertino", context: ctx) ) print(weather.content) // "Currently 22°C in Cupertino. Partly cloudy with a light breeze at 12 km/h." // Web search let search = try await SearchWebUseCase().execute( SearchWebRequest(query: "WWDC 2025 highlights", context: ctx) ) print(search.content) // Web page summary let summary = try await GenerateWebPageSummaryUseCase().execute( GenerateWebPageSummaryRequest( url: "https://developer.apple.com/foundation-models/", context: ctx ) ) print(summary.content) print("Tokens:", summary.metadata.tokenCount ?? 0) ``` -------------------------------- ### GenerationGuide.minimum(_:) Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Creates a GenerationGuide for integers that enforces a minimum value (inclusive). ```APIDOC /// Enforces a minimum value. /// /// Use a `minimum` generation guide --- whose bounds are inclusive --- to ensure the model produces /// a value greater than or equal to some minimum value. For example, you can specify that all characters /// in your game start at level 1: /// /// ```swift /// @Generable /// struct GameCharacter { /// @Guide(description: "A creative name appropriate for a fantasy RPG character") /// var name: String /// /// @Guide(description: "A level for the character", .minimum(1)) /// var level: Int /// } /// ``` public static func minimum(_ value: Int) -> GenerationGuide ``` -------------------------------- ### SystemLanguageModel.init(adapter:guardrails:) Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Initializes the base SystemLanguageModel with a custom adapter. ```APIDOC ## SystemLanguageModel.init(adapter:guardrails:) ### Description Creates the base version of the model, incorporating a provided adapter for customized behavior, along with optional guardrails. ### Initializer `public convenience init(adapter: SystemLanguageModel.Adapter, guardrails: SystemLanguageModel.Guardrails = .default)` ### Parameters - **adapter** (SystemLanguageModel.Adapter) - The adapter to customize the model's behavior. - **guardrails** (SystemLanguageModel.Guardrails) - The guardrails to apply to the model. Defaults to `.default`. ### Availability - iOS 26.0+ - macOS 26.0+ - tvOS unavailable - watchOS unavailable ``` -------------------------------- ### SystemLanguageModel.init(useCase:guardrails:) Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Initializes a SystemLanguageModel for a specific use case. ```APIDOC ## SystemLanguageModel.init(useCase:guardrails:) ### Description Creates a system language model tailored for a specific use case, with options for default or custom guardrails. ### Initializer `public convenience init(useCase: SystemLanguageModel.UseCase = .general, guardrails: SystemLanguageModel.Guardrails = Guardrails.default)` ### Parameters - **useCase** (SystemLanguageModel.UseCase) - The specific use case for the model. Defaults to `.general`. - **guardrails** (SystemLanguageModel.Guardrails) - The guardrails to apply to the model. Defaults to `Guardrails.default`. ### Availability - iOS 26.0+ - macOS 26.0+ - tvOS unavailable - watchOS unavailable ``` -------------------------------- ### Get JSON String Representation of GeneratedContent Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Access the `jsonString` property to get a JSON string representation of the GeneratedContent object. This is useful for serializing the content. ```swift // Object with properties let content = GeneratedContent(properties: [ "name": "Johnny Appleseed", "age": 30, ]) print(content.jsonString) // Output: {"name": "Johnny Appleseed", "age": 30} ``` -------------------------------- ### Swift Macro for Guiding Generable Types Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Defines the `@Guide` macro for influencing allowed values of properties in `Generable` types. Supports different overloads for various input types. ```swift /// Allows for influencing the allowed values of properties of a ``Generable`` type. /// - SeeAlso: `@Generable` macro ``Generable(description:)`` @available(iOS 26.0, macOS 26.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable) @attached(peer) public macro Guide(description: String? = nil, _ guides: GenerationGuide...) = #externalMacro(module: "FoundationModelsMacros", type: "GuideMacro") where T : Generable ``` ```swift /// Allows for influencing the allowed values of properties of a ``Generable`` type. /// - SeeAlso: `@Generable` macro ``Generable(description:)`` @available(iOS 26.0, macOS 26.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable) @attached(peer) public macro Guide(description: String? = nil, _ guides: Regex) = #externalMacro(module: "FoundationModelsMacros", type: "GuideMacro") ``` ```swift /// Allows for influencing the allowed values of properties of a ``Generable`` type. /// - SeeAlso: `@Generable` macro ``Generable(description:)`` @available(iOS 26.0, macOS 26.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable) @attached(peer) public macro Guide(description: String) = #externalMacro(module: "FoundationModelsMacros", type: "GuideMacro") ``` -------------------------------- ### Local Development Commands for FoundationLabCLI Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/FoundationLabCLI/README.md Use these commands to run the FoundationLabCLI locally after navigating to its directory. The `--help` flag provides general assistance, while other commands demonstrate specific functionalities like checking model status or simulating a session response. ```bash cd FoundationLabCLI swift run fm --help ``` ```bash swift run fm model status ``` ```bash swift run fm session respond --dry-run --json --prompt "Suggest an uplifting science fiction novel" ``` -------------------------------- ### Enforce Minimum Double Value with Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `minimum` generation guide to ensure a Double value is greater than or equal to a specified minimum. Similar to Float, but with different precision. ```swift @Generable struct GameCharacter { @Guide(description: "A creative name appropriate for a fantasy RPG character") ``` -------------------------------- ### GenerationGuide.maximum(_:) Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Creates a GenerationGuide for integers that enforces a maximum value (inclusive). ```APIDOC /// Enforces a maximum value. /// /// Use a `maximum` generation guide --- whose bounds are inclusive --- to ensure the model produces /// a value less than or equal to some maximum value. For example, you can specify that the highest level /// a character in your game can achieve is 100: /// /// ```swift /// @Generable /// struct GameCharacter { /// @Guide(description: "A creative name appropriate for a fantasy RPG character") /// var name: String /// /// @Guide(description: "A level for the character", .maximum(100)) /// var level: Int /// } /// ``` public static func maximum(_ value: Int) -> GenerationGuide ``` -------------------------------- ### Swift: Define Maximum Array Count Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `maximumCount` generation guide to enforce a maximum number of elements in an array. The bounds are inclusive, useful for limiting the number of items in a list. ```swift public static func maximumCount(_ count: Int) -> GenerationGuide<[Element]> where Value == [Element] ``` -------------------------------- ### GenerationGuide.anyOf(_:) Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Creates a GenerationGuide for strings that enforces the string to be one of the provided values. ```APIDOC /// Enforces that the string be one of the provided values. public static func anyOf(_ values: [String]) -> GenerationGuide ``` -------------------------------- ### Enforce Decimal Value within a Range with Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `range` generation guide to ensure a Decimal value falls within inclusive bounds. Ideal for precise cost or value ranges. ```swift @Generable struct ShopItem { @Guide(description: "A creative name for an item sold in a fantasy RPG") var name: String @Guide(description: "A cost for the item", .range(0.25...1000)) var cost: Decimal } ``` -------------------------------- ### Swift: Define Exact Array Count Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `count` generation guide with a specific integer to enforce that an array has exactly a certain number of elements. Useful for ensuring a list has a precise size. ```swift public static func count(_ count: Int) -> GenerationGuide<[Element]> where Value == [Element] ``` -------------------------------- ### Build and Run Commands for Foundation Lab Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/Agents.md Commands to open the project in Xcode, build from the command line, and run tests on a specific simulator. ```bash open FoundationLab.xcodeproj ``` ```bash xcodebuild -project FoundationLab.xcodeproj -scheme "Foundation Lab" -destination 'platform=iOS Simulator,name=iPhone 17 Pro' build ``` ```bash xcodebuild -project FoundationLab.xcodeproj -scheme "Foundation Lab" -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -derivedDataPath ./build test ``` -------------------------------- ### Control Text Generation Options (Swift) Source: https://context7.com/rudrankriyam/foundation-models-framework-example/llms.txt Illustrates how to use `FoundationLabGenerationOptions` to control sampling methods (greedy, top-k, nucleus), temperature, and maximum response tokens for text generation requests. Requires `FoundationLabCore` import. ```swift import FoundationLabCore // Greedy decoding (deterministic) let greedy = FoundationLabGenerationOptions( sampling: .greedy, maximumResponseTokens: 100 ) // Random top-k sampling with a fixed seed for reproducibility let topK = FoundationLabGenerationOptions( sampling: .randomTop(50, seed: 42), temperature: 0.8, maximumResponseTokens: 512 ) // Random nucleus (top-p) sampling let nucleus = FoundationLabGenerationOptions( sampling: .randomProbabilityThreshold(0.95), temperature: 1.0 ) let result = try await GenerateTextUseCase().execute( TextGenerationRequest( prompt: "Write a creative opening line for a novel.", generationOptions: topK, context: CapabilityInvocationContext(source: .app) ) ) print(result.content) ``` -------------------------------- ### Enforce Float Value within a Range with Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `range` generation guide to ensure a Float value falls within inclusive bounds. Suitable for values like item costs in a game. ```swift @Generable struct ShopItem { @Guide(description: "A creative name for an item sold in a fantasy RPG") var name: String @Guide(description: "A cost for the item", .range(1...1000)) var cost: Float } ``` -------------------------------- ### GenerationGuide.constant(_:) Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Creates a GenerationGuide for strings that enforces the string to be exactly a given value. ```APIDOC /// Enforces that the string be precisely the given value. public static func constant(_ value: String) -> GenerationGuide ``` -------------------------------- ### Swift: Define Minimum Array Count Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `minimumCount` generation guide to enforce a minimum number of elements in an array. The bounds are inclusive, useful for ensuring a list has at least a certain number of items. ```swift public static func minimumCount(_ count: Int) -> GenerationGuide<[Element]> where Value == [Element] ``` -------------------------------- ### GenerationGuide.range(_:) Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Creates a GenerationGuide for integers that enforces values to fall within a specified inclusive range. ```APIDOC /// Enforces values fall within a range. /// /// Use a `range` generation guide --- whose bounds are inclusive --- to ensure the model produces a /// value that falls within a range. For example, you can specify that the level of characters in your game /// are between 1 and 100: /// /// ```swift /// @Generable /// struct GameCharacter { /// @Guide(description: "A creative name appropriate for a fantasy RPG character") /// var name: String /// /// @Guide(description: "A level for the character", .range(1...100)) /// var level: Int /// } /// ``` public static func range(_ range: ClosedRange) -> GenerationGuide ``` -------------------------------- ### Enforce Maximum Float Value with Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `maximum` generation guide to ensure a Float value is less than or equal to a specified maximum. Useful for setting upper limits like maximum character levels. ```swift @Generable struct GameCharacter { @Guide(description: "A creative name appropriate for a fantasy RPG character") var name: String @Guide(description: "A level for the character", .maximum(100.0)) var level: Float } ``` -------------------------------- ### Swift: Define Array Count Range Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `count` generation guide with a closed range to ensure the number of elements in an array falls within specified bounds (inclusive). Useful for controlling the size of lists. ```swift public static func count(_ range: ClosedRange) -> GenerationGuide<[Element]> where Value == [Element] ``` -------------------------------- ### Prompt Initialization Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Initializes a Prompt with string literal content or dynamically using a PromptBuilder. ```APIDOC /// A prompt from a person to the model. /// /// Prompts can contain content written by you, an outside source, or input directly from people using /// your app. You can initialize a `Prompt` from a string literal: /// /// ```swift /// let prompt = Prompt("What are miniature schnauzers known for?") /// ``` /// /// Use ``PromptBuilder`` to dynamically control the prompt's content based on your app's state. The /// code below shows if the Boolean is `true`, the prompt includes a second line of text: /// /// ```swift /// let responseShouldRhyme = true /// let prompt = Prompt { /// "Answer the following question from the user: \(userInput)" /// if responseShouldRhyme { /// "Your response MUST rhyme!" /// } /// } /// ``` /// /// If your prompt includes input from people, consider wrapping the input in a string template with your /// own prompt to better steer the model's response. For more information on handling inputs in your /// prompts, see . @available(iOS 26.0, macOS 26.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable) public struct Prompt : Sendable { /// Creates an instance with the content you specify. public init(_ content: some PromptRepresentable) } @available(iOS 26.0, macOS 26.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable) extension Prompt { public init(@PromptBuilder _ content: () throws -> Prompt) rethrows } ``` -------------------------------- ### Swift: Define Range Generation Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use a `range` generation guide to ensure the model produces a value that falls within a specified closed range (inclusive). This is useful for setting bounds on properties like item costs. ```swift public static func range(_ range: ClosedRange) -> GenerationGuide ``` -------------------------------- ### Run Foundation Lab CLI Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/README.md Execute the `fm` CLI tool for local development or one-off responses. Ensure you are in the `FoundationLabCLI` directory. ```bash cd FoundationLabCLI && swift run fm --help ``` ```bash cd FoundationLabCLI && swift run fm session respond --dry-run --json --prompt "Suggest an uplifting science fiction novel" ``` -------------------------------- ### Initialize and Use LanguageModelSession Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/Agents.md Demonstrates how to initialize LanguageModelSession and use it for single-turn responses, streaming responses, and generating structured data. ```swift let session = LanguageModelSession() let response = try await session.respond(to: "Hello") let stream = session.streamResponse(to: "Write a story") let structured = try await session.respond(to: "Suggest a book", generating: BookRecommendation.self) ``` -------------------------------- ### Initialize LanguageModelSession with Instructions Builder Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Create a new session using an instructions builder closure. This provides a structured way to define complex instructions for the language model. ```swift public convenience init(model: SystemLanguageModel = .default, tools: [any Tool] = [], @InstructionsBuilder instructions: () throws -> Instructions) rethrows ``` -------------------------------- ### Prompt - Initializer with PromptBuilder Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Initializes a Prompt using a closure that returns a Prompt, enabling dynamic content construction via PromptBuilder. ```swift public init(@PromptBuilder _ content: () throws -> Prompt) rethrows ``` -------------------------------- ### GenerationGuide.pattern(_:) Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Creates a GenerationGuide for strings that enforces the string to follow a specified regular expression pattern. ```APIDOC /// Enforces that the string follows the pattern. public static func pattern(_ regex: Regex) -> GenerationGuide ``` -------------------------------- ### SystemLanguageModel Adapter Initialization Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Initializes an adapter for the SystemLanguageModel either from a file URL or by name from downloaded assets. ```APIDOC ## Initializing SystemLanguageModel Adapters ### Description Initializes an adapter for the SystemLanguageModel. This can be done either by providing a file URL to an adapter file or by specifying the name of a pre-downloaded adapter. ### Initializers #### `init(fileURL: URL) throws` Creates an adapter from the specified file URL. Throws `AssetLoadingError` if the `fileURL` is invalid. #### `init(name: String) throws` Creates an adapter downloaded from the background assets framework using its name. Throws `AssetLoadingError` if no compatible asset packs with the given adapter name are downloaded. ``` -------------------------------- ### Initialize Schema from Generable Type Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Creates a schema directly from a Swift type that conforms to the `Generable` protocol. Guides can be provided to influence generation. ```swift public init(type: Value.Type, guides: [GenerationGuide] = []) where Value : Generable ``` -------------------------------- ### Swift Instructions Struct Initialization Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Shows how to initialize the `Instructions` struct using a content closure that conforms to `InstructionsRepresentable`. Supports builder pattern for complex instructions. ```swift /// Creates an instance with the content you specify. public init(_ content: some InstructionsRepresentable) @available(iOS 26.0, macOS 26.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable) extension Instructions : InstructionsRepresentable { /// An instance that represents the instructions. public var instructionsRepresentation: Instructions { get } } @available(iOS 26.0, macOS 26.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable) extension Instructions { public init(@InstructionsBuilder _ content: () throws -> Instructions) rethrows } ``` -------------------------------- ### Create a Prompt from a String Literal Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Initialize a Prompt directly from a string literal for simple, static prompts. ```swift let prompt = Prompt("What are miniature schnauzers known for?") ``` -------------------------------- ### Instructions Structure Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Represents instructions for the model, including content and available tools. Provides an initializer to set up these instructions. ```APIDOC ## Instructions Structure ### Description Represents instructions for the model, including content and available tools. Provides an initializer to set up these instructions. ### Initializer `init(id: String = UUID().uuidString, segments: [Transcript.Segment], toolDefinitions: [Transcript.ToolDefinition])` Initializes instructions by describing how you want the model to behave using natural language. ### Parameters - **id** (String) - Optional - A unique identifier for this instructions segment. - **segments** ([Transcript.Segment]) - Required - An array of segments that make up the instructions. - **toolDefinitions** ([Transcript.ToolDefinition]) - Required - Tools that the model should be allowed to call. ``` -------------------------------- ### Prompt - Initializer with PromptRepresentable Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Creates a Prompt instance from any type that conforms to the PromptRepresentable protocol. ```swift public init(_ content: some PromptRepresentable) ``` -------------------------------- ### Tool Calling with LanguageModelSession Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/README.md Demonstrates how to integrate tools with LanguageModelSession for extended functionality. Supports single or multiple tools. ```swift // Single tool let weatherSession = LanguageModelSession(tools: [WeatherTool()]) let response = try await weatherSession.respond( to: "Is it hotter in New Delhi or Cupertino?" ) // Multiple tools let multiSession = LanguageModelSession(tools: [ WeatherTool(), Search1WebSearchTool(), ContactsTool() ]) let multiResponse = try await multiSession.respond( to: "Check the weather, search the web, and find my friend John's contact" ) ``` -------------------------------- ### GenerationGuide Range Int Guide Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Enforces that an Int value falls within a specified inclusive range. Use this to ensure generated integers are between two bounds. ```swift public static func range(_ range: ClosedRange) -> GenerationGuide ``` -------------------------------- ### fm CLI: Multi-turn Chat and Customization (Bash) Source: https://context7.com/rudrankriyam/foundation-models-framework-example/llms.txt Demonstrates multi-turn chat functionality with the `fm` CLI, including streaming responses, custom system prompts, greedy sampling, and setting maximum tokens. Use `--message` for each turn. ```bash # Multi-turn chat (three messages in one shared session) fm session chat \ --message "My name is Alex." \ --message "What's a good iOS architecture?" \ --message "Show me an MVVM example." \ --stream # With custom system prompt and greedy sampling fm session respond \ --prompt "Explain actors in Swift" \ --system-prompt "You are a senior Swift engineer. Be concise." \ --sampling greedy \ --max-tokens 200 \ --verbose ``` -------------------------------- ### Generable Data Model: BookRecommendation Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/README.md Defines a BookRecommendation struct marked with @Generable, specifying fields like title, author, and genre with @Guide annotations for constraints. ```swift @Generable struct BookRecommendation { @Guide(description: "The title of the book") let title: String @Guide(description: "The author's name") let author: String @Guide(description: "Genre of the book") let genre: Genre } ``` -------------------------------- ### Compiling and Managing Adapters Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Provides methods for compiling adapters, retrieving compatible adapter identifiers, and managing obsolete adapters. ```APIDOC ## Compiling and Managing Adapters ### Description This section covers operations related to preparing adapters for use, querying system compatibility, and cleaning up old adapters. ### Methods #### `compile() async throws` Prepares an adapter before it can be used with a `LanguageModelSession`. This method should be called if your adapter has a draft model. #### `static func compatibleAdapterIdentifiers(name: String) -> [String]` Retrieves all adapter identifiers that are compatible with the current system models. The identifiers are returned in descending order of system preference. This is useful for determining which asset pack or on-demand resource to download. - **Parameters**: - `name` (String): The name of the adapter. - **Returns**: An array of strings, where each string is a compatible adapter identifier. #### `static func removeObsoleteAdapters() throws` Removes all adapters that are no longer compatible with the current system models. This operation can throw an error if adapter removal fails. ``` -------------------------------- ### GenerationGuide for Array Element Constraints Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md This extension provides static methods for GenerationGuide to enforce constraints on array elements, such as minimum/maximum count and specific ranges. These are primarily for macro expansion. ```swift public static func element(_ guide: GenerationGuide) -> GenerationGuide<[Element]> where Value == [Element] ``` -------------------------------- ### Initialize Object Schema with Properties Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use this initializer to create an object schema with explicit nil representation control and a list of properties. ```swift public init(name: String, description: String? = nil, representNilExplicitlyInGeneratedContent explicitNil: Bool, properties: [DynamicGenerationSchema.Property]) ``` -------------------------------- ### Annotate Struct with @Generable Macro Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use the `@Generable` macro to allow the model to generate instances of your Swift struct. The `@Guide` macro can be used on properties for descriptions and generation control. ```swift @Generable struct SearchSuggestions { @Guide(description: "A list of suggested search terms", .count(4)) var searchTerms: [SearchTerm] @Generable struct SearchTerm { // Use a generation identifier for data structures the framework generates. var id: GenerationID @Guide(description: "A 2 or 3 word search term, like 'Beautiful sunsets'") var searchTerm: String } } ``` -------------------------------- ### SystemLanguageModel.tokenCount(for:) Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Calculates the token count for a given set of instructions. ```APIDOC ## SystemLanguageModel.tokenCount(for:) ### Description Calculates the number of tokens required to represent the provided instructions. ### Method `nonisolated(nonsending) final public func tokenCount(for instructions: Instructions) async throws -> Int` ### Parameters - **instructions** (Instructions) - The instructions for which to calculate the token count. ### Returns `Int` - The total token count for the instructions. ### Throws An error if the token count cannot be determined. ### Availability - iOS 26.4+ - macOS 26.4+ - tvOS unavailable - watchOS unavailable ``` -------------------------------- ### Generable Data Model: ProductReview Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/README.md Defines a ProductReview struct marked with @Generable, including fields for product name, rating, pros, and cons, with @Guide annotations for specific field descriptions. ```swift @Generable struct ProductReview { @Guide(description: "Product name") let productName: String @Guide(description: "Rating from 1 to 5") let rating: Int @Guide(description: "Key pros and cons") let pros: [String] let cons: [String] } ``` -------------------------------- ### SystemLanguageModel Use Cases Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Illustrates how to specify different use cases for the SystemLanguageModel, such as general prompting or content tagging. ```APIDOC ## SystemLanguageModel Use Cases ### Description The `SystemLanguageModel` can be initialized with specific `UseCase` values to tailor its behavior for different tasks. The `general` use case is the default. ### Use Case Definitions - `SystemLanguageModel.UseCase.general`: For general-purpose text generation. This is the default if no use case is specified. - `SystemLanguageModel.UseCase.contentTagging`: For tasks that require generating a list of categorizing tags based on the input prompt. The model will always respond with tags when this use case is specified. ### Example Usage (Conceptual) ```swift // Using the default general use case let generalModel = SystemLanguageModel.default // Using the contentTagging use case let taggingModel = SystemLanguageModel(useCase: .contentTagging) ``` ### Note When using `SystemLanguageModel.default`, you do not need to explicitly specify the `UseCase` as it defaults to `.general`. ``` -------------------------------- ### Generate JSON output from CLI Source: https://context7.com/rudrankriyam/foundation-models-framework-example/llms.txt Use the 'fm session respond' command with the '--json' flag to get structured output suitable for scripting. The 'jq' tool can then parse this JSON. ```bash fm session respond --prompt "List 3 Swift tips" --json | jq '.response' ``` -------------------------------- ### SwiftUI View for Streaming Responses with GenerationID Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md An example SwiftUI View that streams responses from a LanguageModelSession and displays a list of 'Person' objects. It uses GenerationID to ensure stable identification of list items. ```swift struct PeopleView: View { @State private var session = LanguageModelSession() @State private var people = [Person.PartiallyGenerated]() var body: some View { // A person's name changes as the response is generated, // and two people can have the same name, so it is not suitable // for use as an id. // // `GenerationID` receives special treatment and is guaranteed // to be both present and stable. List { ForEach(people) { person in Text("Name: \(person.name)") } } .task { for try! await people in stream.streamResponse( to: "Who were the first 3 presidents of the US?", generating: [Person].self ) { withAnimation { self.people = people } } } } } ``` -------------------------------- ### Convert Dynamic Schema to GenerationSchema Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/Foundation Lab/Views/Examples/DynamicSchemas/README.md Demonstrates the conversion of a dynamically created schema, including its dependencies, into a static GenerationSchema. ```swift let schema = try GenerationSchema( root: rootSchema, dependencies: [schema1, schema2, ...] ) ``` -------------------------------- ### Define a Generatable Struct with Array Element Constraints Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Use the @Generable macro to define custom data structures. Specify constraints on array elements, such as their type, range, and count, using the @Guide attribute. ```swift @Generable struct FortuneCookie { @Guide(description: "A fortune from a fortune cookie") var name: String @Guide(description: "A list lucky numbers", .element(.range(0...9)), .count(4)) var luckyNumbers: [Int] } ``` -------------------------------- ### PromptBuilder - buildLimitedAvailability Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Creates a Prompt from a component that may have limited availability, ensuring compatibility. ```swift public static func buildLimitedAvailability(_ prompt: some PromptRepresentable) -> Prompt ``` -------------------------------- ### Create Basic Object Schema Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/Foundation Lab/Views/Examples/DynamicSchemas/README.md Demonstrates the creation of a simple object schema with a String property using DynamicGenerationSchema. ```swift let schema = DynamicGenerationSchema( name: "Person", description: "A person", properties: [ DynamicGenerationSchema.Property( name: "name", description: "Full name", schema: .init(type: String.self) ) ] ) ``` -------------------------------- ### Swift: Decimal Generable Conformance Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/fmf.md Provides static `generationSchema` and an initializer `init(_:)` for `Decimal` conforming to `Generable`. Manual implementation of `generatedContent` is also shown. ```swift extension Decimal : Generable { /// An instance of the generation schema. public static var generationSchema: GenerationSchema { get } /// Creates an instance from content generated by a model. /// /// Conformance to this protocol is provided by the `@Generable` macro. /// A manual implementation may be used to map values onto properties using /// different names. To manually initialize your type from generated content, /// decode the values as shown below: /// /// ```swift /// struct Person: ConvertibleFromGeneratedContent { /// var name: String /// var age: Int /// /// init(_ content: GeneratedContent) { /// self.name = try content.value(forProperty: "firstName") /// self.age = try content.value(forProperty: "ageInYears") /// } /// } /// ``` /// /// - Important: If your type also conforms to ``ConvertibleToGeneratedContent``, /// it is critical that this implementation be symmetrical with ``ConvertibleToGeneratedContent/generatedContent``. /// /// - SeeAlso: `@Generable` macro ``Generable(description:)`` public init(_ content: GeneratedContent) throws /// This instance represented as generated content. /// /// Conformance to this protocol is provided by the `@Generable` macro. /// A manual implementation may be used to map values onto properties using /// different names. Use the generated content property as shown below, to /// manually return a new ``GeneratedContent`` with the properties you specify. /// /// ```swift /// struct Person: ConvertibleToGeneratedContent { /// var name: String /// var age: Int /// /// var generatedContent: GeneratedContent { /// GeneratedContent(properties: [ /// "firstName": name, /// "ageInYears": age /// ]) /// } /// } /// ``` /// /// - Important: If your type also conforms to ``ConvertibleFromGeneratedContent``, /// it is critical that this implementation be symmetrical with ``ConvertibleFromGeneratedContent/init(_:)``. public var generatedContent: GeneratedContent { get } ``` -------------------------------- ### Generate Homebrew Formula Source: https://github.com/rudrankriyam/foundation-models-framework-example/blob/main/README.md Use this script to prepare for Homebrew releases by generating the necessary formula. Replace `` with the desired version tag. ```bash ./Scripts/generate-homebrew-formula.sh ```