Sample CodeiOS, iPadOS, Mac CatalystReviewed 2026-11-01View on Apple Developer

Book Tracker: Using Evaluations to evaluate an intelligent feature

At a glance

Item Summary
Purpose A SwiftData book library with two Foundation Models features (tag generation from a review, and tool-calling library search), plus a full evaluation workflow: heuristic and model-judge evaluations, a synthetic dataset generator, a result extractor, and a judge-calibration suite.
App architecture Five Xcode targets. The SwiftUI app (BookTracker) keeps model calls in two seams: BookTaggingService.generateTags(for:) and the three Tool structs in BookSearchTools.swift. Two hosted test bundles (BookTrackerTests, HillClimbingEvaluations) and a macOS tool (BookSampleGenerator) call or compile those same seams. A second macOS tool (DatasetExtractor) post-processes evaluation results.
Main patterns Service object (BookTaggingService, shared by the app, the evaluations, and the generator), Actor isolation (BookSearchCollector gathers tool results)
Project style One folder per target. App code is split into Models/, Services/, and Views/. Evaluation folders hold the Evaluation types, their Swift Testing suites, and JSON datasets.
Execution model The app target defaults to main-actor isolation; test and tool targets do not. Views start unretained Tasks for model calls. Tool calls run as async methods on Sendable snapshots and report IDs to an actor.
State/event model SwiftData (@Model Book, @Query, modelContext) is the shared store. Each view keeps transient UI state in private @State. No observable view model exists.
Key frameworks/packages Swift modules SwiftUI, SwiftData, FoundationModels, Playgrounds (app); Evaluations, Testing, TabularData, os.log (tests); ArgumentParser from the remote swift-argument-parser package (extractor only).

Project structure

BookTracker.xcodeproj               # 5 targets
BookTracker/                        # app target (synchronized folder)
├── BookTrackerApp.swift            # @main, ModelContainer, first-launch seeding
├── ContentView.swift               # TabView: Library + Search
├── Models/
│   ├── Book.swift                  # @Model Book + static sampleBooks
│   └── MockBooksModifier.swift     # in-memory PreviewModifier
├── Services/
│   ├── BookTaggingService.swift    # @Generable BookTags + stateless service
│   └── BookSearchTools.swift       # BookAssistant, collector actor, snapshots, 3 Tools
└── Views/                          # Library, Search, Detail, AddBook, covers, tag layout
BookTrackerEvaluations/             # BookTrackerTests target (hosted)
├── BookTags.swift                  # BookTaggingEvaluation + suite
├── SyntheticBookTags.swift         # same metrics over the JSON dataset
├── SearchBooks.swift               # tool-call trajectory evaluation
└── synthetic_book_samples.json
HillClimbingEvaluations/            # judge calibration target (hosted)
├── ModelJudgeAlignmentEvaluation.swift
├── Statistics.swift                # Cohen's kappa
└── BookTaggingEvaluation-extracted.json
BookSampleGenerator/main.swift      # macOS tool: synthetic data via SampleGenerator
DatasetExtractor/main.swift         # macOS tool: .xcevalresult -> JSON pairs

Structure observations

  • The targets are an application (BookTracker.xcodeproj/project.pbxproj:245), two unit-test bundles (BookTracker.xcodeproj/project.pbxproj:268, BookTracker.xcodeproj/project.pbxproj:311), and two command-line tools (BookTracker.xcodeproj/project.pbxproj:223, BookTracker.xcodeproj/project.pbxproj:291). Both test bundles depend on the app (BookTracker.xcodeproj/project.pbxproj:439, BookTracker.xcodeproj/project.pbxproj:444) and run inside it through TEST_HOST (BookTracker.xcodeproj/project.pbxproj:744).
  • The generator does not link the app. A synchronized-folder exception compiles three app files directly into the tool: Models/Book.swift, Services/BookSearchTools.swift, and Services/BookTaggingService.swift (BookTracker.xcodeproj/project.pbxproj:73, BookTracker.xcodeproj/project.pbxproj:74, BookTracker.xcodeproj/project.pbxproj:75).
  • The test bundles reach app code through @testable import BookTracker (BookTrackerEvaluations/BookTags.swift:12, HillClimbingEvaluations/ModelJudgeAlignmentEvaluation.swift:13).
  • The JSON files are data artifacts of the workflow: the generator writes synthetic_book_samples.json into the test folder (BookSampleGenerator/main.swift:80), and the calibration suite loads the extracted results as a bundle resource (BookTracker.xcodeproj/project.pbxproj:390).

Platform boundary

Apple lists iOS, iPadOS, and Mac Catalyst. The app target’s build settings support iphoneos iphonesimulator xros xrsimulator with device families 1,2,7 and set SUPPORTS_MACCATALYST = NO (BookTracker.xcodeproj/project.pbxproj:652, BookTracker.xcodeproj/project.pbxproj:653, BookTracker.xcodeproj/project.pbxproj:659). The two tools build for macosx (BookTracker.xcodeproj/project.pbxproj:466). This document keeps Apple’s platform list and grounds code claims in the project as shipped.

Overall architecture

Reference code

BookTracker/Services/BookTaggingService.swift:37 — the single tag-generation seam

    static func generateTags(for review: String) async throws -> BookTags {
        let prompt = tagsPrompt(review: review)
        let session = LanguageModelSession(
            model: SystemLanguageModel(guardrails: .permissiveContentTransformations),
            instructions: instructions
        )
        let response = try await session.respond(to: prompt, generating: BookTags.self)
        return response.content
    }

BookTrackerEvaluations/BookTags.swift:18 — the evaluation’s subject calls the same seam

    func subject(from sample: ModelSample<BookTags>) async throws -> ModelSubject<BookTags> {
        let result = try await BookTaggingService.generateTags(for: sample.promptDescription)
        return ModelSubject(value: result)
    }

Interpretation

Observed: the app (BookTracker/Views/AddBookView.swift:109, BookTracker/Views/BookDetailView.swift:126), the curated and synthetic evaluations (BookTrackerEvaluations/BookTags.swift:19, BookTrackerEvaluations/SyntheticBookTags.swift:18), and the generator’s dataset type all go through BookTaggingService and BookTags. Search works the same way: the app and SearchToolEvaluations build sessions from the same three tool types and the same BookAssistant.instructions (BookTracker/Views/SearchView.swift:89, BookTrackerEvaluations/SearchBooks.swift:548).

Inference: the workflow is a loop. Ship a feature behind one seam, evaluate it with heuristics and a model judge, grow the dataset synthetically, extract results, then check that the judge agrees with an expert before trusting its scores. The seams are what keep every stage measuring the shipping code.

Ownership and state

Ownership evidence

BookTracker/BookTrackerApp.swift:14 — the app creates and seeds the persistent container

    let container: ModelContainer = {
        do {
            let container = try ModelContainer(for: Book.self)
            addSampleBooks(in: container.mainContext)
            return container
        } catch {
            fatalError("Failed to create ModelContainer: \(error)")
        }
    }()

BookTracker/Views/SearchView.swift:79 — a search creates its collector and tools, snapshotting the queried books

        let collector = BookSearchCollector()
        let snapshots = books.map(\.snapshot)
        let tools: [any Tool] = [
            SearchBooksTool(books: snapshots, collector: collector),
            GetBookDetailsTool(books: snapshots, collector: collector),
            FindSimilarBooksTool(books: snapshots, collector: collector)
        ]
Owner Object or state Relationship Mutation authority
BookTrackerApp ModelContainer Creates once and installs with .modelContainer(container) (BookTracker/BookTrackerApp.swift:28) addSampleBooks(in:) inserts the curated books only when the store is empty (BookTracker/BookTrackerApp.swift:36)
SwiftData store Book records Read through @Query (BookTracker/ContentView.swift:12, BookTracker/Views/LibraryView.swift:13) AddBookView inserts or edits (BookTracker/Views/AddBookView.swift:129); BookDetailView deletes (BookTracker/Views/BookDetailView.swift:59); BookDetailHeader writes generated tags (BookTracker/Views/BookDetailView.swift:130)
SearchView searchText, resultIDs, isSearching, errorMessage, lastSearchedQuery private @State (BookTracker/Views/SearchView.swift:18) Only SearchView
SearchView.runSearch() BookSearchCollector, tools, LanguageModelSession Local values created per search and dropped afterward The collector is mutated only through its actor method add(_:)
AddBookView Draft title, author, review, tags private @State copied from bookToEdit on appear (BookTracker/Views/AddBookView.swift:90) The view writes back to the Book only after tag generation finishes
BookAssistant / BookTaggingService Instructions, known genres static let constants (BookTracker/Services/BookSearchTools.swift:16, BookTracker/Services/BookTaggingService.swift:22) Immutable
Test suites One Evaluation value per suite static let (BookTrackerEvaluations/BookTags.swift:151, BookTrackerEvaluations/SearchBooks.swift:570) Immutable after construction

