포스트

[WWDC26] Create robust evaluations for agentic apps

이 글은 WWDC 세션의 transcript 와 영상 화면을 Claude Code 로 정리한 글이다. code 는 세션 snippet 을 기본으로 하고, macOS 27 SDK 와 Xcode 27 에서 Swift 5 mode 와 Swift 6 mode 모두 -emit-sil 까지 통과시킨 sample 로 다시 만들었다. 세션 code 그대로는 compile 되지 않는 곳이 있어 그 부분은 본문에서 따로 밝혔다.

Evaluations framework 는 intelligence 로 동작하는 기능이 잘 되고 있는지 재고, 시간에 따른 개선을 추적하고, production 에서 품질을 지키게 해 주는 framework 다. Xcode 27 에서 새로 나왔고 macOS, iOS, watchOS, visionOS 를 지원한다. 세션 Create robust evaluations for agentic apps 은 Evaluations 팀 engineer 인 Ada 와 Kyle 이 진행한다.

기본 개념은 Meet the Evaluations framework 에서, 개선 전략은 Improve your prompts by hill-climbing with Evaluations 에서 다뤘고, 이 세션은 평가가 복잡해지고 커질 때의 문제를 다룬다. 이 블로그의 Meet the Evaluations framework 정리 글에서 기본 개념을 볼 수 있다. Meet the Evaluations framework 에서 소개한 hill-climbing 은 한 걸음 고쳐 보고 재서 나아졌으면 그 방향으로 계속 오르는 방식으로, intelligence 기능을 만들고, 시험하고, 출시하는 과정을 그린 것이다. 이 세션은 그중 Develop 과 Evaluate 단계에 집중한다.

Hill-climbing 그림에서 Develop 상자가 강조되어 있고 Evaluate 상자로 화살표가 이어진다 출처: WWDC26 - Create robust evaluations for agentic apps

Develop 상자에는 “Implement changes”, “Test hypothesis” 라는 설명이 붙어 있고, 파란 화살표가 초록색 Evaluate 상자로 이어진다. 세션은 이 두 단계에서 두 가지를 다룬다. 하나는 synthetic data 로 evaluation dataset 을 넓히는 것이고, 다른 하나는 tool calling 이라는 model 행동을 쓰는 agentic workflow(model 이 스스로 tool 을 골라 여러 단계를 밟는 흐름)의 평가다. 예제는 BookTracker 라는 개인 서재 앱이다.


13개 sample로는 좁은 dataset

Develop 단계에서는 보통 몇 개 안 되는 sample 로 evaluation 을 시작한다. 그런데 기능은 거의 언제나 dataset 이 담는 것보다 복잡하다. sample 을 쓰는 데는 시간이 들고, 늘리기도 어렵고, 실제 세상에서 기능이 어떻게 동작하는지 알려면 필요한 다양함을 거의 담지 못한다. 발표자의 말로 evaluation 결과의 질은 그 뒤에 있는 data 만큼만 좋고, 좋은 evaluation data 를 쓰는 일은 어렵다.

Framework 는 sample 생성을 전부 code 로 정의하는 API 를 내놓는다. 그래서 자기만의 생성 pipeline 을 만들어 command line 에서 돌리거나 이미 쓰는 workflow 에 끼워 넣을 수 있다. text 기반 data 를 지원하고, @Generable macro(model 이 정해진 구조의 값을 생성하게 해 주는 macro)를 이용해 구조가 있는 synthetic data 를 만든다.

BookTracker 는 작성한 review 를 바탕으로 책에 tag 를 자동으로 붙이는 intelligence 기능이 있는 앱이다. Book 은 title, author, review, tags, rating 을 가지고, 표지 디자인에 쓰는 변수도 있다. Book.sampleBooks 는 Book 13개가 담긴 배열이고 첫 번째 예가 Pride and Prejudice 에 대한 review 다.

13개는 괜찮은 출발점처럼 보여도 기능이 어떻게 동작하는지를 보여 주는 창이 좁다. 이 dataset 으로 낸 evaluation 결과는 훌륭해 보이면서도 완전히 오해를 부를 수 있다. 발표자는 이 기능이 마주칠 data 의 다양함을 이렇게 든다.

  • 책은 수없이 많다.
  • 장르는 수백 개다.
  • 방금 읽은 책을 사용자가 평하는 방식도 다양하다.
  • 현실에서는 요약이 모호하거나 불완전한 경우도 있다.

13개로는 이것을 다 담을 수 없다. 필요한 것은 더 많은 coverage 이고, 예제를 손으로 쓰느라 며칠을 쓰지 않고 얻어야 한다.


Synthetic data란?

synthetic data 는 사람이 직접 쓰지 않고 model 이 만들어 낸 sample 이다. 이 세션에서는 기존 sample 을 model 에게 보여 주고 “이런 것을 더 만들어 달라” 고 해서 dataset 을 넓힌다. 비유하자면 입시 문제집에 기출 문제 13개가 있을 때, 그것을 본 출제 위원이 비슷한 결의 새 문제를 87개 더 내서 100문제짜리 모의고사로 만드는 일이다. 기출 13문제가 몇 단원만 다루고 있으면 점수가 잘 나와도 다른 단원의 실력은 점수에 드러나지 않는다. 문제를 넓혀 단원을 고루 덮을수록 점수가 실제 실력을 닮아 간다.

다만 출제 위원이 낸 문제에는 오류가 섞일 수 있다. 그래서 만든 sample 을 걸러 내는 단계(validator)가 같이 따라오고, 만든 뒤에 dataset 이 대표성을 갖는지 살피는 일도 사람이 해야 한다.


makeSamples로 dataset 늘리기

가장 단순한 방법은 makeSamples 다. 필요한 것은 세 가지다. prompt, dataset, 그리고 synthetic 으로 만들고 싶은 sample 수인 target count 다. target count 에는 이미 가진 dataset 도 포함된다.

code 오른쪽에 Prompt, Dataset, Target count 세 라벨이 있고 Target count 가 강조되어 있다 출처: WWDC26 - Create robust evaluations for agentic apps

왼쪽 code 가 prompt, dataset, targetCount 세 변수를 차례로 정의하고, 오른쪽의 세 라벨 중 Target count 만 파랗게 켜져 있다. code 는 이렇다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let prompt = Prompt("""
    Generate diverse range of book reviews and corresponding tags.
    Cover a wide range of genres, time periods, cultures, and
    reader personas. Do not repeat books already in the dataset.
    """)

let dataset = Book.sampleBooks.map { book in
    ModelSample(prompt: book.review, expected: BookTags(tags: book.tags))
}

let targetCount = 100
var expandedDataset = dataset

for try await sample in dataset.makeSamples(prompt, targetCount: targetCount) {
    expandedDataset.append(sample)
    print("Generated \(expandedDataset.count) samples so far.")
}

