HomeiOS DevelopmentWorking with @Generable and @Information in Basis Fashions

Working with @Generable and @Information in Basis Fashions


Within the earlier tutorial, we launched the Basis Fashions framework and demonstrated learn how to use it for primary content material technology. That course of was pretty easy — you present a immediate, wait a couple of seconds, and obtain a response in pure language. In our instance, we constructed a easy Q&A app the place customers might ask any query, and the app displayed the generated textual content immediately.

However what if the response is extra advanced — and you want to convert the unstructured textual content right into a structured object?

For instance, suppose you ask the mannequin to generate a recipe, and also you need to flip that response right into a Recipe object with properties like titlecomponents, and directions.

Do you want to manually parse the textual content and map every half to your information mannequin?

The Basis Fashions framework in iOS 26 offers two highly effective new macros referred to as Generable and @Information to assist builders simplify this course of.

On this tutorial, we’ll discover how these macros work and the way you should utilize them to generate structured information immediately from mannequin output.

The Demo App

generable-macro-demo-app.png

We’ll construct a easy Quiz app that demonstrates learn how to use Basis Fashions to generate structured content material. On this case, it’s the vocabulary questions for English learners.

The app shows a multiple-choice query with 4 reply choices, permitting customers to check their information interactively. Every query is generated by the on-device language mannequin and mechanically parsed right into a Swift struct utilizing the @Generable macro.

This demo app exhibits how builders can transfer past primary textual content technology and use Basis Fashions to create structured content material.

Utilizing @Generable and @Information

Let’s get began with constructing the demo app. As mentioned earlier than, not like the earlier Q&A demo, this quiz app presents a multiple-choice query with a number of reply choices. To signify the query, we’ll outline the next construction in Swift:

struct Query {
    let textual content: String
    let selections: [String]
    let reply: String
    let clarification: String
}

Later, we are going to ask the on-device language mannequin to generate quiz questions. The problem is how we are able to convert the mannequin’s unstructured textual content response right into a usable Query object. Happily, the Basis Fashions framework introduces the @Generable macro to simplify the conversion course of.

To allow automated conversion, merely mark your struct with @Generable, like this:

import FoundationModels

@Generable
struct Query {
    @Information(description: "The quiz query")
    let textual content: String
    @Information(.depend(4))
    let selections: [String]
    let reply: String
    @Information(description: "A short clarification of why the reply is right.")
    let clarification: String
}

The framework additionally introduces the @Information macro, which permits builders to offer particular directions to the language mannequin when producing properties. As an illustration, to specify that every query ought to have precisely 4 selections, you should utilize @Information(.depend(4)) on the selections array property.

With array, aside from controlling the precise variety of aspect, you too can use the next guides:

.minimumCount(3)
.maximumCount(100)

You too can add a descriptive clarification to a property to provide the language mannequin extra context in regards to the type of information it ought to generate. This helps make sure the output is extra correct and aligned together with your expectations.

It’s vital to concentrate to the order during which properties are declared. When utilizing a Generable sort, the language mannequin generates values sequentially based mostly on the order of the properties in your code. This turns into particularly vital when one property’s worth depends on one other. For instance, within the code above, the clarification property depends upon the reply, so it needs to be declared after the reply to make sure it references the proper context.

Constructing the Quiz App

With the Query construction prepared, we dive into the implementation of the Quiz app. Swap again to ContentView and replace the code like this:

import FoundationModels

struct ContentView: View {
    
    @State non-public var session = LanguageModelSession(directions: "You're a highschool English instructor.")
    
    @State non-public var query: Query?
    
    var physique: some View {
        VStack(spacing: 20) {
            
            if let query {
                QuestionView(query: query)
            } else {
                ProgressView("Producing questions ...")
            }
            
            Spacer()
            
            Button("Subsequent Query") {
                Activity {
                    do {
                        query = nil
                        query = strive await generateQuestion()
                    } catch {
                        print(error)
                    }
                }
            }
            .padding()
            .body(maxWidth: .infinity)
            .background(Shade.inexperienced.opacity(0.18))
            .foregroundStyle(.inexperienced)
            .font(.headline)
            .cornerRadius(10)

        }
        .padding(.horizontal)
        .activity {
            do {
                query = strive await generateQuestion()
            } catch {
                print(error)
            }
        }
    }
    
    func generateQuestion() async throws -> Query {
        
        let response = strive await session.reply(to: "Create a vocabulary quiz for highschool college students. Generate one multiple-choice query that checks vocabulary information.", producing: Query.self)
        
        return response.content material
    }
}

The consumer interface code for this app is easy and straightforward to comply with. What’s value highlighting, nonetheless, is how we combine the Basis Fashions framework to generate quiz questions. Within the instance above, we create a LanguageModelSession and supply it with a transparent instruction, asking the language mannequin to tackle the position of an English instructor.

To generate a query, we use the session’s reply methodology and specify the anticipated response sort utilizing the producingparameter. The session then mechanically produces a response and maps the consequence right into a Query object, saving you from having to parse and construction the info manually.

Subsequent, we’ll implement the QuestionView, which is answerable for displaying the generated quiz query, dealing with consumer interplay, and verifying the chosen reply. Add the next view definition inside your ContentView file:

struct QuestionView: View {
    let query: Query
    
    @State non-public var selectedAnswer: String? = nil
    @State non-public var didAnswer: Bool = false

    var physique: some View {
        ScrollView {
            VStack(alignment: .main) {
                Textual content(query.textual content)
                    .font(.title)
                    .fontWeight(.semibold)
                    .padding(.vertical)
                
                VStack(spacing: 12) {
                    ForEach(query.selections, id: .self) { alternative in
                        
                        Button {
                            if !didAnswer {
                                selectedAnswer = alternative
                                didAnswer = true
                            }

                        } label: {
                            if !didAnswer {
                                Textual content(alternative)
                            } else {
                                HStack {
                                    if alternative == query.reply {
                                        Textual content("✅")
                                    } else if selectedAnswer == alternative {
                                        Textual content("❌")
                                    }
                                    
                                    Textual content(alternative)
                                }
                            }
                        }
                        .disabled(didAnswer)
                        .padding()
                        .body(maxWidth: .infinity)
                        .background(
                            Shade.blue.opacity(0.15)
                        )
                        .foregroundStyle(.blue)
                        .font(.title3)
                        .cornerRadius(12)

                    }
                }
                
                if didAnswer {
                    
                    VStack(alignment: .main, spacing: 10) {
                        Textual content("The proper reply is (query.reply)")
                        
                        Textual content(query.clarification)
                    }
                    .font(.title3)
                    .padding(.high)
                }
            }
            

        }
    }
    
}

This view presents the query textual content on the high, adopted by 4 reply selections rendered as tappable buttons. When the consumer selects a solution, the view checks if it’s right and shows visible suggestions utilizing emojis (✅ or ❌). As soon as answered, the proper reply and an evidence are proven under. The @State properties observe the chosen reply and whether or not the query has been answered, permitting the UI to replace reactively.

As soon as you have applied all the required modifications, you may check the app within the Preview canvas. It’s best to see a generated vocabulary query just like the one proven under, full with 4 reply selections. After choosing a solution, the app offers fast visible suggestions and an evidence.

generable-macro-demo-test.png

Abstract

On this tutorial, we explored learn how to use the Basis Fashions framework in iOS 26 to generate structured content material with Swift. By constructing a easy vocabulary quiz app, we demonstrated how the brand new @Generable and @Information macros can flip unstructured language mannequin responses into typed Swift structs.

Keep tuned — within the subsequent tutorial, we’ll dive into one other highly effective function of the Basis Fashions framework.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments