포스트

[WWDC26] LLM search using Core Spotlight

이 글은 WWDC 세션의 transcript 와 영상 화면을 Claude Code 로 정리한 글이고, 실제로 쓴 날은 2026-11-25 다. code 는 세션 page 의 snippet 을 Xcode 27 SDK 선언에 맞춰 다시 쓰고 type check 했다. SpotlightSearchTool 의 이름은 macOS 27 에서 실행해 읽었다.


세션 정보

  • 세션: LLM search using Core Spotlight
  • 길이: 16분 25초
  • 공개일: 2026-06-08
  • 발표: Jennifer Moore (Spotlight Engineer)
  • 코드: 세션 page 에 snippet 12개, hiking trails sample app 은 받지 않음

한 줄 요약

앱이 Core Spotlight 에 넣어 둔 index 를 SpotlightSearchTool 하나로 language model 의 tool 로 연결하면, model 이 직접 query 를 만들어 검색하고 그 결과만으로 답하게 할 수 있고, guidance 와 contact resolver 와 custom stage 로 그 검색을 앱에 맞게 좁히거나 넓힐 수 있다.


세션의 구성

세션은 세 부분이다. tool 을 session 에 붙여 결과를 화면에 내기까지가 Introduction, 검색 능력을 앱에 맞게 바꾸는 것이 Customization, 응답 품질을 재는 것이 Evaluation 이다. 발표자는 한 명이다.

순서내용발표
1tool calling 으로 답을 앱의 content 에 묶기Jennifer Moore
2SpotlightSearchTool 구성과 session 에 추가Jennifer Moore
3index delegate 로 완전한 item 돌려주기Jennifer Moore
4응답과 search reply 로 결과 표시Jennifer Moore
5guidance profile, contact resolver, custom stageJennifer Moore
6Evaluations framework 로 품질 평가Jennifer Moore

출처: WWDC26 - LLM search using Core Spotlight

title 화면에는 세션 이름과 “Jennifer Moore, Spotlight Engineer” 가 적혀 있다.

출처: WWDC26 - LLM search using Core Spotlight

agenda 는 Introduction, Customization, Evaluation 세 줄이다.


앱의 content 로만 답하게 하는 문제

예제는 발표자가 만든 hiking trails 앱이다. state park 와 trail 을 둘러볼 수 있고, 다녀온 trail 에는 무엇이 좋았는지 직접 메모를 남긴다.

출처: WWDC26 - LLM search using Core Spotlight

trail 상세 화면이다. 제목은 El Capitan Meadow Trail 이고 그 아래에 Yosemite Valley 라는 위치, Easy 난이도, 1.0 hrs, “Hiked on March 5, 2026” 표시, tag 몇 개, 그리고 해 질 녘에 meadow 까지 걸어간 이야기를 쓴 메모가 보인다.

발표자가 원하는 것은 다녀온 hike 나 새로 가 볼 hike 를 language model 에게 묻는 것이다. LanguageModelSession 을 앱에 넣고 session.respond(to: "What are some nice hikes near water?") 를 부르면 답은 나온다. 다만 그 답은 model 이 세상에 대해 알고 있는 지식에서 나온다. 앱이 알고 있는 hike 에 대해서만 답하게 하려면 다른 길이 필요하다.

앱은 이미 이 hike 들을 Core Spotlight index 에 넣어 두었다. 그래서 Foundation Models 의 tool calling 을 통해 그 index 를 model 에게 열어 주는 것이 세션의 출발점이다.

출처: WWDC26 - LLM search using Core Spotlight

“Tool-calling for response generation” slide 는 두 줄이다. tool 은 arguments 와 output 과 instructions 를 선언하고, model 은 tool 을 부를 arguments 를 생성한다.


SpotlightSearchTool 이란?

SpotlightSearchTool 은 Core Spotlight 가 제공하는 struct 로, Foundation Models 의 Tool protocol 을 채택한다. session 의 tool 목록에 넣으면 model 이 필요하다고 판단할 때 query 를 만들어 이 tool 을 부르고, tool 은 앱의 Core Spotlight index 를 검색해 결과를 돌려준다. 앱이 직접 query 문자열을 짜지 않는다는 것이 핵심이다.

출처: WWDC26 - LLM search using Core Spotlight

slide 에는 NEW 표시와 함께 iOS, iPadOS, macOS, visionOS 가 각각 27.0 으로 적혀 있다. SDK 에서도 tvOS 와 watchOS 는 unavailable 로 표시되어 있다.