makeSamples로 dataset 넓히기

  1. Prompt 는 Foundation Models 의 prompt type 이다. 여기서는 model 에게 더 다양한 book review sample 을 제안하라고 시킨다. 발표자는 좋은 prompt 를 쓰려면 model 이 과제를 이해하고 사용자가 줄 수 있는 입력의 폭을 다루는 데 무슨 정보가 필요한지 생각하라고 한다. 위 prompt 는 장르, 시대, 문화, reader persona 를 넓게 덮고 이미 dataset 에 있는 책은 반복하지 말라고 쓴다.
  2. ModelSample 는 이번에 새로 나온 sample type 이다. 여기서는 책의 review 를 prompt 로, 책의 tags 를 기대하는 출력(expected)으로 담는다. BookTags 는 tags 배열을 가진 @Generable struct 로 앱이 정의한 type 이다.
  3. makeSamples(_:targetCount:) 는 dataset 에 붙는 method 이고 새로 만들어진 sample 의 async stream 을 돌려준다. for try await 로 돌면서 만들어진 sample 을 expandedDataset 에 붙인다. expandedDataset 은 처음 dataset 으로 초기화해 두었다. async stream 은 결과가 하나씩 도착하는 대로 받는 흐름이다.
  4. targetCount 는 최종 dataset 의 전체 크기다. 시작할 때의 sample 을 포함하므로 13개로 시작해 100 을 주면 model 이 실제로 만드는 것은 87개다. 기본으로는 on-device model(기기 안에서 도는 model)이 생성에 쓰인다.

얼마나 만들어야 하나

Target count 라는 제목 아래 What, Who, How 세 아이콘이 나란히 있다 출처: WWDC26 - Create robust evaluations for agentic apps

물음표 원, 사람, 점선 경로가 각각 What, Who, How 에 붙어 있다. “얼마나 있어야 충분한가” 에 대한 발표자의 답은 “경우에 따라 다르다” 이고, 이 세 질문이 그 기준이다. 올바른 target count 는 전적으로 기능에 달려 있다.

  • What: 그 기능이 무엇을 하는가.
  • Who: 누가 쓰는가.
  • How: 사람들이 얼마나 다양한 방식으로 그것을 다루는가.

BookTracker 에서 100개는 시작점일 뿐이다. synthetic data 생성은 대개 반복 과정이다. 초기 dataset 을 정의하고, synthetic data 를 만들고, sample 을 검증하고, 그 data 가 대표성이 충분한지 분석하고, 확신이 설 때까지 이 순환을 이어 간다. 양보다 훨씬 중요한 것은 coverage 다. “sample 이 몇 개나 필요한가” 대신 “이 기능이 실제로 쓰일 의미 있는 다양함을 덮었는가” 를 물으라는 것이 세션의 말이다.


SampleGenerator로 생성 과정 조절하기

on-device model 은 대부분의 경우 좋은 선택이다. 그래도 자기 model 을 쓰거나 model 이 따르는 instructions 를 바꾸고 싶을 수 있다. prompt, dataset, target count 를 넘는 설정이 필요하면 SampleGenerator 로 생성 과정 전체를 조절한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let generator = SampleGenerator<ModelSample<BookTags>>(
    prompt,
    samples: dataset,
    targetCount: targetCount,
    sessionProvider: {
        LanguageModelSession(
            model: PrivateCloudComputeLanguageModel(),
            instructions: """
                You are a synthetic data generator for a book-tracking app's evaluation suite.
                Your job is to produce realistic, diverse book entries that will stress-test
                a tagging system.

                Rules:
                - Review must be at least 100 characters long.
                - Review should cover a mix of genre, mood/tone, and themes.
                - Reviews should vary in length.
                - Create between 3 and 8 tags.
                - Tags must be lowercase.
                """
        )
    }
)

sessionProvider로 생성 model 정하기

  1. SampleGenerator 는 initializer 에 prompt, 초기 sample(samples:), targetCount, sessionProvider 를 받는다. 이 밖에 samplingStrategy: 와 validator: 도 받는다. 생성되는 sample 의 type 은 ModelSample<BookTags> 처럼 type parameter 로 고른다.
  2. sessionProvider 는 LanguageModelSession 을 돌려주는 closure 다. 어떤 model 이 생성을 맡고 어떤 system 수준 instructions 가 과제를 틀 지을지를 여기서 정한다.
  3. PrivateCloudComputeLanguageModel 은 Private Cloud Compute, 즉 Apple 서버에서 돌리는 더 큰 model 이다. 발표자는 context 가 더 크다는 이유로 이 model 을 골랐다.
  4. instructions 에는 특정 책, 장르, mood 에 생성을 맞추는 custom instructions 와 생성되는 sample 이 지켜야 할 rule 다섯 개를 적는다. review 는 100자 이상, 장르와 mood/tone 과 theme 을 섞기, review 길이 달리하기, tag 3개에서 8개, tag 는 소문자다.

Session과 batch

생성 중에 session 이 어떻게 쓰이는지를 알아 두어야 한다. framework 는 batch size 를 자동으로 정한다. batch 는 생성 중에 한 번에 묶어 처리하는 sample 묶음이고 그 개수가 batch size 다.

sessionProvider 상자 하나 안에 Batch 1, Batch 2, Batch 3 이 위에서 아래로 쌓여 있다 출처: WWDC26 - Create robust evaluations for agentic apps

generator 는 run 이 시작될 때 sessionProvider 를 한 번 부르고, 그 session 을 batch 사이에 재사용한다. 그래서 생성이 진행되는 동안 model 이 context 를 유지한다. 그림에서 세 batch 가 같은 상자 하나 안에 들어 있는 것이 이 뜻이다.

그런데 session 은 커질 수 있는 크기에 한계가 있다. 요청이 많거나, prompt 가 크거나, 출력이 큰 경우에는 run 도중 session 의 context window(model 이 한 번에 붙들 수 있는 대화 분량의 한도)를 다 써 버릴 수 있고, 그러면 error 가 던져진다.

왼쪽 sessionProvider 상자는 Batch 3 이 상자 아래로 넘쳐 있고, 오른쪽에 경고 표시와 함께 새 sessionProvider 상자가 Batch 2 까지 채워져 있다 출처: WWDC26 - Create robust evaluations for agentic apps

왼쪽 상자는 세 batch 가 모두 차서 넘쳐 있고, 오른쪽 위에 주황색 경고 표시가 있다. 오른쪽에 같은 sessionProvider 상자가 새로 시작되어 Batch 1 과 Batch 2 는 차 있고 Batch 3 은 비어 있다. 이때 generator 는 sessionProvider 를 다시 불러 새 session 을 얻고 생성을 이어 간다. 새 session 에는 이전 session 의 context 가 없다. 그래서 sessionProvider 의 instructions 는 그 자체로 완결되게 써야 하고, 한 번만 불릴 것이라고 가정하면 안 된다. context size 한계를 완화하는 방법은 Build agentic app experiences with the Foundation Models framework 세션에서 더 다룬다.


Sampling strategy

custom session provider 를 쓰면 samplingStrategy 도 고를 수 있다. 이 값은 generator 가 초기 dataset 에서 어떤 sample 을 골라 model 에게 in-context 예제(prompt 안에 함께 넣어 보여 주는 예제)로 보여 줄지를 정한다. SDK 에서는 SampleGenerator 의 initializer 에 samplingStrategy: parameter 로 들어가고, 값은 .random(retries: Int = 5) 와 .slidingWindow 다. 전략은 두 종류다.

