### Prompting with Reasoning Instructions Source: https://developer.apple.com/documentation/foundationmodels/prompting-an-on-device-foundation-model Prompt the model with instructions that guide it to first plan, then execute steps, and finally provide the answer. This example uses a `ReasonableAnswer` structure to capture the output. ```swift let instructions = """ Answer the person's question. 1. Begin your response with a plan to solve this question. 2. Follow your plan's steps and show your work. 3. Deliver the final answer in `answer`. """ var session = LanguageModelSession(instructions: instructions) // The answer should be 30 days. let prompt = "How many days are in the month of September?" let response = try await session.respond( to: prompt, generating: ReasonableAnswer.self ) ``` -------------------------------- ### PresentationInstructions Example Source: https://developer.apple.com/documentation/foundationmodels/dynamicinstructions An example of implementing DynamicInstructions with conditional logic for image editing. ```swift struct PresentationInstructions: DynamicInstructions { // The data source for conditional instructions. var isEditingImage = true var body: some DynamicInstructions { // The instructions and tools that remain the same across any use of this type. Instructions { "Help people improve their presentation." } ListPhotosTool() AddPhotoTool() // Depending on the state of the app, include additional instructions // that provide the model with more task-specific instructions and tools. if isEditingImage { ImageEditingInstructions() } } } ``` -------------------------------- ### init(name:description:type:guides:) Source: https://developer.apple.com/documentation/foundationmodels/generationschema/property/init%28name%3Adescription%3Atype%3Aguides%3A%29 Creates a property that contains a string type. This initializer is available on iOS, iPadOS, Mac Catalyst, macOS, visionOS, and watchOS starting from specific versions. ```APIDOC ## init(name:description:type:guides:) ### Description Create a property that contains a string type. ### Parameters `name` The property’s name. `description` A natural language description of what content should be generated for this property. `type` The type this property represents. `guides` An array of regexes to be applied to this string. If there’re multiple regexes in the array, only the last one will be applied. ### Declaration ```swift init( name: String, description: String? = nil, type: String.Type, guides: [Regex] = [] ) ``` ``` -------------------------------- ### init(type:guides:) Source: https://developer.apple.com/documentation/foundationmodels/dynamicgenerationschema/init%28type%3Aguides%3A%29 Creates a schema from a generable type and guides. Available on iOS, iPadOS, Mac Catalyst, macOS, visionOS 26.0+ and watchOS 27.0+. ```APIDOC ## init(type:guides:) ### Description Creates a schema from a generable type and guides. ### Parameters #### Parameters - **type** (`Value.Type`) - Required - A `Generable` type. - **guides** (`[GenerationGuide]`) - Optional - Generation guides to apply to this `DynamicGenerationSchema`. ### Generable Constraint `Value` must conform to `Generable`. ``` -------------------------------- ### Guide Macro Declaration Source: https://developer.apple.com/documentation/foundationmodels/guide%28description%3A%29 This is the declaration of the `Guide` macro. It takes a single String parameter named 'description'. ```swift @attached(peer) macro Guide(description: String) ``` -------------------------------- ### Few-Shot Prompting with Structured Examples Source: https://developer.apple.com/documentation/foundationmodels/prompting-an-on-device-foundation-model Use few-shot prompting by providing the model with examples of desired output structures. This example demonstrates creating NPC customers with specific fields like name, image description, and coffee order. ```swift let instructions = """ Create an NPC customer with a fun personality suitable for the dream realm. \ Have the customer order coffee. Here are some examples to inspire you: {name: "Thimblefoot", imageDescription: "A horse with a rainbow mane", \ coffeeOrder: "I would like a coffee that's refreshing and sweet, like the grass in a summer meadow."} {name: "Spiderkid", imageDescription: "A furry spider with a cool baseball cap", \ coffeeOrder: "An iced coffee please, that's as spooky as I am!"} {name: "Wise Fairy", imageDescription: "A blue, glowing fairy that radiates wisdom and sparkles", \ coffeeOrder: "Something simple and plant-based, please. A beverage that restores my wise energy."} """ ``` -------------------------------- ### Using minimum(_:) for Character Level Source: https://developer.apple.com/documentation/foundationmodels/generationguide/minimum%28_%3A%29 Example of using the .minimum() guide with the @Guide macro to enforce a minimum level of 0.75 for a GameCharacter's level property. ```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 } ``` -------------------------------- ### Guide Macro Declaration Source: https://developer.apple.com/documentation/foundationmodels/guide%28description%3A_%3A%29 This is the declaration for the Guide macro, which takes an optional description and a Regex for guiding generable types. ```swift @attached(peer) macro Guide( description: String? = nil, _ guides: Regex ) ``` -------------------------------- ### Transcript.Entry.instructions(_:) Source: https://developer.apple.com/documentation/foundationmodels/transcript/entry/instructions%28_%3A%29 Represents developer-provided instructions for a transcript entry. Use this case when you need to guide the model's behavior or output. ```swift case instructions(Transcript.Instructions) ``` -------------------------------- ### Initialize DynamicGenerationSchema with Type and Guides Source: https://developer.apple.com/documentation/foundationmodels/dynamicgenerationschema/init%28type%3Aguides%3A%29 Use this initializer to create a schema for a specific `Generable` type, optionally providing custom generation guides. This is the primary way to define the structure and behavior of a dynamic schema. ```swift init( type: Value.Type, guides: [GenerationGuide] = [] ) where Value : Generable ``` -------------------------------- ### LanguageModelError.unsupportedGenerationGuide(_:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelerror/unsupportedgenerationguide%28_%3A%29 An unsupported generation guide was used. This error occurs if you attempt to use generation guides that a model does not support. For example, many models don’t support certain guides using certain regex patterns. ```APIDOC ## LanguageModelError.unsupportedGenerationGuide(_:) ### Description An unsupported generation guide was used. This error occurs if you attempt to use generation guides that a model does not support. For example, many models don’t support certain guides using certain regex patterns. ### Case ```swift case unsupportedGenerationGuide(LanguageModelError.UnsupportedGenerationGuide) ``` ### See Also - `struct UnsupportedGenerationGuide`: Information about an unsupported generation guide. ``` -------------------------------- ### init(_:) Source: https://developer.apple.com/documentation/foundationmodels/instructions/init%28_%3A%29 Initializes a new instance of Instructions using a content closure that builds the instructions. ```APIDOC ## init(_:) ### Description Initializes a new instance of Instructions using a content closure that builds the instructions. ### Method Initializer ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response Initializes an Instructions object. #### Response Example N/A ``` -------------------------------- ### init(model:tools:instructions:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelsession/init%28model%3Atools%3Ainstructions%3A%29 Starts a new session in a blank slate state with instructions builder. This initializer allows for customization of the language model, available tools, and initial instructions for the model's behavior. ```APIDOC ## init(model:tools:instructions:) ### Description Starts a new session in a blank slate state with instructions builder. ### Parameters - **model** (SystemLanguageModel) - The language model to use for this session. Defaults to `.default`. - **tools** ([any Tool]) - Tools to make available to the model for this session. Defaults to an empty array. - **instructions** (() throws -> Instructions) - Instructions that control the model’s behavior. This parameter uses the `@InstructionsBuilder` attribute. ``` -------------------------------- ### init(schemaName:debugDescription:metadata:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelerror/unsupportedgenerationguide/init%28schemaname%3Adebugdescription%3Ametadata%3A%29 Initializes an UnsupportedGenerationGuide error with optional schema name, a required debug description, and optional metadata. ```APIDOC ## init(schemaName:debugDescription:metadata:) ### Description Initializes an `UnsupportedGenerationGuide` error. This initializer is used to create specific error instances when a generation process is not supported, providing details for debugging. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **schemaName** (String?) - Optional. The name of the schema associated with the error. - **debugDescription** (String) - Required. A detailed description of the error for debugging purposes. - **metadata** ([String : any Sendable] = [:]) - Optional. A dictionary containing additional metadata for the error. Defaults to an empty dictionary. ### Request Example ```swift let error = LanguageModelError.UnsupportedGenerationGuide(schemaName: "mySchema", debugDescription: "Generation failed due to unsupported parameters.") ``` ### Response #### Success Response This is an initializer, not an endpoint that returns a response. #### Response Example N/A ``` -------------------------------- ### Shop Struct with maximumCount Guide Source: https://developer.apple.com/documentation/foundationmodels/generationguide/maximumcount%28_%3A%29 This example shows how to use the .maximumCount(10) guide to limit the 'inventory' array to a maximum of 10 ShopItem elements. The bounds are inclusive. ```swift @Generable struct Shop { @Guide(description: "A creative name for a shop in a fantasy RPG") var name: String @Guide(description: "A list of items for sale", .maximumCount(10)) var inventory: [ShopItem] } ``` -------------------------------- ### Defining a Generable Structure for Guided Generation Source: https://developer.apple.com/documentation/foundationmodels/prompting-an-on-device-foundation-model Define a Swift struct conforming to `@Generable` to guide the model's output format. This example defines an `NPC` structure for customer data. ```swift @Generable struct NPC: Equatable { let name: String let coffeeOrder: String let imageDescription: String } ``` -------------------------------- ### init(_:) Source: https://developer.apple.com/documentation/foundationmodels/anydynamicinstructions/init%28_%3A%29 Creates an instance of AnyDynamicInstructions from the dynamic instructions you specify. ```APIDOC ## init(_:) ### Description Creates an instance from the dynamic instructions you specify. ### Method initializer ### Parameters #### Parameters - **dynamicInstructions** (any DynamicInstructions) - The dynamic instructions. ``` -------------------------------- ### Defining a Tool with Parameters for Efficient Tool Calling Source: https://developer.apple.com/documentation/foundationmodels/managing-the-context-window Define a Tool with clear descriptions for the tool itself and its parameters using @Guide. This provides the model with context for making informed tool calls. ```swift @Observable final class FindPointsOfInterestTool: Tool { let name = "findPointsOfInterest" let description = "Finds points of interest for a landmark." @Generable enum Category: String, CaseIterable { case campground case hotel case cafe case museum case marina case restaurant case nationalMonument } @Generable struct Arguments { @Guide(description: "The type of destination to look up.") let pointOfInterest: Category @Guide(description: "The natural language query of what to search for.") let naturalLanguageQuery: String } func call(arguments: Arguments) async throws -> String { // Implement the logic your app needs when the model calls this tool. } } ``` -------------------------------- ### Applying Generable Macro to a Struct Source: https://developer.apple.com/documentation/foundationmodels/generable%28description%3A%29 Example of applying the Generable macro to a Swift struct named NovelIdea. Properties like title, subtitle, and genre are marked with the @Guide attribute for guided generation. ```swift @Generable struct NovelIdea { @Guide(description: "A short title") let title: String @Guide(description: "A short subtitle for the novel") let subtitle: String @Guide(description: "The genre of the novel") let genre: Genre } ``` -------------------------------- ### Getting the Generation Schema Source: https://developer.apple.com/documentation/foundationmodels/generable Provides an instance of the generation schema, which describes the properties of an object and guides on their values. ```swift static var generationSchema: GenerationSchema ``` -------------------------------- ### Initialize a session with instructions and make a prompt Source: https://developer.apple.com/documentation/foundationmodels/generating-content-and-performing-tasks-with-foundation-models This snippet shows how to initialize a LanguageModelSession with specific instructions and then use it to respond to a prompt. The instructions guide the model's output format and content. ```swift let instructions = """ Suggest five 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) ``` -------------------------------- ### Example Usage of element(_:) with Array Guides Source: https://developer.apple.com/documentation/foundationmodels/generationguide/element%28_%3A%29 Demonstrates how to use the element(_:) guide within a @Generable struct to specify constraints for elements in an array. Here, luckyNumbers are integers between 0 and 9, and the array must contain exactly 4 elements. ```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] } ``` -------------------------------- ### Creating a Property Source: https://developer.apple.com/documentation/foundationmodels/generationschema/property Use this initializer to create a property with a string type. It accepts a name, an optional description, and an optional array of guides. ```swift init(name:description:type:guides:) ``` -------------------------------- ### init(_:) Source: https://developer.apple.com/documentation/foundationmodels/conditionaldynamicinstructions/init%28_%3A%29 Creates a dynamic instructions instance that selects between two conditions based on the provided branch. ```APIDOC ## init(_:) ### Description Creates a dynamic instructions instance that selects between two conditions. ### Method initializer ### Parameters #### Parameters - **branch** (ConditionalDynamicInstructions.Branch) - Required - The condition to evaluate. ``` -------------------------------- ### Initialize Instructions Source: https://developer.apple.com/documentation/foundationmodels/transcript/instructions/init%28id%3Asegments%3Atooldefinitions%3A%29 Use this initializer to set up instructions for a model, providing a unique ID, an array of segments, and a list of allowed tool definitions. ```swift init( id: String = UUID().uuidString, segments: [Transcript.Segment], toolDefinitions: [Transcript.ToolDefinition] ) ``` -------------------------------- ### Get CIImage from Image Attachment Source: https://developer.apple.com/documentation/foundationmodels/transcript/imageattachment/ciimage Access the image attachment as a CIImage object. This property is available in beta versions of iOS, iPadOS, Mac Catalyst, macOS, and visionOS starting from version 27.0. ```swift var ciImage: CIImage { get } ``` -------------------------------- ### Initializer Signature for UnsupportedGenerationGuide Source: https://developer.apple.com/documentation/foundationmodels/languagemodelerror/unsupportedgenerationguide/init%28schemaname%3Adebugdescription%3Ametadata%3A%29 This is the signature for the `init(schemaName:debugDescription:metadata:)` initializer. It is available for various Apple platforms starting from iOS 27.0. ```swift init( schemaName: String?, debugDescription: String, metadata: [String : any Sendable] = [:] ) ``` -------------------------------- ### Declare a maximum value for a Decimal property Source: https://developer.apple.com/documentation/foundationmodels/generationguide/maximum%28_%3A%29 Use the `maximum(_:)` generation guide to ensure a generated `Decimal` value does not exceed a specified maximum. This example sets the maximum level for a game character to 99.9. ```swift static func maximum(_ value: Decimal) -> GenerationGuide ``` ```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 } ``` -------------------------------- ### init(input:output:metadata:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelsession/usage-swift.struct/init%28input%3Aoutput%3Ametadata%3A%29 Creates a usage value with the given token counts for input, output, and optional metadata. ```APIDOC ## init(input:output:metadata:) ### Description Creates a usage value with the given token counts. ### Parameters `input` Token counts for the transcript. `output` Token counts for the response. `metadata` Additional usage statistics from the language model. ``` -------------------------------- ### Debug Description Property Source: https://developer.apple.com/documentation/foundationmodels/generatedcontent/parsingerror/debugdescription Use this property to get a string that describes the specific reason a parsing operation failed. Available on iOS, iPadOS, macOS, visionOS, and watchOS starting from version 27.0 (Beta). ```swift var debugDescription: String ``` -------------------------------- ### init() Source: https://developer.apple.com/documentation/foundationmodels/languagemodelexecutorgenerationchannel/init%28%29 Creates a new generation channel instance. ```APIDOC ## init() ### Description Creates a new generation channel instance. ### Method initializer ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```swift LanguageModelExecutorGenerationChannel.init() ``` ### Response ### Success Response - **Instance** (LanguageModelExecutorGenerationChannel) - A new generation channel instance. ``` -------------------------------- ### Generate an NPC with a Language Model Session Source: https://developer.apple.com/documentation/foundationmodels/generate-dynamic-game-content-with-guided-generation-and-tools Demonstrates how to use a `LanguageModelSession` to generate an `NPC` object. The prompt includes a description of the game setting, the role of the assistant, and examples of desired NPC output to guide the generation. ```swift let session = LanguageModelSession { """ A conversation between the Player and a helpful assistant. This is a fantasy RPG game that takes place at Dream Coffee, the beloved coffee shop of the dream realm. Your role is to use your imagination to generate fun game characters. """ } let prompt = """ Create an NPC customer with a fun personality suitable for the dream realm. Have the customer order coffee. Here are some examples to inspire you: {name: "Thimblefoot", imageDescription: "A horse with a rainbow mane", coffeeOrder: "I would like a coffee that's refreshing and sweet like grass of a summer meadow"} {name: "Spiderkid", imageDescription: "A furry spider with a cool baseball cap", coffeeOrder: "An iced coffee please, that's as spooky as me!"} {name: "Wise Fairy", imageDescription: "A blue glowing fairy that radiates wisdom and sparkles", coffeeOrder: "Something simple and plant-based please, that will restore my wise energy."} " // Generate the NPC using the custom generable type. let npc = try await session.respond( to: prompt, generating: NPC.self, ).content ``` -------------------------------- ### Initialize Prompt with Full Options Source: https://developer.apple.com/documentation/foundationmodels/transcript/prompt/init%28id%3Ametadata%3Asegments%3Aoptions%3Aresponseformat%3Acontextoptions%3A%29 Use this initializer to create a prompt with all available configuration options, including custom ID, metadata, segments, generation options, response format, and context options. Default values are provided for most parameters. ```swift init( id: String = UUID().uuidString, metadata: [String : any Codable & Sendable & Equatable] = [:], segments: [Transcript.Segment], options: GenerationOptions = GenerationOptions(), responseFormat: Transcript.ResponseFormat? = nil, contextOptions: ContextOptions = ContextOptions() ) ``` -------------------------------- ### Get JSON String Representation of Generated Content Source: https://developer.apple.com/documentation/foundationmodels/generatedcontent/jsonstring Use the jsonString property to obtain a JSON string representation of a GeneratedContent object. This example shows how to create a GeneratedContent object with properties and then print its JSON string. ```swift var jsonString: String { get } ``` ```swift let content = GeneratedContent(properties: [ "name": "Johnny Appleseed", "age": 30, ]) print(content.jsonString) // Output: {"name": "Johnny Appleseed", "age": 30} ``` -------------------------------- ### init(id:metadata:segments:options:responseFormat:contextOptions:) Source: https://developer.apple.com/documentation/foundationmodels/transcript/prompt/init%28id%3Ametadata%3Asegments%3Aoptions%3Aresponseformat%3Acontextoptions%3A%29 Creates a prompt with specified ID, metadata, segments, generation options, response format, and context options. ```APIDOC ## init(id:metadata:segments:options:responseFormat:contextOptions:) ### Description Creates a prompt with specified ID, metadata, segments, generation options, response format, and context options. ### Parameters #### Parameters - **id** (String) - Optional - A `Generable` type to use as the response format. Defaults to `UUID().uuidString`. - **metadata** ([String : any Codable & Sendable & Equatable]) - Optional - Metadata provided as part of this prompt. Defaults to an empty dictionary `[:]`. - **segments** ([Transcript.Segment]) - Required - An array of segments that make up the prompt. - **options** (GenerationOptions) - Optional - Options that control how tokens are sampled from the distribution the model produces. Defaults to `GenerationOptions()`. - **responseFormat** (Transcript.ResponseFormat?) - Optional - A response format that describes the output structure. - **contextOptions** (ContextOptions) - Optional - Settings that configure how the model is prompted. Defaults to `ContextOptions()`. ``` -------------------------------- ### init(useCase:guardrails:) Source: https://developer.apple.com/documentation/foundationmodels/systemlanguagemodel/init%28usecase%3Aguardrails%3A%29 Creates a SystemLanguageModel instance for a specific use case, with optional guardrails for content filtering. ```APIDOC ## init(useCase:guardrails:) ### Description Creates a `SystemLanguageModel` for a specific use case. ### Method `convenience init` ### Parameters #### Parameters - **useCase** (`SystemLanguageModel.UseCase`) - Optional - Defaults to `.general`. Represents the use case for prompting. - **guardrails** (`SystemLanguageModel.Guardrails`) - Optional - Defaults to `Guardrails.default`. Flags sensitive content from model input and output. ### See Also - `struct UseCase`: A type that represents the use case for prompting. - `struct Guardrails`: Guardrails flag sensitive content from model input and output. ``` -------------------------------- ### Unsupported Generation Guide Error Source: https://developer.apple.com/documentation/foundationmodels/languagemodelerror Indicates that an invalid or unsupported generation guide was provided with the request. Verify the format and validity of generation guides. ```swift case unsupportedGenerationGuide(LanguageModelError.UnsupportedGenerationGuide) ``` ```swift struct UnsupportedGenerationGuide ``` -------------------------------- ### init(debugDescription:) Source: https://developer.apple.com/documentation/foundationmodels/privatecloudcomputelanguagemodel/error/networkfailure/init%28debugdescription%3A%29 Initializes a `NetworkFailure` error with a provided debug description string. This is a beta API and subject to change. ```APIDOC ## init(debugDescription:) ### Description Initializes a `NetworkFailure` error with a provided debug description string. This method is available on iOS, iPadOS, Mac Catalyst, macOS, visionOS, and watchOS starting from version 27.0. ### Parameters #### Path Parameters - **debugDescription** (String) - Description of the error for debugging purposes. ### Method Initializer ### Endpoint N/A (This is an SDK method, not an HTTP endpoint) ### Request Example ```swift let networkError = PrivateCloudComputeLanguageModel.Error.NetworkFailure(debugDescription: "Failed to establish connection.") ``` ### Response N/A (Initializers do not have traditional responses like API endpoints.) ### Beta Software This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software. ``` -------------------------------- ### Generation guide unsupported error Source: https://developer.apple.com/documentation/foundationmodels/languagemodelerror/unsupportedgenerationguide An unsupported generation guide was used. ```APIDOC ## Case: unsupportedGenerationGuide An unsupported generation guide was used. ### Declaration ```swift case unsupportedGenerationGuide(LanguageModelError.UnsupportedGenerationGuide) ``` ``` -------------------------------- ### Creating a prompt with context options Source: https://developer.apple.com/documentation/foundationmodels/transcript/prompt Initializes a new prompt with additional context options, suitable for advanced configurations. This initializer is marked as Beta. ```APIDOC ## init(id: String, metadata: [String : any Codable & Sendable & Equatable], segments: [Transcript.Segment], options: GenerationOptions, responseFormat: Transcript.ResponseFormat?, contextOptions: ContextOptions) ### Description Creates a prompt with a unique identifier, metadata, content segments, generation options, an optional response format, and specific context options. This initializer is in Beta. ### Parameters #### Path Parameters - **id** (String) - Required - The identifier of the prompt. - **metadata** ([String : any Codable & Sendable & Equatable]) - Required - Metadata provided as part of this prompt. - **segments** ([Transcript.Segment]) - Required - Ordered prompt segments. - **options** (GenerationOptions) - Required - Generation options associated with the prompt. - **responseFormat** (Transcript.ResponseFormat?) - Optional - An optional response format that describes the desired output structure. - **contextOptions** (ContextOptions) - Required - Configuration of the prompt. This parameter is in Beta. ``` -------------------------------- ### init(_:) Source: https://developer.apple.com/documentation/foundationmodels/tupledynamicinstructions/init%28_%3A%29 Creates a dynamic instructions instance that represents a tuple. This initializer takes a variable number of elements that form the tuple. ```APIDOC ## init(_:) ### Description Creates a dynamic instructions instance that represents a tuple. ### Method Initializer ### Signature ```swift init(_ contents: repeat each Content) ``` ### Parameters #### Parameters - **contents** (repeat each Content) - The elements of the tuple. ``` -------------------------------- ### Initialize Session with a Tool Source: https://developer.apple.com/documentation/foundationmodels/expanding-generation-with-tool-calling Initialize a session with a list of relevant tools. These tools become available for all subsequent interactions within that session. ```swift let session = LanguageModelSession( tools: [searchTool], // ... other session configurations ) ``` -------------------------------- ### Enforce Array Element Guide Source: https://developer.apple.com/documentation/foundationmodels/generationguide Applies a generation guide to each element within an array. Use this to constrain the properties of array items. ```swift static func element(GenerationGuide) -> GenerationGuide<[Element]> ``` -------------------------------- ### init(category:explanation:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelfeedback/issue/init%28category%3Aexplanation%3A%29 Creates a new issue with a specified category and an optional explanation. ```APIDOC ## init(category:explanation:) ### Description Creates a new issue with a specified category and an optional explanation. ### Parameters #### Parameters - **category** (LanguageModelFeedback.Issue.Category) - Required - A category for this issue. - **explanation** (String?) - Optional - An optional explanation of this issue. ``` -------------------------------- ### Creating a property Source: https://developer.apple.com/documentation/foundationmodels/generationschema/property Initializes a Property object with a name, description, type, and optional guides. This initializer is used to create properties that contain a string type. ```APIDOC ## `init(name:description:type:guides:)` ### Description Creates a property that contains a string type. ### Parameters - **name** (String) - The name of the property. - **description** (String) - The description of the property. - **type** (String) - The type of the property, expected to be a string. - **guides** (Array?) - Optional array of guides associated with the property. ``` -------------------------------- ### Handle Model Refusals with Guided Generation Source: https://developer.apple.com/documentation/foundationmodels/improving-the-safety-of-generative-model-output Catch `LanguageModelSession.GenerationError.refusal(_:_:)` when the model refuses a request during guided generation. Retrieve an asynchronous explanation for the refusal to display to the user. ```swift do { let session = LanguageModelSession() let topic = "" // A sensitive topic. let response = try session.respond( to: "List five key points about: \(topic)", generating: [String].self ) } catch LanguageModelSession.GenerationError.refusal(let refusal, _) { // Generate an explanation for the refusal. if let message = try? await refusal.explanation { // Display the refusal message. } } ``` -------------------------------- ### init(name:description:parameters:) Source: https://developer.apple.com/documentation/foundationmodels/transcript/tooldefinition/init%28name%3Adescription%3Aparameters%3A%29 Initializes a new tool definition with a name, description, and generation schema parameters. This is a Swift initializer for creating tool definitions. ```APIDOC ## init(name:description:parameters:) ### Description Initializes a new tool definition with a name, description, and generation schema parameters. ### Parameters #### Path Parameters - **name** (String) - Required - The name of the tool. - **description** (String) - Required - A description of the tool's purpose. - **parameters** (GenerationSchema) - Required - The schema defining the parameters for generation. ``` -------------------------------- ### Create Generation Guide with Description Source: https://developer.apple.com/documentation/foundationmodels/generationguide A macro used to influence the allowed values of properties within a generable type, providing a description for the guide. Available in Beta. ```swift `macro Guide(description: String)` ``` -------------------------------- ### init(id:segments:toolDefinitions:) Source: https://developer.apple.com/documentation/foundationmodels/transcript/instructions/init%28id%3Asegments%3Atooldefinitions%3A%29 Initializes instructions by describing how you want the model to behave using natural language, providing a unique identifier, an array of segments, and a list of tools the model can call. ```APIDOC ## init(id:segments:toolDefinitions:) ### Description Initializes instructions by describing how you want the model to behave using natural language. This initializer allows for specifying a unique ID, an array of segments that form the instructions, and the tools the model should be permitted to call. ### Parameters #### Parameters - **id** (String) - Optional - A unique identifier for this instructions segment. Defaults to a new UUID. - **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. ``` -------------------------------- ### CompactingProfile Example Source: https://developer.apple.com/documentation/foundationmodels/sessionpropertyvalues An example of a CompactingProfile that demonstrates how to access and modify session history to manage the context window. It shows how to compact the history when entries exceed a certain limit. ```swift struct CompactingProfile: LanguageModelSession.DynamicProfile { @SessionProperty(\. history) var history var body: some LanguageModelSession.DynamicProfile { Profile { // Custom instructions and tools that you define. } .onResponse { _ in // Compact the history when the entries exceed a certain limit. if history.count > 100 { history = Array(history.suffix(50)) } } } } ``` -------------------------------- ### init(_:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelsession/profile/init%28_%3A%29 Creates a profile that contains dynamic instructions. This initializer is available for iOS, iPadOS, Mac Catalyst, macOS, and visionOS, starting from version 27.0. ```APIDOC ## init(_:) ### Description Creates a profile that contains dynamic instructions. ### Parameters #### dynamicInstructions - **dynamicInstructions** (some DynamicInstructions) - Required - The dynamic instructions. ``` -------------------------------- ### init(_:) Source: https://developer.apple.com/documentation/foundationmodels/prompt/init%28_%3A%29 Initializes a new Prompt using a closure that builds the prompt content. This initializer is available on iOS, iPadOS, Mac Catalyst, macOS, visionOS, and watchOS. ```APIDOC ## init(_:) ### Description Initializes a new Prompt using a closure that builds the prompt content. This initializer is available on iOS, iPadOS, Mac Catalyst, macOS, visionOS, and watchOS. ### Method `init(@PromptBuilder _ content: () throws -> Prompt) rethrows` ### Parameters #### Closure Parameter - **content** (`() throws -> Prompt`) - Required - A closure that returns a `Prompt` and can throw an error. It is annotated with `@PromptBuilder`. ### Throws This initializer can throw an error if the `content` closure throws an error. ``` -------------------------------- ### options Source: https://developer.apple.com/documentation/foundationmodels/transcript/prompt/options Generation options associated with the prompt. This property is available on iOS, iPadOS, Mac Catalyst, macOS, visionOS starting from version 26.0, and watchOS starting from version 27.0. ```APIDOC ## Instance Property # options Generation options associated with the prompt. iOS 26.0+iPadOS 26.0+Mac Catalyst 26.0+macOS 26.0+visionOS 26.0+watchOS 27.0+ ```swift var options: GenerationOptions ``` ``` -------------------------------- ### init(capabilities:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelcapabilities/init%28capabilities%3A%29 Initializes LanguageModelCapabilities with a specified list of supported capabilities. This is a beta feature available on multiple Apple platforms. ```APIDOC ## init(capabilities:) ### Description Initializes the `LanguageModelCapabilities` struct by providing an array of `LanguageModelCapabilities.Capability` values, indicating the supported features of a language model. ### Method `init(capabilities: [LanguageModelCapabilities.Capability])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift let myCapabilities: [LanguageModelCapabilities.Capability] = [.someCapability1, .someCapability2] let modelCapabilities = LanguageModelCapabilities(capabilities: myCapabilities) ``` ### Response #### Success Response An initialized `LanguageModelCapabilities` object. #### Response Example ```swift // No direct response example as this is an initializer. // The result is an instance of LanguageModelCapabilities. ``` ### See Also - `struct Capability`: A capability that a given language model may or may not have. - Creating an instance ``` -------------------------------- ### Define a Generable Cat Profile Structure Source: https://developer.apple.com/documentation/foundationmodels/generating-swift-data-structures-with-guided-generation Define a Swift struct conforming to `Generable` to guide model responses. Use the `@Guide` macro for properties with specific constraints, such as a numeric range or descriptive text. ```swift @Generable(description: "Basic profile information about a cat") struct CatProfile { // A guide isn't necessary for basic fields. var name: String @Guide(description: "The age of the cat", .range(0...20)) var age: Int @Guide(description: "A one sentence profile about the cat's personality") var profile: String } ``` -------------------------------- ### Unsupported Guide Error Case Source: https://developer.apple.com/documentation/foundationmodels/languagemodelsession/generationerror/unsupportedguide%28_%3A%29 This code snippet shows the definition of the `unsupportedGuide` error case within `LanguageModelSession.GenerationError`. It takes a `Context` object as an argument. This case is used to indicate an unsupported generation guide pattern. ```swift case unsupportedGuide(LanguageModelSession.GenerationError.Context) ``` -------------------------------- ### init(_:) Source: https://developer.apple.com/documentation/foundationmodels/anytool/init%28_%3A%29 Creates a tool that wraps the given tool. Available on iOS, iPadOS, Mac Catalyst, macOS, visionOS, and watchOS, all starting from version 27.0 (Beta). ```APIDOC ## init(_:) ### Description Creates a tool that wraps the given tool. ### Parameters #### Parameters - **tool** (some Tool) - The tool to wrap. ``` -------------------------------- ### LanguageModelError.UnsupportedGenerationGuide Source: https://developer.apple.com/documentation/foundationmodels/languagemodelerror/unsupportedgenerationguide Information about an unsupported generation guide. ```APIDOC ## Struct: UnsupportedGenerationGuide Information about an unsupported generation guide. ### Topics #### Creating an error instance ```swift init(schemaName: String?, debugDescription: String, metadata: [String : any Sendable]) ``` #### Inspecting unsupported generation guide errors ```swift var metadata: [String : any Sendable] var schemaName: String? var debugDescription: String ``` ### Relationships #### Conforms To * Sendable * SendableMetatype ``` -------------------------------- ### Define Model Behavior with Instructions Source: https://developer.apple.com/documentation/foundationmodels/instructions Use a string to define the model's role and behavior. This example specifies that the model should suggest concise related topics. ```swift struct Instructions ``` ```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) ``` -------------------------------- ### GenerationGuide.element Source: https://developer.apple.com/documentation/foundationmodels/generationguide Enforces a generation guide on the elements within an array. ```APIDOC ## GenerationGuide.element ### Description Enforces a guide on the elements within the array. ### Method static func ### Signature `static func element(GenerationGuide) -> GenerationGuide<[Element]>` ### Parameters * `GenerationGuide` - The guide to enforce on each element of the array. ``` -------------------------------- ### init(id:segments:options:responseFormat:) Source: https://developer.apple.com/documentation/foundationmodels/transcript/prompt/init%28id%3Asegments%3Aoptions%3Aresponseformat%3A%29 Creates a prompt using the provided identifier, segments, generation options, and an optional response format. ```APIDOC ## init(id:segments:options:responseFormat:) ### Description Creates a prompt using the provided identifier, segments, generation options, and an optional response format. ### Parameters #### Parameters - **id** (String) - Optional - A unique identifier for the prompt. Defaults to a new UUID. - **segments** ([Transcript.Segment]) - Required - An array of segments that constitute the prompt. - **options** (GenerationOptions) - Optional - Options that control token sampling during generation. Defaults to `GenerationOptions()`. - **responseFormat** (Transcript.ResponseFormat?) - Optional - Specifies the desired output structure for the response. ``` -------------------------------- ### Get Image as CIImage Source: https://developer.apple.com/documentation/foundationmodels/transcript/imageattachment Retrieves the image attachment as a CIImage. ```swift var ciImage: CIImage ``` -------------------------------- ### Get Image as CGImage Source: https://developer.apple.com/documentation/foundationmodels/transcript/imageattachment Retrieves the image attachment as a CGImage. ```swift var cgImage: CGImage ``` -------------------------------- ### init(debugDescription:) Source: https://developer.apple.com/documentation/foundationmodels/privatecloudcomputelanguagemodel/error/serviceunavailable/init%28debugdescription%3A%29 Initializes the `ServiceUnavailable` error with a provided debug description. This is useful for providing more context when the service is unavailable. ```APIDOC ## init(debugDescription:) ### Description Initializes the `ServiceUnavailable` error with a provided debug description. This is useful for providing more context when the service is unavailable. ### Parameters #### Path Parameters - **debugDescription** (String) - Description of the error for debugging purposes. ``` -------------------------------- ### UnsupportedGenerationGuide Structure Source: https://developer.apple.com/documentation/foundationmodels/languagemodelerror/unsupportedgenerationguide Defines the structure for an unsupported generation guide error. ```swift struct UnsupportedGenerationGuide ``` -------------------------------- ### GET isAvailable Source: https://developer.apple.com/documentation/foundationmodels/systemlanguagemodel/isavailable Retrieves the availability status of the system language model. ```APIDOC ## GET isAvailable ### Description A convenience getter to check if the system is entirely ready. ### Endpoint SystemLanguageModel.isAvailable ### Response - **isAvailable** (Bool) - Returns true if the system is ready, false otherwise. ### Availability - iOS 26.0+ - iPadOS 26.0+ - Mac Catalyst 26.0+ - macOS 26.0+ - visionOS 26.0+ ``` -------------------------------- ### init(_:) Source: https://developer.apple.com/documentation/foundationmodels/convertiblefromgeneratedcontent/init%28_%3A%29 Creates an instance from content generated by a model. This initializer is available on iOS, iPadOS, Mac Catalyst, macOS, visionOS, and watchOS starting from specific versions. ```APIDOC ## init(_:) ### Description Creates an instance from content generated by a model. ### Method `init(_ content: GeneratedContent) throws` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```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") } } ``` ### Response #### Success Response An instance of the type conforming to `ConvertibleFromGeneratedContent`. #### Response Example None explicitly provided in source. ``` -------------------------------- ### GenerationOptions.SamplingMode.kind Source: https://developer.apple.com/documentation/foundationmodels/generationoptions/samplingmode-swift.struct Gets the kind of sampling mode. This is a computed property of GenerationOptions.SamplingMode. ```APIDOC ## let kind: GenerationOptions.SamplingMode.Kind ### Description Gets the kind of sampling mode. ### Kind `let kind` ``` -------------------------------- ### TupleDynamicInstructions Initialization Source: https://developer.apple.com/documentation/foundationmodels/tupledynamicinstructions Explains how to create an instance of TupleDynamicInstructions, which represents a tuple of dynamic instructions. ```APIDOC ## `init(repeat each Content)` ### Description Creates a dynamic instructions instance that represents a tuple. ### Parameters * `Content` (Type of dynamic instructions): The types of dynamic instructions to include in the tuple. This must conform to the `DynamicInstructions` protocol. ### Usage ```swift let myTupleInstructions = TupleDynamicInstructions(instruction1, instruction2, ...) ``` ``` -------------------------------- ### LanguageModelSession.GenerationError.unsupportedGuide(_:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelsession/generationerror/unsupportedguide%28_%3A%29 An error that indicates a generation guide with an unsupported pattern was used. This is deprecated. ```APIDOC ## LanguageModelSession.GenerationError.unsupportedGuide(_:) ### Description An error that indicates a generation guide with an unsupported pattern was used. ### Case ```swift case unsupportedGuide(LanguageModelSession.GenerationError.Context) ``` ### Deprecated Use `LanguageModelError.unsupportedGenerationGuide(_:)` instead. ``` -------------------------------- ### Create and Initialize Content Tagging Model Session Source: https://developer.apple.com/documentation/foundationmodels/categorizing-and-organizing-data-with-content-tags Create an instance of the on-device language model's content tagging use case and initialize a session with specific instructions for tag generation. ```swift // Create an instance of the on-device language model's content tagging use case. let model = SystemLanguageModel(useCase: .contentTagging) // Initialize a session with the model and instructions. let session = LanguageModelSession(model: model, instructions: """ Provide the two tags that are most significant in the context of topics. """ ) ``` -------------------------------- ### Get Image Orientation Source: https://developer.apple.com/documentation/foundationmodels/transcript/imageattachment/orientation Retrieve the display orientation of the image. This property is read-only. ```swift var orientation: CGImagePropertyOrientation { get } ``` -------------------------------- ### init(model:tools:transcript:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelsession/init%28model%3Atools%3Atranscript%3A%29 Starts a new language model session by rehydrating from a provided transcript. This initializer allows you to resume a previous session's state, including the conversation history and any configured tools. ```APIDOC ## init(model:tools:transcript:) ### Description Starts a session by rehydrating from a transcript. This allows you to resume a previous conversation. ### Parameters * **model** (*SystemLanguageModel*) - Optional - The language model to use for this session. Defaults to `.default`. * **tools** (*[any Tool]*) - Optional - An array of tools to make available to the model for this session. Defaults to an empty array. * **transcript** (*Transcript*) - Required - The transcript to resume the session from. ``` -------------------------------- ### Get Tool Name Source: https://developer.apple.com/documentation/foundationmodels/tool/name-6x7wj Access the unique name of the tool. This property is read-only. ```swift var name: String { get } ``` -------------------------------- ### init(totalTokenCount:reasoningTokenCount:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelexecutorgenerationchannel/usage/output-swift.struct/init%28totaltokencount%3Areasoningtokencount%3A%29 Initializes an instance of `Output` with the specified total token count and reasoning token count. This initializer is part of the beta release and is available on iOS, iPadOS, macOS, visionOS, and watchOS starting from version 27.0. ```APIDOC ## init(totalTokenCount:reasoningTokenCount:) ### Description Initializes an `Output` object with the total number of tokens and the number of reasoning tokens. ### Parameters #### Parameters - **totalTokenCount** (Int) - The total number of tokens. - **reasoningTokenCount** (Int) - The number of reasoning tokens. ### Availability - iOS 27.0+ - iPadOS 27.0+ - Mac Catalyst 27.0+ - macOS 27.0+ - visionOS 27.0+ - watchOS 27.0+ ### Beta Software This documentation pertains to beta software and is subject to change. ``` -------------------------------- ### Get Sampling Mode Kind Source: https://developer.apple.com/documentation/foundationmodels/generationoptions/samplingmode-swift.struct Access the kind of the current sampling mode. ```swift `let kind: GenerationOptions.SamplingMode.Kind` ``` -------------------------------- ### Transcript.Entry.instructions(_:) Source: https://developer.apple.com/documentation/foundationmodels/transcript/entry/instructions%28_%3A%29 Represents instructions, typically provided by you, the developer, to the model. ```APIDOC ## Transcript.Entry.instructions(_:) ### Description Instructions, typically provided by you, the developer. ### Case ```swift case instructions(Transcript.Instructions) ``` ### Parameters #### Path Parameters - **instructions** (Transcript.Instructions) - Required - The instructions to be provided. ``` -------------------------------- ### Creating an input instance Source: https://developer.apple.com/documentation/foundationmodels/languagemodelexecutorgenerationchannel/usage/input-swift.struct Initializes a new Input instance with the total and cached token counts. ```APIDOC ## `init(totalTokenCount: Int, cachedTokenCount: Int)` ### Description Initializes a new `Input` instance with the total number of input tokens and the number of input tokens served from a cache. ### Parameters #### Path Parameters - **totalTokenCount** (Int) - Required - The total number of input tokens from the transcript. - **cachedTokenCount** (Int) - Required - The number of input tokens that were served from a cache. ``` -------------------------------- ### debugDescription Source: https://developer.apple.com/documentation/foundationmodels/languagemodelerror/unsupportedgenerationguide/debugdescription Returns a string that represents the unsupported generation guide error, useful for debugging. ```APIDOC ## debugDescription ### Description Returns a string that represents the unsupported generation guide error, useful for debugging. ### Instance Property `var debugDescription: String` ### Availability iOS 27.0+ Beta iPadOS 27.0+ Beta Mac Catalyst 27.0+ Beta macOS 27.0+ Beta visionOS 27.0+ Beta watchOS 27.0+ Beta ``` -------------------------------- ### init(input:output:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelexecutorgenerationchannel/usage/init%28input%3Aoutput%3A%29 Creates a usage update for the LanguageModelExecutorGenerationChannel.Usage, specifying token counts for both input and output. ```APIDOC ## init(input:output:) ### Description Creates a usage update. ### Parameters #### Parameters - **input** (LanguageModelExecutorGenerationChannel.Usage.Input) - Required - Token counts for the transcript. - **output** (LanguageModelExecutorGenerationChannel.Usage.Output) - Required - Token counts for the response. ``` -------------------------------- ### Getting the error description Source: https://developer.apple.com/documentation/foundationmodels/systemlanguagemodel/error/assetsunavailable Retrieves a string describing the reason why the model assets are unavailable. ```APIDOC ## `var debugDescription: String` ### Description A description of why the assets are unavailable. ### Properties - **debugDescription** (String) - A description of why the assets are unavailable. ``` -------------------------------- ### init(debugDescription:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelsession/generationerror/context/init%28debugdescription%3A%29 Creates a context for LanguageModelSession.GenerationError with a provided debug description. ```APIDOC ## init(debugDescription:) ### Description Creates a context for LanguageModelSession.GenerationError with a provided debug description to help developers diagnose issues during development. ### Parameters #### Parameters - **debugDescription** (String) - The debug description to help developers diagnose issues during development. ``` -------------------------------- ### Getting the Explanation Source: https://developer.apple.com/documentation/foundationmodels/languagemodelsession/generationerror/refusal Provides details on accessing the explanation for a model's refusal to respond. ```APIDOC ### Getting the explanation `var explanation: LanguageModelSession.Response` An explanation for why the model refused to respond. `var explanationStream: LanguageModelSession.ResponseStream` A stream containing an explanation about why the model refused to respond. ``` -------------------------------- ### Initialize LanguageModelSession with Custom Model Source: https://developer.apple.com/documentation/foundationmodels/languagemodel Demonstrates how to initialize a LanguageModelSession with a custom server model and prompt it. ```swift // Initialize a session with a custom server model. let session = LanguageModelSession(model: MyCustomServerLanguageModel()) // Use the same API surface to prompt the model. let response = try await session.respond(to: "Tell me a joke!") ``` -------------------------------- ### Accessing the guidedGeneration Capability Source: https://developer.apple.com/documentation/foundationmodels/languagemodelcapabilities/capability/guidedgeneration Use this static property to check for the availability of the guided generation capability. ```swift static var guidedGeneration: LanguageModelCapabilities.Capability { get } ``` -------------------------------- ### Declare a String GenerationGuide with anyOf(_:) Source: https://developer.apple.com/documentation/foundationmodels/generationguide/anyof%28_%3A%29 Use this method to create a GenerationGuide that restricts string outputs to a predefined list of acceptable values. This is useful for ensuring data consistency or validating user input against a set of allowed options. ```swift static func anyOf(_ values: [String]) -> GenerationGuide ``` -------------------------------- ### Get Tool Description Source: https://developer.apple.com/documentation/foundationmodels/tool/description Retrieves a natural language description of when and how to use the tool. This property is required. ```swift var description: String { get } ``` -------------------------------- ### init(_:) Source: https://developer.apple.com/documentation/foundationmodels/languagemodelsession/sessionproperty/init%28_%3A%29 Creates a session property with the specified key path. This initializer is available for iOS, iPadOS, Mac Catalyst, macOS, visionOS, and watchOS starting from version 27.0. ```APIDOC ## init(_:) ### Description Creates a session property with the specified key path. ### Method initializer ### Parameters #### Path Parameters - **keyPath** (ReferenceWritableKeyPath) - Required - The key path to the property. ``` -------------------------------- ### Getting the debug description Source: https://developer.apple.com/documentation/foundationmodels/generationschema/schemaerror/context Retrieves a string representation of the debug description for the schema error context. ```APIDOC ## debugDescription ### Description A string representation of the debug description. ### Properties - **debugDescription** (String) - A string representation of the debug description. ``` -------------------------------- ### Guide Macro for Influencing Property Values Source: https://developer.apple.com/documentation/foundationmodels/generable Allows for influencing the allowed values of properties of a generable type. ```swift macro Guide(description: String) ``` -------------------------------- ### Create a token usage instance Source: https://developer.apple.com/documentation/foundationmodels/languagemodelsession/usage-swift.struct Initializes a usage value with the provided input, output, and metadata token counts. ```swift init(input: LanguageModelSession.Usage.Input, output: LanguageModelSession.Usage.Output, metadata: [String : any Sendable & Codable & Equatable]) ```