SDK 에서 이 type 은 CoreSpotlight 와 FoundationModels 를 함께 import 했을 때 열리는 cross-import overlay 에 들어 있다. 둘 중 하나만 import 하면 이름이 보이지 않는다. 문서는 SpotlightSearchTool 에 있다.


먼저 갖춰야 할 index

tool 이 검색할 대상은 앱이 Core Spotlight 에 donate 해 둔 searchable content 다. 그래서 index 가 먼저 있어야 한다.

출처: WWDC26 - LLM search using Core Spotlight

“Build your searchable index” slide 의 세 줄은 searchable content 를 Spotlight 에 donate 하기, searchable delegate 구현하기, metadata query 와 semantic query 수행하기다. 아래에는 WWDC24 의 Support semantic search with Core Spotlight 가 참고 세션으로 걸려 있다. tool calling 자체는 WWDC25 의 Deep dive into the Foundation Models framework 를 보라고 한다.


도구 구성과 session 연결

Introduction 은 세 가지를 다룬다. tool 을 구성하는 법, 검색 도중에 추가 context 를 주는 법, 결과를 화면에 내는 법이다. 이 절은 첫 번째다.

tool 은 한 줄로 만들어진다. 기본 구성은 앱의 Core Spotlight index 를 검색한다. model 은 system model 을 쓸 수도 있고 Model Provider API 로 다른 model 을 쓸 수도 있다. 아래는 기본 system model 로 session 을 만든 형태다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import CoreSpotlight
import FoundationModels

func askAboutHikes() async throws -> String {
    let tool = SpotlightSearchTool()

    let session = LanguageModelSession(
        tools: [tool],
        instructions: "Answer only from the trails found in the app's index."
    )

    let response = try await session.respond(to: "What hikes have I gone on?")
    return response.content
}

func makeFileTool() -> SpotlightSearchTool {
    SpotlightSearchTool(
        configuration: .init(sources: [.files])
    )
}

makeFileTool() 은 세션이 보여 준 두 번째 형태다. source 를 .files 로 주면 앱 sandbox 안의 파일 경로를 검색한다. instructions 문장은 내가 넣은 것이고 세션 화면에는 instructions 라는 변수만 보인다.

기본 구성의 tool 은 on-device system model 과 함께 쓰면 context 에 들어가지 않는다. macOS 27.0.1 에서 SystemLanguageModel.default.contextSize 는 4096 인데, tokenCount(for:) 로 재 보면 SpotlightSearchTool() 하나가 13,753 token 이다. sources 를 .files 나 .coreSpotlight 로 바꿔도 같다. 이 상태로 respond 를 부르면 “Provided 13,780 tokens, but the maximum allowed is 4,096” 이라는 error 로 끝난다. on-device model 로 쓸 때는 아래 guidance profile 절의 .focused level 을 같이 준다.

SpotlightSearchTool.Configuration

SDK 선언을 보면 Configuration 의 initializer 는 sources, guide, contactResolver, customStages 를 받는다. SearchSource 는 .coreSpotlight 와 .files 두 종류고, 각각 CoreSpotlightSource 와 FileSource 를 넘겨 세부 설정을 줄 수 있다. CoreSpotlightSource 에는 maximumResultCount 가, FileSource 에는 검색 범위를 정하는 scopes 가 있다. SpotlightSearchTool() 의 기본값은 Configuration(sources: [.coreSpotlight]) 인데, Configuration 을 직접 만들 때 sources 의 기본값은 빈 배열이다. 그래서 아래 code 에서는 sources 를 매번 적었다. 설정 전체는 Spotlight search tool 에 있다.


한 번의 질문이 처리되는 순서

session 에 질문을 넣으면 model 과 tool 사이에서 일이 몇 단계로 진행된다.

출처: WWDC26 - LLM search using Core Spotlight

도식의 Prompt 는 “What hikes have I gone on?” 이다. 그 아래로 Generate query, Invoke search tool, Execute query, Read output, Generate response 다섯 단계가 한 묶음으로 있고, 마지막이 Final output to user 다. model 이 tool 을 쓰기로 정하고 query 를 생성해 tool 을 부르면, Spotlight 가 query 를 실행해 result set 의 설명을 돌려준다. model 은 그 설명을 읽고 최종 응답을 만든다.

출처: WWDC26 - LLM search using Core Spotlight

앱의 Trail Search 화면에 나온 응답이다. Maple Canyon Trail, Rubicon Trail, Congress Trail, Crystal Cove State Park, El Capitan Meadow Trail 이 각각 한 문단씩 설명과 함께 나열되어 있다. 전부 앱이 index 에 넣어 둔 trail 이다.


검색 중에 완전한 item 을 돌려주는 delegate