Initial samples 줄에는 띄엄띄엄 떨어진 sample 이 남아 있고, Selected samples 줄에 여러 색의 sample 여섯 개가 모여 있다 출처: WWDC26 - Create robust evaluations for agentic apps

첫째는 random 이다. 초기 sample 의 무작위 부분집합을 예제로 고르되 중복이 없게 한다. 초기 sample 의 순서를 신경 써서 생각하지 않아도 출력이 다양하게 유지된다. 그림에서 Initial samples 줄의 sample 들이 띄엄띄엄 떨어져 있고, Selected samples 줄에는 여러 색이 섞여 올라와 있다.

Initial samples 줄에서 이어진 구간이 Selected samples 줄에 순서대로 선택되어 있다 출처: WWDC26 - Create robust evaluations for agentic apps

둘째는 sliding window 다. 초기 sample 을 순서대로 한 구간씩 따라가며 중복은 건너뛴다. dataset 의 순서에 의미가 있다면 이 전략을 고려한다. 그림에서는 Initial samples 줄 오른쪽 끝에 window 경계로 보이는 세로 막대가 있고, Selected samples 줄에는 여섯 sample 이 모여 있다.

BookTracker 의 초기 sample 은 순서에 의미가 없으므로 random 을 쓴다. random 이 기본값이라서 코드에 따로 적지 않았다. 이제 generator 의 run() 을 부르면 새로 합성된 sample 의 stream 이 나오고, 각 sample 을 앞서 정의한 expandedDataset 에 붙인다.


Validator로 생성 결과 걸러내기

Validation 이라는 제목 아래 rule 다섯 줄이 있고 Length of review varies 만 주황색이다 출처: WWDC26 - Create robust evaluations for agentic apps

만든 data 가 기대한 모양인지 확인하는 것이 validator closure 다. validator 는 만들어진 sample 마다 받아들일지 거절할지를 정하는 자기만의 논리를 쓰게 해 준다. session provider 의 instructions 에 rule 을 이미 적었지만, 그것이 출력이 rule 을 따른다는 보장은 아니다.

  • review 는 최소 100자다.
  • review 는 서로 다른 장르, mood, tone 을 다룬다.
  • review 의 길이가 다양하다.
  • book tag 는 3개에서 8개다.
  • tag 는 소문자다.

무엇을 체계적으로 확인할 수 있는지를 따져야 한다. 두 가지를 먼저 알아야 한다. validation closure 는 sample 하나하나를 따로 놓고 검증하며 다른 sample 에 대한 context 가 없다. 그러니 review 의 다양함은 단순한 검증을 넘는 판단이 필요하고, review 길이가 다양한지는 모든 sample 을 가로질러 봐야 한다. 그림에서 “Length of review varies” 가 주황색인 것이 이 때문이다. 나머지 세 rule(100자 이상, tag 3개에서 8개, 소문자)은 sample 하나만 보고 체계적으로 판단할 수 있어서 validation closure 로 맡긴다.

Tag count validation 이라는 제목 아래 Frankenstein 표지가 있고 tag 2개짜리는 빨간 X, tag 7개짜리는 초록 체크로 표시되어 있다 출처: WWDC26 - Create robust evaluations for agentic apps

발표자는 Mary Shelley 의 Frankenstein 을 예로 든다. 생성된 sample 이 review 를 100자 이상으로 정의했는지 확인하고, model 이 review 마다 만드는 tag 가 3개에서 8개인지 확인한다. 그림에서 ["classic", "gothic"] 두 개짜리는 X 이고 ["classic", "gothic", "horror", "tragic", "science fiction", "morality", "philosophical"] 일곱 개짜리는 체크다. 마지막으로 tag 가 모두 소문자인지 확인한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
validator: { sample in
    guard let book = sample.expected else { return false }

    // Review must be at least 100 characters
    guard sample.promptDescription.count >= 100 else { return false }

    // Must have between 3 and 8 tags
    guard (3...8).contains(book.tags.count) else { return false }

    // All tags must be lowercase
    guard book.tags.allSatisfy({ $0 == $0.lowercased() }) else { return false }

    return true
}

validator closure로 sample 받아들이기

validator 는 SampleGenerator 의 initializer 에 넘기는 closure 이고 sample 하나를 받아 Bool 을 돌려준다. true 면 받아들이고 false 면 거절한다.

  1. sample.expected 는 sample 이 가진 기대 출력이다. 여기서는 BookTags 이고 없으면 거절한다.
  2. sample.promptDescription 은 sample 의 prompt 를 문자열로 본 것이다. 이 sample 의 prompt 는 book 의 review 이므로 count 가 100 이상인지가 review 길이 rule 이다.
  3. (3...8).contains(book.tags.count) 는 tag 개수 rule 이다.
  4. allSatisfy 는 배열의 모든 원소가 조건을 만족하는지 확인하고, lowercased() 는 문자열을 소문자로 바꾼다. 소문자로 바꾼 값과 같은지 비교해 모든 tag 가 소문자인지 확인한다.

위 code 의 closure 는 initializer 의 validator: 자리에 놓는다. 세션 화면은 이 closure 만 보여 준다. 아래는 앞의 두 조각을 initializer 에 끼운 자리를 보여 주는 축약이고, /* */ 자리는 위의 code 로 채운다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let generator = SampleGenerator<ModelSample<BookTags>>(
    prompt,
    samples: dataset,
    targetCount: targetCount,
    sessionProvider: { /* 위의 LanguageModelSession */ },
    validator: { sample in /* 위의 closure */ }
)

for try await sample in generator.run() {
    // During iteration
    expandedDataset.append(sample)
}

// After iteration
let allSamples = await generator.samples
let invalidSamples = await generator.invalidSamples

print("Generated \(allSamples.count) new samples. Total: \(expandedDataset.count)")

samples와 invalidSamples로 결과 읽기

generator 의 run() 은 새로 합성된 sample 을 하나씩 내보내는 async stream 을 돌려준다. 생성이 진행되는 동안 유효한 sample 은 generator 의 samples property 에 모인다. validator 를 통과하지 못한 sample 은 자동으로 따로 invalidSamples 에 놓인다. 둘 다 run 이 도는 동안 실시간으로 갱신되므로 반복 중에 진행 상황을 보려고 읽어도 되고, loop 가 끝난 뒤에 읽어도 된다. 읽을 때 await 가 붙는다. SampleGenerator 가 actor(한 번에 한 작업만 자기 상태에 접근하게 지켜 주는 type)이기 때문이다. 얻은 결과는 앱에서 바로 쓰거나 dataset 을 로컬에 저장할 수 있다.


넓힌 dataset으로 다시 평가하기

Xcode 27 은 결과를 시각화하는 새 Evaluations Report 를 도입했다. 13개 초기 sample 로 돌린 BookTaggingEvaluation 에서는 tag 의 relevance 와 usefulness 를 평가한 tag quality 점수가 꽤 높았다. 같은 evaluation 을 새 100개 dataset 으로 돌린 것이 SyntheticBookTaggingEvaluation 이고, Compare 버튼으로 둘을 비교했다.

