-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranscriptDebugMenu.swift
More file actions
211 lines (195 loc) · 7.04 KB
/
TranscriptDebugMenu.swift
File metadata and controls
211 lines (195 loc) · 7.04 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//
// Created by Artem Novichkov on 04.08.2025.
//
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
import SwiftUI
import FoundationModels
import OSLog
/// A SwiftUI view for inspecting, copying, and capturing feedback for `LanguageModelSession` transcripts.
///
/// `TranscriptDebugMenu` shows transcript entries in a list with a context menu to copy any entry.
/// It also lets you mark the conversation sentiment and automatically
/// generates a `LanguageModelFeedback` JSON file that can be submitted to Apple using [Feedback Assistant](https://feedbackassistant.apple.com/).
///
/// ## Usage
///
/// ```swift
/// import SwiftUI
/// import FoundationModels
/// import TranscriptDebugMenu
///
/// struct ContentView: View {
/// @State private var showTranscript = false
/// @State private var session = LanguageModelSession()
///
/// var body: some View {
/// VStack {
/// Button("Show Transcript Menu") {
/// showTranscript = true
/// }
/// }
/// .transcriptDebugMenu(session, isPresented: $showTranscript)
/// }
///}
/// ```
public struct TranscriptDebugMenu: View {
/// The language model session containing the transcript to display.
let session: LanguageModelSession
private let feedbackFileURL: URL = FileManager.default
.temporaryDirectory
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension("json")
@State private var sentiment: LanguageModelFeedback.Sentiment?
@State private var feedbackDataFileSaved: Bool = false
private let logger = Logger(subsystem: "com.artemnovichkov.TranscriptDebugMenu", category: "TranscriptDebugMenu")
@State private var searchText: String = ""
@State private var searchScope: SearchScope = .all
@State private var path = NavigationPath()
/// Creates a new transcript debug menu for the specified session.
///
/// - Parameter session: The `LanguageModelSession` whose transcript will be displayed.
/// The session's transcript property is used to populate the list of entries.
public init(session: LanguageModelSession) {
self.session = session
}
public var body: some View {
NavigationStack(path: $path) {
List {
ForEach(entries) { entry in
Text(entry.description)
.transition(.opacity)
.onTapGesture {
path.append(entry)
}
.contextMenu {
Button("Copy") {
copyToClipboard(entry: entry)
}
}
}
if session.isResponding {
ProgressView()
.frame(maxWidth: .infinity)
}
}
.animation(.easeInOut, value: session.transcript)
.overlay {
if session.transcript.isEmpty {
ContentUnavailableView("No entries",
systemImage: "apple.intelligence",
description: Text("The transcript is empty"))
}
}
.navigationTitle("Transcript")
.navigationDestination(for: Transcript.Entry.self) { entry in
TranscriptEntryDetailView(entry: entry)
}
.toolbar {
toolbar
}
.onAppear {
saveFeedbackAttachment(sentiment: sentiment)
}
.onChange(of: sentiment) { _, newValue in
saveFeedbackAttachment(sentiment: newValue)
}
.searchable(text: $searchText)
.searchScopes($searchScope, activation: .onSearchPresentation) {
ForEach(SearchScope.allCases) { scope in
Text(scope.title)
.tag(scope)
}
}
}
}
// MARK: - Private
private var entries: [Transcript.Entry] {
if searchText.isEmpty {
return Array(session.transcript)
}
return session.transcript
.filter { entry in
switch searchScope {
case .all:
return true
case .instructions:
if case .instructions = entry { return true }
return false
case .prompt:
if case .prompt = entry { return true }
return false
case .toolCalls:
if case .toolCalls = entry { return true }
return false
case .toolOutput:
if case .toolOutput = entry { return true }
return false
case .response:
if case .response = entry { return true }
return false
}
}
.filter { entry in
entry.description.localizedCaseInsensitiveContains(searchText)
}
}
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
ToolbarItem {
Button {
sentiment = sentiment == .negative ? nil : .negative
} label: {
Label("Negative",
systemImage: "hand.thumbsdown" + (sentiment == .negative ? ".fill" : ""))
}
}
ToolbarItem {
Button {
sentiment = sentiment == .positive ? nil : .positive
} label: {
Label("Positive",
systemImage: "hand.thumbsup" + (sentiment == .positive ? ".fill" : "" ))
}
}
ToolbarSpacer()
ToolbarItem {
ShareLink(item: feedbackFileURL)
.disabled(!feedbackDataFileSaved)
}
}
private func saveFeedbackAttachment(sentiment: LanguageModelFeedback.Sentiment?) {
let feedbackData = session.logFeedbackAttachment(sentiment: sentiment)
do {
try feedbackData.write(to: feedbackFileURL)
feedbackDataFileSaved = true
} catch {
feedbackDataFileSaved = false
logger.error("Failed to save feedback attachment: \(error.localizedDescription)")
}
}
private func copyToClipboard(entry: Transcript.Entry) {
#if canImport(UIKit)
UIPasteboard.general.string = entry.description
#elseif canImport(AppKit)
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(entry.description, forType: .string)
#endif
}
}
extension Transcript.Entry: @retroactive Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
#Preview {
@Previewable @State var isPresented = false
@Previewable @State var session = LanguageModelSession(transcript: .mock)
Button("Show Transcript Menu") {
isPresented.toggle()
}
.transcriptDebugMenu(session, isPresented: $isPresented)
}