SearchState in the diagram stands for the five @State properties listed above. Tools receive BookSnapshot values, not Book model objects (BookTracker/Services/BookSearchTools.swift:42), so tool code never touches the SwiftData context.

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution. A Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Main-actor isolation (app target) SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor App declarations without explicit isolation, including the views and BookTaggingService, are main-actor isolated. The test and tool targets have no such setting. BookTracker.xcodeproj/project.pbxproj:655
Explicit isolation @MainActor Repeated on the seeding function and on SearchView.runSearch(). BookTracker/BookTrackerApp.swift:33, BookTracker/Views/SearchView.swift:68
Isolation opt-out nonisolated static let BookTaggingService.knownGenres and BookAssistant.instructions are explicitly nonisolated. The nonisolated test target reads knownGenres synchronously inside evaluator closures and passes instructions into sessions. BookTracker/Services/BookTaggingService.swift:59, BookTracker/Services/BookSearchTools.swift:16, BookTrackerEvaluations/BookTags.swift:99, BookTrackerEvaluations/SearchBooks.swift:548
Task creation Plain Task { } in view actions SearchView (onSubmit), AddBookView.save(), and the detail header’s Generate button each start a task from main-actor view code; none is stored or cancelled. BookTracker/Views/SearchView.swift:55, BookTracker/Views/AddBookView.swift:106, BookTracker/Views/BookDetailView.swift:125
Actor isolation actor BookSearchCollector Serializes orderedIDs and seen. Tools await collector?.add(...); the view reads await collector.ids after the session responds. BookTracker/Services/BookSearchTools.swift:24, BookTracker/Services/BookSearchTools.swift:153, BookTracker/Views/SearchView.swift:94
Transfer contract struct BookSnapshot: Sendable Immutable value copy of a Book; the comment states it is for tools “off the main actor”. The executor that runs tool calls is not established by the sample source. BookTracker/Services/BookSearchTools.swift:41, BookTracker/Services/BookSearchTools.swift:42
Async sequence for try await sample in generator.run() The generator tool consumes generated samples at top level, then awaits generator.samples. BookSampleGenerator/main.swift:67, BookSampleGenerator/main.swift:73
Test scheduling @Suite(... .serialized) Only the calibration suite requests serialized execution. HillClimbingEvaluations/ModelJudgeAlignmentEvaluation.swift:337

No DispatchQueue, lock, Task.detached, or Combine appears in the source.

Reference code

BookTracker/Services/BookSearchTools.swift:24 — the only explicit actor

actor BookSearchCollector {
    private var orderedIDs: [String] = []
    private var seen: Set<String> = []

    /// Collected IDs, in the order first seen.
    var ids: [String] { orderedIDs }

    /// Adds IDs that haven't been collected yet.
    func add(_ newIDs: [String]) {
        for id in newIDs where seen.insert(id).inserted {
            orderedIDs.append(id)
        }
    }
}

BookTracker/Views/AddBookView.swift:106 — an unretained task generates tags, then writes to SwiftData

        Task {
            let generatedTags: [String]
            do {
                generatedTags = try await BookTaggingService.generateTags(for: review).tags
            } catch {
                generatedTags = []
            }
            // ...
            isGeneratingTags = false
            dismiss()
        }