Xcode 의 Evaluations report 에 SyntheticBookTaggingEvaluation 결과 표가 열려 있고 오른쪽 위에 Compare 버튼이 있다 출처: WWDC26 - Create robust evaluations for agentic apps

결과 표의 제목이 SyntheticBookTaggingEvaluation 이고 부제에 “100 responses”, 실행 시간 7분 10초가 적혀 있다. 열은 Prompt, Tag Count, Tag Total, Word Count, Has Genre Tag, Relevance, Usefulness 다. 각 행은 sample 하나이고 Tag Count, Word Count, Has Genre Tag 칸에는 초록 체크가 붙어 있는데 Wilde 의 prose 를 다룬 행의 Has Genre Tag 칸만 빨간 X 다. Relevance 와 Usefulness 칸에는 점수가 숫자로 들어 있다. 오른쪽 위의 Compare 가 앞의 13개 evaluation 과 이 100개 evaluation 을 나란히 놓는 버튼이다.

발표자는 점수가 떨어질 것이라 예상했고 그 예상이 맞았다. quality 점수가 내려갔다. tag 생성 기능이 이전에 잘하는 것처럼 보인 이유는 포괄적인 dataset 으로 시험하지 않았기 때문이다. 더 큰 dataset 으로 evaluation 을 돌려서 드러난 점수 하락은 여러 가지를 뜻할 수 있다.

Suggestions 라는 제목 아래 Prompt and instructions, Intelligence feature, Evaluation, Dataset 네 줄이 있다 출처: WWDC26 - Create robust evaluations for agentic apps

  • Prompt and instructions: 점수 변화가 prompt 나 instructions 의 문제 때문일 수 있다. 둘 중 하나 또는 둘 다를 다듬어 필요한 바를 더 잘 담는다.
  • Intelligence feature: intelligence 기능 자체에 빈틈이 있다는 신호일 수 있다.
  • Evaluation: evaluation 을 조정해서 실제로 무엇을 평가하고 있는지 이해하고 싶을 수 있다.
  • Dataset: dataset 이 아직 대표성이 부족해서 더 많은 변화를 담아야 할 수 있다. synthetic data API 로 dataset 을 계속 늘리거나 edge case 를 더 넣는다.

이 넷이 결과를 더 개선하는 핵심 방법이라는 것이 세션의 말이다.


Tool call 평가가 필요한 이유

지금까지는 tag 라는 model 이 만든 것을 평가했다. 그런데 intelligence 기능은 출력을 만들려고 눈에 보이지 않는 단계를 여럿 밟는 경우가 많다. 앱 안에서 여러 동작을 하고 그 동작 하나하나가 결과에 기여한다. 예를 들어 검색 같은 과제다. 여기서 tool calling 이 나온다.


Tool calling이란?

tool calling 은 model 이 답을 직접 지어내는 대신, 앱이 정의해 둔 함수를 이름과 argument 로 불러 달라고 요청하는 방식이다. 앱이 그 함수를 실행해 결과를 돌려주면 model 이 그 결과를 보고 답한다. 비서(model)가 모르는 것을 짐작으로 대답하지 않고 담당 부서(tool)에 전화를 걸어 묻고, 받은 답을 정리해 전하는 것과 같다. 어느 부서에 걸지(tool 이름), 무엇을 물을지(argument), 어떤 순서로 걸지가 모두 평가의 대상이 된다.


Tool의 쓰임과 평가의 어려움

Tools 라는 제목 아래 Real-world data, Business logic, User-visible actions 세 줄과 손가락 icon 이 있다 출처: WWDC26 - Create robust evaluations for agentic apps

tool 은 model workflow 가 사용자를 위해 과제를 끝낼 때 구조를 더해 준다. 세션은 tool 이 쓰이는 방식을 셋으로 든다.

  • Real-world data: 사람들이 매일 쓰는 실제 data 위에서 동작한다.
  • Business logic: 개발자가 정의한 어떤 custom business logic 으로도 동작한다.
  • User-visible actions: 사용자가 직접 부를 수 있는 기능, 완전히 새로운 intelligence 기능용 logic, 또는 둘 다를 부를 수 있다.

여기서 문제가 있다. model 은 올바른 tool 을 한 번도 부르지 않고도 그럴듯한 답을 줄 수 있다. 최종 출력은 맞아 보여도 거기에 이른 경로가 맞지 않을 수 있다.

Challenges 라는 제목 아래 Instruction following, Schema complexity, Edge cases 세 줄이 있다 출처: WWDC26 - Create robust evaluations for agentic apps

세션은 세 가지 어려움을 든다.

  • Instruction following: model 에게 각 tool 을 어떻게 쓰는지 알려 줘야 하고, 세부에 기울이는 주의가 중요하다. 지시를 단어 하나하나 그대로 따라 해 보면 한 단계를 놓치는지 알 수 있다고 한다.
  • Schema complexity: 발표에서는 tool complexity 라고 부르고 화면 라벨은 Schema complexity 다. schema 는 tool 이 받는 argument 의 구조 정의(어떤 이름의 값이 어떤 type 으로 들어오는지)다. tool 은 단순한 지시를 받을 수도 있고 parameter 범위를 정교하게 맞추라고 요구할 수도 있다.
  • Edge cases: tool 이 흔한 입력에서는 잘 동작하는 듯해도 드문 입력에서는 놀라운 행동을 할 수 있다.

Tool evaluations 라는 제목 아래 Correct tools called, All arguments passed, Expected order 세 줄이 있고 오른쪽에 발표자가 있다 출처: WWDC26 - Create robust evaluations for agentic apps

그래서 tool evaluation 이 필요하다. what 이 아니라 how 를 검증하게 해 준다. 확인할 것은 넷이다.

  • model 이 올바른 tool 을 부른다.
  • 올바른 argument 로 부른다.
  • 기대한 순서로 부른다.
  • 중간에 예상 밖의 tool call 이 없다.

BookTracker의 library assistant

Tool examples 라는 제목 아래 searchBooks, getBookDetails, findSimilarBooks 세 이름이 있고 오른쪽 phone 에 BookTracker 의 책 목록과 Fiction 검색창이 있다 출처: WWDC26 - Create robust evaluations for agentic apps

화면의 phone 은 All, Title, Author, Tags 필터가 있는 책 목록이고 Alice’s Adventures in Wonderland, Dongui Bogam, Frankenstein, Romance of the Three Kingdoms 가 보이며 아래 검색창에 Fiction 이 입력되어 있다.

BookTracker 에 library assistant 가 추가되었다. 사용자가 책을 검색하면 제목과 다른 문자열만 걸러 내는 대신 model 이 앱의 custom tool 을 써서 관련된 책을 찾는다. tool 은 셋이다.

  • searchBooks: 비슷한 tag 를 가진 책일 수 있는 것을 찾는다.
  • getBookDetails: 검색 결과에서 출간일 같은 책의 metadata 를 뽑는다.
  • findSimilarBooks: 비슷한 책을 semantic search(글자가 같은지가 아니라 뜻이 가까운지로 찾는 검색)로 찾는다.