두 번째는 검색 도중의 추가 context 다. Spotlight 는 metadata 일부를 원래 값으로 되돌릴 수 없는 압축된 형태로 저장한다. text content 나 HTML 이 그렇다. 검색 대상은 되지만 model 이 읽을 원문은 index 에 남아 있지 않다. 그래서 Spotlight 가 검색 중에 앱에게 원본 item 을 요청할 수 있어야 한다.

출처: WWDC26 - LLM search using Core Spotlight

“Setting an index delegate” slide 는 두 줄이다. reindex 요청에 응답하기, 그리고 원본 item 을 on demand 로 제공하기다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import CoreSpotlight

struct TrailEntry: Sendable {
    let id: String
    let name: String
    let summary: String
    let notes: String
}

actor TrailStore {
    private var entries: [String: TrailEntry] = [:]

    func fetchEntries(ids: [String]) -> [TrailEntry] {
        ids.compactMap { entries[$0] }
    }
}

final class IndexDelegate: NSObject, CSSearchableIndexDelegate {
    let store = TrailStore()

    func searchableItems(forIdentifiers identifiers: [String]) async -> [CSSearchableItem] {
        let entries = await store.fetchEntries(ids: identifiers)
        return entries.map(makeSearchableItem)
    }

    private func makeSearchableItem(from entry: TrailEntry) -> CSSearchableItem {
        let attributes = CSSearchableItemAttributeSet(contentType: .text)
        attributes.title = entry.name
        attributes.contentDescription = entry.summary
        attributes.textContent = entry.notes
        return CSSearchableItem(
            uniqueIdentifier: entry.id,
            domainIdentifier: "trails",
            attributeSet: attributes
        )
    }

    func searchableIndex(
        _ searchableIndex: CSSearchableIndex,
        reindexAllSearchableItemsWithAcknowledgementHandler acknowledgementHandler: @escaping () -> Void
    ) {
        acknowledgementHandler()
    }

    func searchableIndex(
        _ searchableIndex: CSSearchableIndex,
        reindexSearchableItemsWithIdentifiers identifiers: [String],
        acknowledgementHandler: @escaping () -> Void
    ) {
        acknowledgementHandler()
    }
}

세션 화면에는 searchableItems(forIdentifiers:) 만 나온다. TrailEntry, TrailStore, makeSearchableItem 은 내가 채웠고, 두 reindex method 는 protocol 의 필수 요구라서 빈 형태로 넣었다. 실제 앱이라면 여기서 index 를 다시 채워야 한다.

발표자는 이 method 에서 item 을 돌려줄 때 attribute 를 더 붙일 수 있다는 점도 짚는다. 검색용으로 donate 하기에는 맞지 않지만 model 이 추론할 때는 도움이 되는 정보를 이 시점에 실어 보내면 된다.

searchableItems(forIdentifiers:)

CSSearchableIndexDelegate 의 optional method 로, index 가 identifier 목록을 주면 그에 해당하는 완전한 CSSearchableItem 을 돌려준다. 발표자는 새 method 라고 소개하는데 SDK header 의 availability 는 iOS 18.4, macOS 15.4, visionOS 2.4 다. iOS 27 에서 새로 생긴 것은 protectionClass 를 함께 받는 변형이다. 문서는 CSSearchableIndexDelegate 에 있다.


결과를 화면에 내는 두 가지 방법

세 번째는 결과 표시다. 길이 두 개 있다.

하나는 session 의 응답을 그대로 쓰는 것이다. 응답에는 검색된 result set 을 간결하게 설명한 글이 담긴다. assistant 처럼 묻고 답하는 UI 에는 이것으로 충분하다. 앞 절의 응답 화면이 이 경우다.

다른 하나는 검색된 item 을 목록으로 보여 주는 UI 다. 이때는 tool 이 내보내는 search reply 를 직접 받는다.

출처: WWDC26 - LLM search using Core Spotlight

Trail Search 화면에 El Capitan Meadow Trail, Congress Trail, Lands End Trail 이 사진과 Hiked 표시, 한두 줄 설명과 함께 목록으로 나와 있고, 아래 검색 field 에 “What hikes have I gone on” 을 입력하는 중이다.

출처: WWDC26 - LLM search using Core Spotlight

“Search tool results” slide 의 세 줄은 tool 에서 searchable item 을 돌려받아 표시하기, search reply 는 결과를 batch 로 담을 수 있다는 것, query token 으로 표시를 refresh 하기다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@MainActor
final class TrailResultsModel {
    private(set) var titles: [String] = []
    private var currentToken: SpotlightSearchTool.SearchReply.QueryToken?