Observations and inferences:

  • Observed: tasks are never cancelled. The UI prevents overlap by state, not by task identity: canSave is false while isGeneratingTags is true (BookTracker/Views/AddBookView.swift:26), and runSearch() returns early when the query equals lastSearchedQuery (BookTracker/Views/SearchView.swift:71).
  • Inference: the collector exists because the model may call several tools, possibly more than once, during one respond(to:). The actor gives those calls one ordered, de-duplicated result list, and the view reads it once the response completes.
  • Inference: the nonisolated constants keep shared files usable from the nonisolated test target and from the tool target, which compiles BookTaggingService.swift and BookSearchTools.swift without the app’s default isolation.

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line. It does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
State propagation SwiftData @Query and modelContext Views observe Book records; writes through the context update every query BookTracker/Views/SearchView.swift:15, BookTracker/Views/SearchView.swift:16
State propagation Navigation by PersistentIdentifier Lists push an ID; BookDetailDestination resolves it with modelContext.model(for:) BookTracker/Views/LibraryView.swift:34, BookTracker/ContentView.swift:45
State propagation Private @State Search, add/edit, and detail UI states are local to their views BookTracker/Views/AddBookView.swift:18, BookTracker/Views/BookDetailView.swift:76
Guided generation @Generable BookTags, @Guide(.count(3...8)) Output schema for tagging, also the evaluation’s expected-value type BookTracker/Services/BookTaggingService.swift:13, BookTracker/Services/BookTaggingService.swift:15
Swift module import FoundationModels, Playgrounds Sessions and tools; a #Playground block exercises the service BookTracker/Services/BookTaggingService.swift:9, BookTracker/Services/BookTaggingService.swift:10
Swift module import SwiftData, SwiftUI Persistence and UI BookTracker/BookTrackerApp.swift:8, BookTracker/BookTrackerApp.swift:9
Swift module import (tests) Evaluations, Testing, TabularData, os.log Evaluation types, suites, logging BookTrackerEvaluations/BookTags.swift:8, BookTrackerEvaluations/BookTags.swift:11, BookTrackerEvaluations/SearchBooks.swift:10, HillClimbingEvaluations/ModelJudgeAlignmentEvaluation.swift:12
Swift module import (tools) Evaluations, FoundationModels, ArgumentParser SampleGenerator with PrivateCloudComputeLanguageModel; CLI parsing BookSampleGenerator/main.swift:8, BookSampleGenerator/main.swift:38, DatasetExtractor/main.swift:10
Package declaration Remote swift-argument-parser (from 1.8.1), product ArgumentParser Direct dependency of the DatasetExtractor target only BookTracker.xcodeproj/project.pbxproj:955, BookTracker.xcodeproj/project.pbxproj:287

Class and protocol design

Reference code

BookTracker/Services/BookSearchTools.swift:106 — a tool is a value that holds snapshots and an optional collector

struct SearchBooksTool: Tool {
    typealias Arguments = SearchBooksArguments
    typealias Output = String

    let books: [BookSnapshot]
    var collector: BookSearchCollector? = nil
    // ...
}

BookTrackerEvaluations/SearchBooks.swift:525 — the search evaluation registers the same tools without a collector and scores the transcript

struct SearchToolEvaluations: Evaluation {
    var dataset = samples
    
    let pass = Metric("All Passed")
    let percent = Metric("Percentage Passed")
    
    var evaluators: Evaluators {
        ToolCallEvaluator(allPass: pass, percentagePass: percent)
    }
    // ...
}
Type Responsibility Depends on
BookTrackerApp @main entry, container creation and seeding Book, SwiftData
ContentView / BookDetailDestination Tabs, navigation destinations, ID-to-model resolution LibraryView, SearchView, BookDetailView
SearchView Natural-language search: builds tools and a session per query BookSearchCollector, the three tools, BookAssistant
AddBookView / BookDetailView Create, edit, delete, and tag books BookTaggingService, modelContext
BookTaggingService Stateless tag generation (struct with only static members) LanguageModelSession, BookTags
SearchBooksTool, GetBookDetailsTool, FindSimilarBooksTool Pure filtering over snapshots, JSON output, optional ID recording BookSnapshot, BookSearchCollector
BookTaggingEvaluation, SyntheticBookTaggingEvaluation Heuristic metrics plus a ModelJudgeEvaluator over curated or synthetic data BookTaggingService
SearchToolEvaluations Tool-call trajectory scoring with ToolCallEvaluator The three tools, BookAssistant
BookTagJudgmentCalibration Judges stored outputs and compares judge scores with expert scores (Cohen’s kappa) Statistics, extracted JSON
DatasetExtractorCommand ParsableCommand that turns an .xcevalresult into prompt/response JSON ArgumentParser