여러 단계가 이어지고 각 단계가 tool call 이다.

SearchBooksTool 은 이렇게 생겼다. 세션은 name 과 description 을 가진 SearchBooksTool 과 별도의 struct SearchBooksArguments 를 차례로 보여 준다. Tool protocol 이 Arguments 라는 type 을 요구해서 sample 은 이 struct 를 SearchBooksTool 안의 중첩 struct Arguments 로 옮겼다.

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
struct SearchBooksTool: Tool {
    let name = "searchBooks"
    let description = "Searches the user's personal book library"

    @Generable
    struct Arguments {
        @Guide(description: "A freeform search term to match against titles, reviews, or tags")
        var query: String?
        @Guide(description: "Filter results to books with this specific tag")
        var tag: String?
        @Guide(description: "Filter results by mood")
        var mood: String?
        @Guide(description: "Filter results by genre")
        var genre: String?
        @Guide(description: "Maximum number of results to return. Defaults to 5.")
        var limit: Int?
    }

    func call(arguments: Arguments) async throws -> String {
        Book.sampleBooks
            .filter { book in arguments.tag.map { book.tags.contains($0) } ?? true }
            .prefix(arguments.limit ?? 5)
            .map { "\($0.id): \($0.title)" }
            .joined(separator: "\n")
    }
}

세션은 call 의 본문을 보여 주지 않는다. 위 본문은 compile 을 위해 Book.sampleBooks 를 tag 로만 거르게 쓴 sample 구현이다. name, description 문구, argument 는 세션과 같고 call 본문은 sample 이 채웠다. getBookDetails 도 같은 방식의 GetBookDetailsTool 로 만들었다.

Tool protocol로 tool 정의하기

  1. Tool 은 model 이 부를 수 있는 tool 을 정의하는 protocol 이다. name 은 model 이 보는 이름이고 description 은 이 tool 이 언제 유용한지 model 에게 알려 준다.
  2. Arguments 는 @Generable struct 다. @Generable 는 model 이 이 type 의 값을 직접 생성할 수 있게 하는 macro 이고, model 이 tool 을 부를 때 채우는 argument 가 이 struct 가 된다.
  3. @Guide 는 property 마다 model 에게 그 값이 무엇인지 알려 주는 설명을 붙이는 macro 다.
  4. call(arguments:) 는 tool 이 실제로 하는 일이고, 돌려주는 String 이 model 에게 tool 결과로 전달된다.

argument 가 전부 optional 인 것에 주목하라고 발표자는 말한다. model 이 사용자가 물은 내용을 보고 어떤 filter 를 쓸지 스스로 정한다. “find gothic books” 라고 prompt 하면 tag argument 가 채워질 것이라 기대하고, “show me something cheerful” 이라고 하면 mood 검색을 만들 것이라 기대한다. 이런 판단이 바로 평가하고 싶은 것이다.


Trajectory expectation으로 경로 적기

trajectory 는 지나온 경로라는 뜻이다. tool evaluation 은 최종 답이 아니라 model 이 거친 경로를 확인하고, 그 경로를 적는 것이 trajectory expectation 이다.


Trajectory expectation이란?

tool evaluation 의 주된 구성 요소가 trajectory expectation 이다. session transcript(session 에서 오간 prompt, response, tool call 의 기록)에는 prompt 와 response 사이에 tool call 이 섞여 있다. trajectory expectation 은 language model session 에서 일어난 tool call 의 종류와 순서를 확인한다.

Trajectory expectations 라는 제목 아래 Tool type, Order, Arguments 세 줄이 있고 오른쪽 session transcript 의 Prompt, Response 열에 말풍선과 망치 icon 이 늘어서 있다 출처: WWDC26 - Create robust evaluations for agentic apps

오른쪽의 session transcript 는 Prompt 열과 Response 열로 나뉘어 있고, 대괄호로 감싼 안에 말풍선과 망치(tool call) icon 이 순서대로 놓여 있다. 왼쪽 세 줄이 expectation 이 확인하는 세 가지다. 어떤 tool 인지, 어떤 순서인지, 어떤 argument 인지다.

지도 앱의 Directions 화면에서 Golden Gate Park 에서 San Francisco City Hall 까지 경로가 있고 이동 수단 탭 하나가 선택되어 있으며 왼쪽에 빨간 X 가 있다 출처: WWDC26 - Create robust evaluations for agentic apps

발표자는 경로를 계획할 때 내린 결정 목록을 훑어보는 것에 비유한다. 차, 자전거, 버스는 모두 어딘가에 가는 데 각자의 때와 자리가 있는 tool 이고, 특정한 여행의 구간마다 그 쓸모를 평가할 수 있다. 지도 앱의 Directions 화면에서 이동 수단 탭(차, 도보, 대중교통, 자전거, 그 밖의 수단)을 바꾸는 것이 tool 을 고르는 일이고, 그림의 빨간 X 는 구간에 맞지 않는 수단을 골랐다는 표시로 읽힌다. expectation 은 모든 tool call 을 찾은 다음, 하나하나를 evaluation 에 적어 둔 expectation 과 맞춰 본다.


가장 단순한 expectation

prompt 가 “Find books tagged gothic” 이면 searchBooks tool call 이 하나 있기를 기대한다.

1
2
3
4
5
6
7
8
9
10
11
// "Find books tagged gothic"
TrajectoryExpectation(
    unordered: [
        ToolExpectation(
            "searchBooks",
            arguments: [
                .exact(argumentName: "tag", value: .string("gothic"))
            ]
        )
    ]
)

TrajectoryExpectation으로 기대하는 tool call 적기

  1. TrajectoryExpectation 은 model 의 transcript 에서 보기를 기대하는 tool call 을 서술한다. unordered 는 이 tool call 이 언제 일어나는지는 상관없고 일어나기만 하면 된다는 뜻이다.
  2. ToolExpectation 은 tool 하나에 대한 기대다. 첫 인자가 tool 의 이름이고 arguments: 에 argument 에 대한 기대를 배열로 적는다.
  3. .exact(argumentName:value:) 는 argument 의 값이 정확히 일치해야 한다는 matcher 다. 값은 ArgumentValue 로 쓰고 .string, .int, .double, .bool 이 있다. 여기서는 tag 가 "gothic" 이기를 기대한다.

의도로 argument 맞추기

정확한 일치가 늘 원하는 것은 아니다. prompt 가 “Find something cheerful” 이면 model 이 uplifting, happy, cheerful 어느 것을 넘겨도 괜찮다. .naturalLanguage matcher 는 정확한 문자열이 아니라 값이 의도에 맞는지를 확인한다.

1
2
3
4
5
6
7
8
9
10
// "Find something cheerful"
TrajectoryExpectation(
    expected: "searchBooks",
    arguments: [
        .naturalLanguage(
            argumentName: "mood",
            criteria: "Should relate to uplifting, hopeful, or positive feelings"
        )
    ]
)

세션 화면에는 첫 인자의 label 이 없는 TrajectoryExpectation("searchBooks", arguments: ...) 로 나오는데 단일 tool 용 initializer 의 첫 label 이 expected: 라서 그 형태는 missing argument label 'expected:' in call error 가 난다. 그래서 expected: 를 넣었다.