    func observe(_ tool: SpotlightSearchTool) async {
        for await reply in tool.searchResults {
            if reply.queryToken != currentToken {
                currentToken = reply.queryToken
                titles.removeAll()
            }

            switch reply.content {
            case .items(let searchItems):
                titles += searchItems.compactMap { $0.item.attributeSet.title }
            default:
                break
            }
        }
    }
}

searchResults 는 async sequence 다. 결과는 한 번에 오지 않고 batch 로 나뉘어 온다. model 은 응답 하나를 만드는 동안 tool 을 여러 번 부를 수 있어서, reply 가 같은 query 의 다음 batch 인지 새 query 의 첫 batch 인지를 구분해야 한다. queryToken 이 그 구분이다. token 이 바뀌면 화면을 비우고 새로 그린다.

세션 화면의 code 는 case .items(let searchItems): 까지만 있고 그 뒤가 비어 있다. title 을 모으는 부분과 TrailResultsModel 은 내가 채웠다. SDK 에서 .items 가 담는 것은 CSSearchableItem 이 아니라 그것을 감싼 SearchableItem 이고, 원래 item 은 item property 로 꺼낸다.

SpotlightSearchTool.SearchReply

reply 하나는 content, label, queryToken, stageToken, status 를 가진다. status 는 partial 과 complete 로 나뉜다. content 의 case 는 뒤의 custom stage 절에서 전부 다룬다.


검색 능력을 앱에 맞추는 세 가지 방법

Customization 은 세 가지다. 검색 범위를 줄이는 guidance profile, model 이 모르는 지식을 채워 주는 contact resolver, 검색 위에 계산을 얹는 custom pipeline stage 다.


검색 범위를 좁히는 guidance profile

tool 은 자기가 어떤 검색을 할 수 있는지를 model 에게 guidance 로 설명한다. 기본 guidance 는 Spotlight 가 할 수 있는 것 전체를 설명한다. 앱이 그중 일부만 쓴다면 쓰지 않는 부분은 빼는 편이 낫다. 발표자의 예는 사람이다. hiking 앱은 person relationship 을 donate 하지 않으니 author 나 recipient 에 대한 guidance 는 필요 없다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func makeGuidedTool() -> SpotlightSearchTool {
    let profile = SpotlightSearchTool.GuidanceProfile(
        textMatch: true,
        dates: true,
        people: false,
        attributes: [.title, .altitude, .completionDate]
    )

    return SpotlightSearchTool(
        configuration: .init(
            sources: [.coreSpotlight],
            guide: .init(level: .dynamic(profile))
        )
    )
}

func makeFocusedTool() -> SpotlightSearchTool {
    SpotlightSearchTool(
        configuration: .init(
            sources: [.coreSpotlight],
            guide: .init(level: .focused(.items))
        )
    )
}

GuidanceProfile 로 text match 와 date 검색은 켜고 people 은 끄고, model 이 알아야 할 attribute 를 title, altitude, completion date 로 한정했다. 이 profile 을 .dynamic level 로 넘긴다. 두 번째 함수는 .focused level 이다. on-device model 은 context 가 작으니 focused guidance 를 쓰라는 것이 발표자의 권고다. 실제로 재 보면 차이가 크다. 기본인 .complete 는 tool 하나가 13,753 token 이고 .focused(.items) 는 282 token 이다. context 가 4096 token 인 on-device model 에서는 .focused 를 줘야 respond 가 돈다. makeFocusedTool() 을 넣은 session 에 “Find my notes about hiking trails.” 를 물으면 model 이 spotlight_search 를 {"keywords": "hiking trails"} 로 부르고, tool 은 count, hasMore, items 가 든 결과를 돌려준다. 질문 둘을 번갈아 네 번 물었을 때 네 번 모두 tool 을 불렀다.

.dynamic 은 사정이 다르다. makeGuidedTool() 이 만든 tool 은 includesSchemaInInstructions 가 false 고, session 의 transcript 를 보면 instructions entry 의 toolDefinitions 가 비어 있다. .complete 와 .focused 에서는 true 고 spotlight_search 가 들어 있다. 같은 질문을 네 번 물었을 때 on-device model 은 한 번도 tool 을 부르지 않았다. on-device model 로 검색까지 돌리려면 .focused 를 쓴다.

세션 화면의 code 는 sources 를 적지 않는다. 앞에서 본 대로 Configuration 의 sources 기본값이 빈 배열이라, 그대로 두면 어디를 검색하게 되는지 알 수 없어서 .coreSpotlight 를 명시했다.

SpotlightSearchTool.GuidanceProfile