All conformances are to framework protocols (Evaluation, Tool, View, App, PreviewModifier, ParsableCommand, Codable). The sample declares no local protocol, so no protocol-oriented design is claimed.

Access control

Symbol Access Verified effect Likely rationale
BookSearchCollector.orderedIDs, seen private Only the actor can mutate them; callers use add(_:) and ids (BookTracker/Services/BookSearchTools.swift:25, BookTracker/Services/BookSearchTools.swift:26). Inference: keeps the ordered, de-duplicated invariant inside the actor.
BookTaggingService.tagsPrompt(review:) fileprivate static Only code in BookTaggingService.swift can build the prompt (BookTracker/Services/BookTaggingService.swift:47). Inference: every caller goes through generateTags(for:), so the app and evaluations cannot drift on the prompt.
BookDetailsPayload private (file scope) Visible only in BookSearchTools.swift (BookTracker/Services/BookSearchTools.swift:260). Inference: an output-encoding detail of one tool.
addSampleBooks(in:) private (file scope) Callable only from BookTrackerApp.swift (BookTracker/BookTrackerApp.swift:34). Inference: seeding is an app-launch detail.
BookDetailDestination, BookDetailHeader private struct Used only within their files (BookTracker/ContentView.swift:40, BookTracker/Views/BookDetailView.swift:71). Inference: view decomposition without widening the module surface.
View @State storage private Only the owning view can read or write it (BookTracker/Views/SearchView.swift:18). Inference: transient UI state is not shared.
Test-file samples, logger, BundleToken file private Visible only in their test files (BookTrackerEvaluations/SearchBooks.swift:43, HillClimbingEvaluations/ModelJudgeAlignmentEvaluation.swift:21). Inference: dataset and helper details stay local.

The service, tools, Book, and BookTags are implicitly internal. The test bundles see them through @testable import; the generator sees them because it compiles the same files. Nothing is public or open.

Reference code

BookTracker/Services/BookTaggingService.swift:47 — the prompt builder is file-private

    fileprivate static func tagsPrompt(review: String) -> Prompt {
        Prompt {
            """
            Reader's review:
            \(review)

            Generate descriptive tags for this book based on the review above.
            """
        }
    }

Logic ownership and placement

Logic Owning type or file Placement rationale
Tagging instructions, prompt, session, guided output BookTaggingService Observed: one file, used by the app, the evaluations, and (compiled into) the generator.
Search instructions BookAssistant.instructions Observed: its comment says it is shared “so the app and the evals behave the same way” (BookTracker/Services/BookSearchTools.swift:14).
Library filtering and similarity (Jaccard) Tool call(arguments:) methods Observed: deterministic code over snapshots (BookTracker/Services/BookSearchTools.swift:221); only tool selection is left to the model.
Result ordering for display SearchView.resultBooks Observed: orders queried Books by the collector’s ID order (BookTracker/Views/SearchView.swift:24).
Tag-quality heuristics and judge dimensions BookTaggingEvaluation.evaluators Observed: count range, single-word, known-genre, and two judge dimensions (BookTrackerEvaluations/BookTags.swift:72).
Pass thresholds Swift Testing #expect in each suite Observed: e.g. mean tag-count pass rate >= 0.8 (BookTrackerEvaluations/BookTags.swift:166).
Synthetic data rules BookSampleGenerator validator closure Observed: rejects short reviews, wrong tag counts, and non-lowercase tags (BookSampleGenerator/main.swift:54).
Judge calibration BookTagJudgmentCalibration Observed: the subject returns stored expert-labeled values, so the run scores the judge, not the tagger (HillClimbingEvaluations/ModelJudgeAlignmentEvaluation.swift:166).

Design patterns