naturalLanguage로 값의 의도 확인하기

.naturalLanguage(argumentName:criteria:) 의 criteria 는 값이 만족해야 할 조건을 자연어로 쓴 것이고, 정확한 문자열이 아니라 값이 그 조건의 의도에 맞는지를 본다. init(expected:arguments:) 는 tool 하나의 이름과 그 argument 기대만 적는 initializer 다.


그 밖의 matcher

세션은 .contains, .oneOf, .pattern, .range 등이 더 있다고만 짚고, 자세한 내용은 개발자 문서를 보라고 한다. SDK 의 ArgumentMatcher 선언을 정리하면 이렇다.

matcher뜻
exact(argumentName:value:)값이 정확히 같다
keyOnly(argumentName:)값은 상관없고 그 argument 가 있기만 하면 된다
oneOf(argumentName:allowedValues:)허용한 값들 중 하나다
range(argumentName:minimum:maximum:)숫자가 최솟값과 최댓값 사이다
pattern(argumentName:regex:)정규식에 맞는다
contains(argumentName:substring:)문자열이 그 부분 문자열을 포함한다
hasPrefix, hasSuffix문자열이 주어진 글자로 시작하거나 끝난다
naturalLanguage(argumentName:criteria:)값이 자연어 조건의 의도에 맞는다

순서와 금지

여러 단계로 된 과제에서는 순서가 중요하다. model 은 먼저 searchBooks 를 부르고 그다음 getBookDetails 를 불러야 한다. agent 가 상세부터 얻으려 하면 아직 bookId 가 없으므로 그것은 bug 다. trajectory expectation 은 목적지만이 아니라 여정을 확인하므로 이것을 잡아낸다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// "Find gothic books and show details on the first"
TrajectoryExpectation(
    ordered: [
        ToolExpectation(
            "searchBooks",
            arguments: [
                .exact(argumentName: "tag", value: .string("gothic"))
            ]
        ),
        ToolExpectation(
            "getBookDetails",
            arguments: [
                .keyOnly(argumentName: "bookId")
            ]
        )
    ]
)

ordered와 keyOnly로 순서 적기

ordered: 에 적은 expectation 은 적은 순서대로 일어나야 한다. 일어나기만 하면 되는 unordered: 와 대비된다. .keyOnly(argumentName:) 는 값은 보지 않고 그 argument 가 채워져 있기만 하면 통과시키는 matcher 다. getBookDetails 의 bookId 는 값이 앞의 검색 결과에서 오는 것이라 미리 정할 수 없어서 keyOnly 로 적었다.

agent 가 하지 말아야 할 일이 하는 일만큼 중요할 때도 있다. prompt 에 “비슷한 책은 찾지 마” 같은 뜻이 들어 있으면 model 이 그 지시를 따라야 한다. disallowed 는 transcript 에 나타나면 안 되는 tool 을 정한다. agent 가 그래도 findSimilarBooks 를 부르면 실패다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// "Show only sci-fi books. Don't look for similar ones."
TrajectoryExpectation(
    unordered: [
        ToolExpectation(
            "searchBooks",
            arguments: [
                .naturalLanguage(
                    argumentName: "genre",
                    criteria: "Should refer to science fiction")
            ]
        )
    ],
    disallowed: [
        ToolExpectation("findSimilarBooks")
    ]
)

disallowed로 부르면 안 되는 tool 적기

disallowed: 는 transcript 에 나타나면 안 되는 tool 의 ToolExpectation 을 배열로 받는다. SDK 에서 TrajectoryExpectation 의 initializer 는 넷이다.

initializer쓰임
init(ordered:unordered:allowsAdditionalToolCalls:)순서 있는 것과 없는 것을 같이 적는다. allowsAdditionalToolCalls 의 기본값은 true 다
init(ordered:unordered:disallowed:)나타나면 안 되는 tool 을 같이 적는다
init(unordered:)순서 없는 expectation 만 적는다
init(expected:arguments:)tool 하나와 그 argument 만 적는다

ToolExpectation 의 initializer 는 init(_:arguments:) 이고 arguments 의 기본값이 빈 배열이라 disallowed 의 ToolExpectation("findSimilarBooks") 처럼 argument 없이 이름만 적을 수 있다.


ToolCallEvaluator로 채점하기

이제 expectation 이 evaluation 전체에서 어떻게 합쳐지는지 본다. 각 sample 에 prompt 와 trajectory expectation 을 담은 dataset 을 정의하고 ToolCallEvaluator 로 점수를 매긴다. 세션은 evaluator 가 tool 을 단 LanguageModelSession 으로 응답을 받고 structured transcript 를 잡는다고 설명한다. 아래는 compile 되는 형태다. 세션 화면은 expectation 자리를 비워 두었고, sample 은 앞의 gothic 검색 expectation 을 let basic = ... 으로 받아 넣었다. ModelSample<String> 으로 type 을 명시한 것도 sample 이 바꾼 점이다.

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
let basic = TrajectoryExpectation(
    unordered: [
        ToolExpectation(
            "searchBooks",
            arguments: [.exact(argumentName: "tag", value: .string("gothic"))]
        )
    ]
)

struct BookLibraryToolCallEval: Evaluation {
    var dataset = ArrayLoader(samples: [
        ModelSample<String>(
            prompt: "Find all the books tagged with 'gothic'.",
            instructions: "Help the user explore their book collection.",
            expectations: basic
        )
    ])

    let pass = Metric("All Passed")
    let percent = Metric("Percentage Passed")

    func subject(from sample: ModelSample<String>) async throws -> ModelSubject<String> {
        let session = LanguageModelSession(
            tools: [SearchBooksTool(), GetBookDetailsTool()],
            instructions: sample.instructions
        )
        let response = try await session.respond(to: sample.prompt)
        return ModelSubject(
            value: response.content,
            transcript: session.transcript.structuredTranscript
        )
    }

    var evaluators: Evaluators {
        ToolCallEvaluator(allPass: pass, percentagePass: percent)
    }

    func aggregateMetrics(using aggregator: inout MetricsAggregator) {
        aggregator.computeMean(of: pass)
        aggregator.computeMean(of: percent)
    }
}

ToolCallEvaluator로 tool call 채점하기

  1. Evaluation protocol 을 채택한 struct 가 evaluation 하나다. dataset 은 sample 의 묶음이고 여기서는 ArrayLoader 에 sample 배열을 담았다. sample 은 prompt, instructions, 그리고 expectations: 에 trajectory expectation 을 가진다.
  2. Metric 은 점수 하나의 이름표다. ToolCallEvaluator(allPass:percentagePass:) 에 두 Metric 을 넘긴다. ToolCallEvaluator 는 transcript 의 tool call 을 sample 의 expectation 과 맞춰 보고 두 점수를 낸다. all pass 는 expectation 을 전부 충족했는지(통과 아니면 실패)이고, percentage pass 는 충족한 비율이다.
  3. subject(from:) 는 sample 하나를 받아 평가 대상인 ModelSubject 를 만든다. tool 을 단 LanguageModelSession 을 만들어 응답을 받고, ModelSubject(value:transcript:) 의 transcript 에 session.transcript 의 structuredTranscript 를 실어 준다. 응답은 respond(to:) 로 받는다. 세션은 evaluator 쪽이 session 을 돌린다고 설명하지만 SDK 에서는 subject(from:) 가 session 을 돌리고, ToolCallEvaluator 는 ModelSubject 로 넘겨받은 transcript 만 채점한다.
  4. aggregateMetrics(using:) 는 sample 별 점수를 전체 점수로 모으는 곳이다. MetricsAggregator 의 computeMean(of:) 로 두 metric 의 평균을 낸다.