SDK 의 initializer 는 textMatch, similarityMatch, numericMatch, dates, people, contentType, attributes 를 받고 전부 optional 이다. guidance level 은 complete, focused, dynamic 세 가지고 기본은 complete 다. focused 가 받는 content domain 은 audio, calendar, communications, documents, items, visualMedia 여섯이다. guide 에는 level 과 별도로 structured 와 compact 중 하나를 고르는 format 도 있는데 세션은 이것을 다루지 않는다. 문서는 SpotlightSearchTool.GuidanceProfile 에 있다.


지칭을 풀어 주는 contact resolver

질문에는 model 이 혼자서는 풀 수 없는 지칭이 들어온다. “내가” 쓴 메모라고 할 때 그 “나” 가 index 안의 어떤 이름과 email 에 해당하는지는 model 이 알 수 없다. 이것을 reference resolution 이라고 부른다.

출처: WWDC26 - LLM search using Core Spotlight

“Reference resolution” slide 의 부제는 “Providing world knowledge” 고, 본문은 지칭의 모호함을 없애도록 contact resolver 를 제공하라는 한 줄이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct MyContactResolver: ContactResolver {
    func userIdentity() -> ResolvedContact {
        var contact = ResolvedContact(displayName: "Jane Doe")
        contact.emailAddresses = ["jane@example.com", "jdoe@work.com"]
        contact.names = ["Jane", "JD"]
        return contact
    }
}

func makeToolWithResolver() -> SpotlightSearchTool {
    SpotlightSearchTool(
        configuration: .init(
            sources: [.coreSpotlight],
            contactResolver: MyContactResolver()
        )
    )
}

userIdentity() 는 지금 앱을 쓰는 사람의 연락처 정보를 돌려준다. 출처는 account profile 이든 Contacts framework 든 sign-in session 이든 앱이 가진 것을 쓰면 된다.

출처: WWDC26 - LLM search using Core Spotlight

세션 화면의 code 다. 마지막 줄이 tool.contactResolver = MyContactResolver() 로 되어 있다. Xcode 27 SDK 에서는 이 줄이 통과하지 않는다. contactResolver 는 tool 이 아니라 Configuration 의 property 고, tool 의 configuration 은 let 이다. 그래서 위 code 에서는 initializer 에 넘겼다.

ContactResolver

요구사항이 userIdentity() -> ResolvedContact 하나뿐인 protocol 이다. ResolvedContact 는 displayName 으로 만들고 names, nameComponents, emailAddresses, phoneNumbers 를 채울 수 있다. 문서는 ContactResolver 에 있다.


검색 위에 계산을 얹는 pipeline

SpotlightSearchTool 이 하는 검색은 index query 하나로 끝나지 않는다. query 로 얻은 result set 위에서 계산을 이어 붙일 수 있고, 세션은 이것을 pipeline search 라고 부른다.

출처: WWDC26 - LLM search using Core Spotlight

Search, Count, Average 세 단계가 위에서 아래로 쌓인 도식이다. 발표자의 질문은 올해 trail 을 몇 개 다녀왔고 월별 평균 mile 이 얼마냐는 것이다. 다녀온 hike 를 검색하고, 월별로 세어 table 을 만들고, 평균을 낸다.

출처: WWDC26 - LLM search using Core Spotlight

그 질문의 응답 화면이다. 올해 7개를 다녀왔다고 하고 월별로 나눈다. January 는 Rubicon Trail (4.5 mi) 과 Fitzgerald Marine Reserve (2 mi) 로 평균 3.25 mile, February 는 Lands End Trail (3.5 mi) 과 Maple Canyon Trail (4 mi) 로 평균 3.75 mile, March 는 세 곳으로 평균 2 mile 이다. 전체는 20 mile 에 평균 약 2.86 mile 이라고 맺는다.

이 단계들은 기본 제공이고, 앱이 자기만의 단계를 더할 수 있다.

출처: WWDC26 - LLM search using Core Spotlight

“Custom pipeline stages” slide 의 세 줄은 custom pipeline stage 를 등록하기, stage 는 필요할 때 model 이 생성한다는 것, 어느 stage 에서든 data 가 돌아올 수 있다는 것이다.


CustomStage 란?

CustomStage 는 pipeline 에 끼워 넣을 단계를 정의하는 protocol 이다. Generable 을 요구하기 때문에 stage 의 property 를 model 이 직접 채워서 인스턴스를 만든다. 앱은 stage 의 종류를 등록만 하고, 언제 어떤 값으로 쓸지는 model 이 질문을 보고 정한다.

발표자의 예는 “행복했던 hike” 를 찾는 stage 다. 메모에 sentiment analysis 를 돌리거나 별점 5개짜리 hike 를 고르는 식으로 점수를 매긴다.