Pattern Source evidence Purpose or tradeoff
Service object BookTracker/Services/BookTaggingService.swift:20 (struct BookTaggingService with only static members), called from BookTracker/Views/AddBookView.swift:109 and BookTrackerEvaluations/BookTags.swift:19 One stateless seam serves the app, the evaluations, and the generator. Tradeoff: static calls cannot be substituted by injection; evaluations always hit the real model.
Actor isolation BookTracker/Services/BookSearchTools.swift:24 (actor BookSearchCollector) Race-free accumulation of IDs from asynchronous tool calls within one session.

Not claimed: “Binding-based state propagation”. The only @Binding is an animation spacing value in BookTagsView (BookTracker/Views/BookDetailView.swift:206); application state flows through SwiftData queries and local @State, not bindings into a shared model.

Naming conventions

  • Types: …Service for the stateless model-call seam, …Tool for Tool conformances, …Arguments for their @Generable inputs, …Snapshot for the Sendable copy, …Collector for the accumulating actor, …Evaluation/…Tests for the evaluation and its suite, and …Command for the CLI. BookAssistant is a caseless enum used as a namespace for instructions.
  • Tool name strings use lower camel case verbs (searchBooks, getBookDetails, findSimilarBooks) that match the type names.
  • Metrics and judge dimensions are named for what they report (Tag Count, Has Genre Tag, Relevance, Usefulness, Relevance Alignment Score).
  • Methods: generateTags(for:), runSearch(), save(), and subject(from:) from the Evaluation protocol.
  • Files: one primary type per file in the app; evaluation files are named for the feature they test (BookTags.swift, SearchBooks.swift).

Architecture takeaways

  • Put each intelligent feature behind one call site (a service function or a set of tools) and have the evaluation call exactly that. The sample does this for both tagging and search.
  • Keep model-facing tools deterministic and side-effect-light: tools filter Sendable snapshots and report IDs to an actor, so the UI can map results back to live SwiftData models afterward.
  • Treat the evaluation as a pipeline of targets: an app, hosted evaluation bundles, a synthetic-data generator, a result extractor, and a judge-calibration bundle. The generator shares source by compiling the app’s files instead of linking the app.
  • Calibrate a model judge before relying on it: score stored outputs against expert labels and assert agreement (Cohen’s kappa) above a threshold.
  • With target-wide MainActor default isolation, mark shared constants nonisolated when other targets with different isolation defaults must read them synchronously.

Source map

Source file Relevant symbols
BookTracker/BookTrackerApp.swift BookTrackerApp, addSampleBooks(in:)
BookTracker/ContentView.swift ContentView, BookDetailDestination
BookTracker/Models/Book.swift Book, sampleBooks
BookTracker/Services/BookTaggingService.swift BookTags, BookTaggingService, generateTags(for:), tagsPrompt(review:), knownGenres
BookTracker/Services/BookSearchTools.swift BookAssistant, BookSearchCollector, BookSnapshot, SearchBooksTool, GetBookDetailsTool, FindSimilarBooksTool, BookDetailsPayload
BookTracker/Views/SearchView.swift SearchView, runSearch(), resultBooks
BookTracker/Views/AddBookView.swift AddBookView, save(), canSave
BookTracker/Views/BookDetailView.swift BookDetailView, BookDetailHeader, BookTagsView
BookTracker/Views/LibraryView.swift LibraryView
BookTrackerEvaluations/BookTags.swift BookTaggingEvaluation, BookTagEvaluationTests
BookTrackerEvaluations/SyntheticBookTags.swift SyntheticBookTaggingEvaluation
BookTrackerEvaluations/SearchBooks.swift samples, SearchToolEvaluations, SearchToolEvaluationsTest
HillClimbingEvaluations/ModelJudgeAlignmentEvaluation.swift BookTagJudgmentValue, BookTagJudgmentCalibration, BookTagJudgmentCalibrationTests
HillClimbingEvaluations/Statistics.swift Statistics.cohensKappa
BookSampleGenerator/main.swift SampleGenerator, validator, output path
DatasetExtractor/main.swift DatasetExtractorCommand
BookTracker.xcodeproj/project.pbxproj Targets, membership exceptions, default isolation, TEST_HOST, ArgumentParser