세션 code와 compile 되는 code의 차이

세션의 code 는 화면에 맞추려고 줄인 곳이 있어서 그대로 붙여 넣으면 build 가 실패한다. macOS 27 SDK 와 Xcode 27 에서 확인한 것은 셋이다.

세션 codeerror고친 형태
TrajectoryExpectation("searchBooks", arguments: [...])missing argument label 'expected:' in callTrajectoryExpectation(expected: "searchBooks", arguments:)
SampleArrayLoader(samples: [...]) (세션 페이지의 code 목록)cannot find 'SampleArrayLoader' in scopeArrayLoader(samples:)
dataset 과 evaluators 만 가진 BookLibraryToolCallEvaldoes not conform to protocol 'Evaluation'subject(from:) 와 aggregateMetrics(using:) 를 더한다

둘째 줄의 영상 화면 code 는 ArrayLoader(samples:) 이고, 세션 페이지의 code 목록만 SampleArrayLoader 로 적혀 있다. 셋째 줄이 가장 중요하다. 세션은 dataset 과 evaluators 만 보여 주지만 Evaluation protocol 은 subject(from:) 과 aggregateMetrics(using:) 도 요구하고 default 구현이 없다. 위 code 가 두 method 를 가진 이유다. 특히 subject(from:) 에서 tool 을 단 session 으로 응답을 받고 session.transcript.structuredTranscript 를 ModelSubject 에 실어야 ToolCallEvaluator 가 tool call 을 볼 수 있다. sample code 의 session 에는 searchBooks 와 getBookDetails 만 넣었고, report 에서 불리는 findSimilarBooks 는 sample code 에 정의하지 않았다.


Xcode report 읽기

tool call evaluation 의 결과는 다른 결과와 함께 Xcode 에 나온다. 그래서 intelligence 기반 기능이 어떻게 동작하는지의 전체 그림을 볼 수 있다.

Xcode report 의 SearchToolEvaluations 에서 All Passed 50%, Percentage Passed 57% 이고 오른쪽 패널에 한 sample 의 tool call 목록과 실패 이유가 보인다 출처: WWDC26 - Create robust evaluations for agentic apps

왼쪽은 SearchToolEvaluations 의 요약이다. “16 responses” 이고 All Passed 가 50%, Percentage Passed 가 57% 다. All Passed(Ratio) 50% 는 통과한 sample 의 비율이고 Percentage Passed(Average) 57% 는 sample 별 충족 비율의 평균이다. 그 아래 표에는 prompt 마다 All Passed 와 Percentage Passed 가 나열된다. 예를 들어 “cheerful” 은 100%, “classic” 은 0%, “Books similar to Treasure Isl…” 은 33% 이고, 이 행이 선택되어 오른쪽 패널이 열려 있다.

오른쪽 패널은 그 sample 의 상세다. 제목이 BookResults 이고 prompt 는 “Books similar to Treasure Island or something adventurous” 다. All Passed 는 Fail 이고 이유가 “Multiple argument and missing call violations” 로 적혀 있다. Percentage Passed 는 33% 이고 “1 of 3 expected conditions met” 다. 중간 표는 출력 값의 비교다. books 는 subject 가 5개인데 expected 가 2개라서 “Arrays do not match” 경고가 붙고, reason 은 Treasure Island 와 비슷한 모험과 고전 주제라는 문장이다.

가장 아래 표가 tool call 목록이다. Order 순서대로 이렇게 읽는다.

  1. searchBooks(genre: "adventure", limit: 5, query: "Treasure Island") 가 첫 호출이다. Result 칸에 “Expected argument: tag” 가 붙었다. expectation 은 tag argument 를 기대했는데 model 이 genre 와 query 를 넘긴 것이다.
  2. findSimilarBooks(bookId: ..., maxResults: 5) 가 둘째 호출이다. Result 가 비어 있고, 기대한 findSimilarBooks 를 충족한 호출이다.
  3. findSimilarBooks(bookId: ..., maxResults: 3) 가 셋째 호출이다. Result 가 “Additional tool call” 이다. 기대에 없는 추가 호출이라는 뜻이고, 아이콘은 빨간 X 가 아니라 회색 정보 표시다. 회색 정보 표시라 실패로 치지 않는다. 앞의 표에서 본 allowsAdditionalToolCalls 의 기본값 true 와 이어진다.
  4. 마지막 줄 getBookDetails(bookId: *) 는 Order 번호가 없고 Result 가 “Never called” 다. 기대에는 있는데 한 번도 불리지 않았다.

이 sample 의 기대 조건은 셋이다. searchBooks(tag), findSimilarBooks, getBookDetails 이고 결과는 차례로 argument 위반, 충족, Never called 라서 “1 of 3” 이고 33% 다. 추가 호출은 기대 조건에 세지 않아서 실패 이유에도 “Multiple argument and missing call violations” 만 적혀 있다. 최종 답이 그럴듯해 보여도 경로는 argument 와 빠진 호출 두 곳에서 어긋났다.


Tool evaluation용 synthetic data

tool evaluation 의 dataset 을 넓히는 일은 꽤 복잡한데 framework 가 이것을 쉽게 만들었다. tool call evaluation 이 쓰는 ModelSample 과 TrajectoryExpectation 이 모두 generable 이므로 앞에서처럼 sample generator 로 sample 을 합성한다.

tool evaluation 용 synthetic data 를 만들 때 주의할 점이 있다. model 은 개발자가 정의한 tool 이 무엇인지, tool 을 어떤 순서로 불러야 하는지 모른다. 그래서 instructions 에 쓸 수 있는 tool 을 목적과 함께 적고, 순서 요구와 model 이 필요로 할 다른 context 를 적는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let prompt = Prompt("""
    Generate diverse user queries for a personal book library assistant.
    Each sample needs a prompt (what the user says), and a trajectory
    expectation describing which tools should be called and in what order.
    """)

let instructions = """
    AVAILABLE TOOLS:
    - searchBooks(query?, tag?, mood?, genre?, limit?): search the library
    - getBookDetails(bookId): full details for one book
    - findSimilarBooks(bookId, maxResults?): find books sharing tags
    ORDER REQUIREMENTS:
    - searchBooks must come before getBookDetails or findSimilarBooks
    - Use TrajectoryExpectation(ordered:) when sequence matters, else (unordered:)
    USE THESE ARGUMENT MATCHERS:
    - .exact for precise values, .naturalLanguage for fuzzy matching
    - .keyOnly when any value is acceptable, .range for numeric constraints
    - .contains/.hasPrefix/.hasSuffix for partial string matching
    """