출처: WWDC26 - LLM search using Core Spotlight

Congress Trail 의 메모가 강조된 화면이다. 겨울에 가서 눈 덕분에 모든 것이 평화로웠고, General Sherman Tree 아래에서 한참 서 있었으며, 그 계절 중 가장 행복했다는 내용이다. index query 만으로는 이런 메모를 “행복” 으로 찾아내기 어렵다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Generable
struct HappinessStage: CustomStage {
    static let name = "happiness"
    static let description = "Scores hikes by how happy the author was"
    static let inputTypes: [SearchPipelineDataType] = [.items]
    static let outputType: SearchPipelineDataType = .scoredItems

    @Guide(description: "Minimum happiness score (0.0-1.0) to include in results")
    var threshold: Double?

    func execute(items: [SearchableItem]) async throws -> SearchPipelineData {
        let minimum = threshold ?? 0
        let scored = items
            .map { ScoredSearchableItem(item: $0, score: happiness(of: $0)) }
            .filter { $0.score >= minimum }
            .sorted { $0.score > $1.score }
        return .scoredItems(scored)
    }

    private func happiness(of item: SearchableItem) -> Double {
        let rating = item.item.attributeSet.rating?.doubleValue ?? 0
        return min(max(rating / 5, 0), 1)
    }
}

func makeToolWithStage() -> SpotlightSearchTool {
    SpotlightSearchTool(
        configuration: .init(
            sources: [.coreSpotlight],
            customStages: [HappinessStage(threshold: 0.5)]
        )
    )
}

stage 는 이름과 설명, 받는 data 종류와 내놓는 data 종류를 static 으로 선언한다. model 은 이 설명을 보고 stage 를 쓸지 정한다. threshold 는 @Guide 로 뜻을 적어 둔 property 라서 model 이 질문에 맞춰 값을 넣는다. 점수 계산은 세션에 나오지 않아서 별점을 0 에서 1 사이로 바꾸는 단순한 식으로 채웠다.

출처: WWDC26 - LLM search using Core Spotlight

세션 화면의 code 는 위와 세 곳이 다르다.

항목세션 화면Xcode 27 SDK
출력 type 선언static var outputTypes: [SearchPipelineDataType]static var outputType: SearchPipelineDataType
실행 methodexecute(on input: SearchPipelineData)execute(items:), execute(scoredItems:) 등 입력 종류별 method
등록customStages: [.happinessBoost(threshold: 0.5)]customStages: [HappinessStage(threshold: 0.5)]

SDK 의 CustomStage 는 입력 종류마다 execute 를 따로 두고 전부 기본 구현을 준다. stage 는 inputTypes 에 적은 종류의 method 만 구현하면 된다. static var 를 static let 으로 바꾼 것은 Swift 6 language mode 에서 변경 가능한 global state 로 걸리지 않게 하려는 것이다. 문서는 CustomStage 에 있다.


stage 가 내놓는 여러 종류의 reply

pipeline 이 들어오면 search reply 가 담는 것도 item 목록만이 아니게 된다. 어느 stage 에서든 결과가 나올 수 있고 종류가 제각각이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func describe(_ reply: SpotlightSearchTool.SearchReply) -> String {
    let label = reply.label ?? "Result"

    switch reply.content {
    case .items(let searchItems):
        return "\(label): \(searchItems.count) items"
    case .scoredItems(let scored):
        return "\(label): \(scored.count) scored items"
    case .groupedItems(let groups):
        return "\(label): \(groups.count) groups"
    case .count(let count):
        return "\(label): \(count.value)"
    case .table(let table):
        return "\(label): \(table.rows.count) rows"
    case .statistic(let statistic):
        return "\(label): \(statistic.name) = \(statistic.value)"
    case .text(let text):
        return "\(label): \(text.body)"
    @unknown default:
        return label
    }
}

case 는 일곱 개다. item 목록, 점수가 붙은 item, 묶인 item, 개수, table, 통계 값 하나, text 다. label 은 LLM 이 그 결과에 붙인 이름이라서 화면의 section 제목으로 쓸 수 있다. 세션 화면의 code 는 case 를 나열만 하고 본문이 없어서, 각 case 에서 꺼낸 값은 SDK 선언을 보고 채웠다. SearchCount 에는 value, SearchResultsTable 에는 columns 와 rows, SearchStatistic 에는 name 과 value, SearchTextResult 에는 body 가 있고 넷 다 header 를 가진다.


응답 품질 평가

마지막은 Evaluation 이다. model 과 tool 이 함께 만든 답이 좋은지는 눈으로 몇 번 물어보는 것으로는 알 수 없다.

출처: WWDC26 - LLM search using Core Spotlight

“Model + Tool evaluation” slide 의 두 줄은 큰 규모의 dataset 만들기와 응답 품질을 평가할 metric 정의하기다. 아래에 WWDC26 의 “Meet the Evaluations framework” 와 “Create robust evaluations for an agentic app” 이 걸려 있다.

세션이 고른 metric 은 result coverage 다. 질문마다 나와야 할 item 의 identifier 를 정해 두고, 실제 검색 결과가 그것을 얼마나 덮었는지를 본다.


평가용 sample 의 모양

sample 하나는 질문, 기대하는 응답, 기대하는 tool 호출, 그리고 나와야 할 item identifier 로 이루어진다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import Evaluations
import FoundationModels

struct TrailRequest: ModelSampleProtocol {
    typealias ExpectedValue = String
    typealias Expectation = TrajectoryExpectation

    var input: ModelSampleInput
    var output: ModelSampleOutput<String, TrajectoryExpectation>

    var expectedIdentifiers: [String]

    var expected: String? { output.value }
}

func makeSample() -> TrailRequest {
    TrailRequest(
        input: ModelSampleInput(prompt: Prompt("Find me coastal hikes")),
        output: ModelSampleOutput(
            value: "I found 4 coastal trails.",
            expectations: TrajectoryExpectation(
                unordered: [
                    ToolExpectation("searchSpotlight", arguments: [.keyOnly(argumentName: "query")])
                ]
            )
        ),
        expectedIdentifiers: ["trail:001", "trail:002", "trail:006", "trail:009"]
    )
}

TrajectoryExpectation 은 model 이 답에 이르는 동안 어떤 tool 을 불러야 하는지를 적는다. 여기서는 searchSpotlight 라는 tool 이 query 라는 argument 와 함께 불렸는지만 본다. .keyOnly 는 argument 의 값은 따지지 않고 key 가 있는지만 확인한다는 뜻이다. searchSpotlight 는 세션 화면에 나온 문자열을 그대로 옮긴 것이다. macOS 27.0.1 에서 SpotlightSearchTool().name 을 찍어 보면 spotlight_search 가 나온다. name 은 var 라서 바꿀 수 있으니, expectation 에 적는 문자열은 앱이 쓰는 tool 의 name 과 맞춘다.

세션 화면의 TrailRequest 에는 expected 가 없다. SDK 에서는 ModelSampleProtocol 이 물려받는 SampleProtocol 이 expected 를 요구해서, 없으면 conformance error 가 난다. makeSample() 은 아래 JSON 의 한 항목을 code 로 옮겨 본 것이다. Evaluations framework 는 SDK 의 기본 framework 경로가 아니라 platform 의 Developer/Library/Frameworks 에 들어 있어서, test target 에서 쓰는 것을 전제로 한 것으로 보인다.

ModelSampleProtocol

input 으로 ModelSampleInput, output 으로 ModelSampleOutput<ExpectedValue, Expectation> 을 요구하는 protocol 이다. ModelSampleInput 은 prompt 외에 instructions 와 generation schema 도 담을 수 있다. 문서는 ModelSampleProtocol 과 TrajectoryExpectation 에 있다.


seed sample 에서 dataset 까지

dataset 을 손으로 다 쓰지는 않는다. 몇 개의 seed sample 을 쓰고, Evaluations 의 Sample Generation API 로 수를 늘린다. 세션의 sample project 는 이 일을 하는 command line tool 을 따로 두고 있다.

출처: WWDC26 - LLM search using Core Spotlight

Xcode 에 열린 trail-items 파일이다. 항목마다 uniqueIdentifier, title, contentDescription, textContent, namedLocation, stateOrProvince, keywords, latitude, longitude, rating, duration, completionDate 가 있다. 첫 항목은 trail:001 Fitzgerald Marine Reserve 다. navigator 에는 project 이름 LLMSearchUsingCoreSpotlight 아래로 HikingTrails, SampleDataGenerator, TrailSearchEvals 가 보인다.

출처: WWDC26 - LLM search using Core Spotlight

trail-queries-seed 파일이다. 항목마다 query, expectedItemIdentifiers, samplePrompt 가 있다. 예를 들어 “Find me coastal hikes” 의 기대 identifier 는 trail:001, trail:002, trail:006, trail:009 고, sample 응답은 coastal trail 4개를 찾았다며 이름을 나열한다. “Which trails haven’t I hiked yet?” 처럼 부정이 들어간 질문도 seed 에 있다. scheme 선택란에는 SampleDataGenerator 와 My Mac 이 보인다.