순서와 matcher 를 instructions 로 알려 주기

instructions 에 세 부분이 들어 있다. AVAILABLE TOOLS 는 tool 마다 이름, argument, 무엇을 하는지를 적는다. ORDER REQUIREMENTS 는 searchBooks 가 다른 둘보다 먼저 와야 한다는 것과 순서가 중요하면 ordered 를 쓰고 아니면 unordered 를 쓰라는 것이다. USE THESE ARGUMENT MATCHERS 는 앞에서 본 matcher 를 어떤 때 쓸지 알려 준다. 세션 원문의 “must comes” 는 “must come” 으로 고쳐 적었다.

generator 는 기존 dataset 을 초기 sample 로, targetCount 를 100 으로 준다. 여기서도 validator 를 둔다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let generator = SampleGenerator<ModelSample<String>>(
    prompt,
    samples: dataset,
    targetCount: 100,
    sessionProvider: {
        LanguageModelSession(model: PrivateCloudComputeLanguageModel(), instructions: instructions)
    },
    validator: { sample in
        guard let expectations = sample.output.expectations else { return false }
        let totalExpectations = expectations.ordered.count + expectations.unordered.count
        guard totalExpectations > 0 else { return false }
        let validTools: Set<String> = ["searchBooks", "getBookDetails", "findSimilarBooks"]
        let allExpectations = expectations.ordered + expectations.unordered + expectations.disallowed
        for expectation in allExpectations {
            guard validTools.contains(expectation.name) else { return false }
        }
        return true
    }
)

var result = dataset
for try await sample in generator.run() { result.append(sample) }

세션 code 는 validator: closure 만 보여 주고, closure 안은 guard sample.output.expectations != nil 다음에 expectations! 로 강제 unwrap 한다. 위의 guard let 형태와 SampleGenerator(...) 로 감싼 부분, var result loop 는 sample 이 더했다.

sample.output으로 expectation 검증하기

  • sample.output 은 generator 가 model 에게 생성시킨 쪽의 값이다. 앞의 tag 예제에서 읽은 sample.expected 는 ModelSample<BookTags> 가 정답으로 가진 BookTags 였고, 여기서는 output 의 expectations 를 읽는다. expectations 는 optional 이라 nil 이면 expectation 이 없는 sample 이므로 거절한다.
  • ordered, unordered, disallowed 는 TrajectoryExpectation 이 가진 ToolExpectation 배열이다. ordered 와 unordered 의 개수 합이 0 보다 커야 적어도 tool 하나를 가리킨다.
  • ToolExpectation.name 은 expectation 이 가리키는 tool 의 이름이다. 세 배열을 이어 붙여 모든 이름이 validTools 집합 안에 있는지 보고, model 이 존재하지 않는 tool 이름을 지어내면 거절한다.

세션이 밝히는 의의는 synthetic data API 가 기존 dataset 을 개발자 혼자 쓸 수 있는 범위를 넘어 넓히는 강력한 방법이라는 점이다. data 가 대표성을 가질수록 점수는 현실을 더 닮는다.


두 evaluation을 한 suite로

Combine evaluations 라는 제목 아래 Book tagging evaluations 상자에 Tag count, Genre coverage, Quality scores 가, Library tool evaluations 상자에 Tool calls, Argument matchers, Ordered 와 unordered 가 있다 출처: WWDC26 - Create robust evaluations for agentic apps

초록색 Book tagging evaluations 상자에는 Tag count, Genre coverage, Quality scores 가, 주황색 Library tool evaluations 상자에는 Tool calls, Argument matchers, Ordered / unordered 가 들어 있고 둘 사이에 더하기 기호가 있다.

앞에서 만든 book tagging evaluation 은 model 이 무엇을 만들었는지를 확인한다. tag 개수, 장르 coverage, 품질 점수다. 이번에 만든 tool evaluation 은 model 이 어떻게 거기에 도달했는지를 확인한다. 올바른 tool, 올바른 argument, 올바른 순서다. 둘을 같은 evaluation suite 에서 돌리면 기능에 대한 end-to-end 확신이 생긴다는 것이 세션의 마무리다.


정리

주제핵심
작은 dataset13개 sample 로는 점수가 좋아도 오해를 부른다. 양보다 coverage
makeSamplesprompt, dataset, targetCount 로 새 sample 의 async stream 을 얻는다. targetCount 는 초기 sample 을 포함한 전체 크기
SampleGeneratorsessionProvider 로 model 과 instructions 를 정한다. session 은 batch 사이에 재사용되고 가득 차면 새로 시작된다
samplingStrategyrandom 은 초기 sample 의 무작위 부분집합(기본값), sliding window 는 순서대로
validatorsample 하나만 보고 판단할 수 있는 rule 만 맡는다. 실패는 invalidSamples 로 따로 모인다
다시 평가큰 dataset 으로 돌리면 점수가 내려갈 수 있고, 원인은 prompt, 기능, evaluation, dataset 넷 중 하나
tool 평가최종 출력이 맞아도 경로가 틀릴 수 있다. 올바른 tool, argument, 순서, 예상 밖 호출 없음
TrajectoryExpectationunordered, ordered, disallowed 와 argument matcher 로 tool call 의 종류와 순서를 적는다
ToolCallEvaluatorall pass 와 percentage pass 두 metric. report 에서 어느 호출이 어긋났는지 읽는다
두 evaluation무엇을 만들었는지(tagging)와 어떻게 도달했는지(tool)를 한 suite 에서

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

  • dataset 이 작으면 점수가 좋아도 믿지 않는다. synthetic data 로 넓힌 dataset 으로 다시 돌려서 점수가 내려가면 그것이 원래 모습에 가까운 점수다.
  • targetCount 를 정할 때 몇 개인지보다 기능이 무엇을 하는지, 누가 쓰는지, 얼마나 다양한 방식으로 쓰는지를 묻는다.
  • sessionProvider 의 instructions 는 한 번만 불린다고 가정하지 않고 그 자체로 완결되게 쓴다. context window 가 차면 새 session 이 이전 context 없이 시작된다.
  • instructions 의 rule 은 보장이 아니다. sample 하나로 판단할 수 있는 rule 은 validator 로, dataset 전체를 봐야 하는 rule 은 따로 검토한다.
  • tool 을 쓰는 기능은 최종 출력만 보지 말고 trajectory 를 expectation 으로 적는다. 순서가 중요하면 ordered, 하지 말아야 할 호출이 있으면 disallowed, 값이 정해지지 않은 argument 는 keyOnly 나 naturalLanguage 를 쓴다.
  • 세션 code 를 그대로 붙이면 compile 되지 않는다. TrajectoryExpectation(expected:arguments:), ArrayLoader, 그리고 subject(from:) 와 aggregateMetrics(using:) 를 갖춘 Evaluation 이 필요하다.
  • tool 용 synthetic data 를 만들 때는 model 이 tool 을 모르므로 instructions 에 tool 목록, 순서 요구, matcher 를 적고, validator 로 tool 이름과 expectation 존재를 확인한다.

참고자료

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