SDK 에서 이 일을 하는 것은 SampleGenerator actor 와 배열의 makeSamples(_:targetCount:) 다. prompt 와 seed sample, 목표 개수를 받고 async sequence 로 sample 을 내놓는다. 세션은 이 호출 code 를 보여 주지 않아서 글에 싣지 않았다.


test 로 돌리는 평가

평가는 test target 에서 Swift Testing 의 test 하나로 돈다.

출처: WWDC26 - LLM search using Core Spotlight

화면의 test 는 trailSearchEval() 이다. 순서는 이렇다. item 과 sample 을 load 한다. Self.indexDelegate.indexSearchableItems(items) 로 item 을 Core Spotlight 에 donate 한다. Self.makeSearchTool() 로 tool 을 만든다. TrailSearchEvaluation(tool:dataset:) 에 tool 과 ArrayLoader(samples:) 를 넘기고 run() 한다. 마지막으로 result.aggregateValue(.mean(of: Metric("ResultCoverage"))) 로 평균을 구해 #expect(coverageMean >= 0.5, ...) 로 확인한다. 기준은 질문 전체에서 result coverage 평균 50% 이상이다.

이 test 는 code 블록으로 싣지 않았다. TrailSearchEvaluation 과 ResultCoverage 를 계산하는 evaluator, loadItems() 같은 helper 가 화면에 나오지 않아서, 옮기려면 대부분을 짐작으로 채워야 하기 때문이다. SDK 에서 확인한 것은 ArrayLoader(samples:), Evaluation protocol 의 run(), EvaluationResult 의 aggregateValue(_:), Metric(_:) 이 화면의 호출 모양대로 있다는 것까지다. Evaluation protocol 은 dataset, subject(from:), evaluators, aggregateMetrics(using:) 를 요구한다.


세션의 마무리

발표자는 이제 search query 를 직접 쓰지 않게 됐다는 말로 맺는다. query 를 만드는 것은 model 이고, 앱은 index 를 채우고 model 이 그 index 를 어떻게 쓸 수 있는지를 설명해 주는 쪽으로 일이 옮겨 간다.

출처: WWDC26 - LLM search using Core Spotlight

next steps slide 는 LLM search sample code 와 Evaluations deep dive 두 줄이고, 아래에 “Bring an LLM provider to the Foundation Models framework” 와 “Create robust evaluations for an agentic app” 이 관련 세션으로 걸려 있다. tool 이 Foundation Models 안에서 어디에 놓이는지는 What’s new in the Foundation Models framework 정리 에서, tool 여러 개를 엮는 구성은 Build agentic app experiences 정리 에서 다뤘다.


정리

하고 싶은 것쓰는 것
model 이 앱의 index 를 검색하게 하기SpotlightSearchTool() 을 session 의 tools 에 추가
sandbox 의 파일 검색Configuration(sources: [.files])
model 에게 원문과 추가 attribute 주기index delegate 의 searchableItems(forIdentifiers:)
검색된 item 을 목록으로 표시tool.searchResults 와 queryToken
쓰지 않는 검색 능력 빼기GuidanceProfile 과 .dynamic, 또는 .focused
“나” 같은 지칭 풀기Configuration 의 contactResolver
검색 결과 위에 앱만의 계산 얹기CustomStage 와 customStages
응답 품질 재기Evaluations 의 ModelSampleProtocol, TrajectoryExpectation

실제 프로젝트에 가져갈 점은 다음과 같다.

  • SpotlightSearchTool 은 CoreSpotlight 와 FoundationModels 를 둘 다 import 해야 보인다.
  • 이미 Core Spotlight 에 content 를 donate 하고 있다면 tool 은 한 줄로 붙는다. donate 가 없다면 그것이 먼저다.
  • text content 는 index 에 원문으로 남지 않는다. model 이 메모 본문을 읽어야 하는 앱이라면 searchableItems(forIdentifiers:) 를 구현해 둔다.
  • 목록 UI 는 session 응답이 아니라 searchResults 에서 만든다. queryToken 이 바뀔 때만 화면을 비운다.
  • Configuration 을 직접 만들 때는 sources 를 적는다. 기본값이 빈 배열이다.
  • on-device model 을 쓴다면 guidance 를 .focused 나 .dynamic 으로 줄여 context 를 아낀다.
  • custom stage 는 inputTypes 에 적은 종류의 execute 만 구현한다. 이름과 설명은 model 이 읽는 글이니 구체적으로 쓴다.
  • 세션 page 의 snippet 은 Xcode 27 SDK 와 여러 곳이 다르다. 붙여 넣기 전에 선언을 확인한다.

참고자료

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.