Created
June 17, 2025 03:18
-
-
Save gonzalolarralde/47cf78b0180a1362e37af2a4e93fa3be to your computer and use it in GitHub Desktop.
Test FoundationModels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import SwiftUI | |
import FoundationModels | |
var model = LanguageModelSession( | |
model: .init(useCase: .general), | |
transcript: .init(entries: [ | |
.instructions( | |
.init( | |
segments: [ | |
.text(.init(content: "Hello, you are a helpful AI yada yada")) | |
], | |
toolDefinitions: [] | |
) | |
) | |
]) | |
) | |
struct ContentView: View { | |
struct Message : Identifiable{ | |
enum Side { | |
case left, middle, right | |
var foreground: Color { | |
switch self { | |
case .left: .white | |
case .middle: .primary | |
case .right: .black | |
} | |
} | |
var background: Color { | |
switch self { | |
case .left: .orange | |
case .middle: .clear | |
case .right: .gray | |
} | |
} | |
} | |
let id: UUID | |
let side: Side | |
let message: AttributedString | |
} | |
@State var textInput = "" | |
@State var messages = [Message]() | |
@State var loading: Bool = false | |
var body: some View { | |
ScrollViewReader { proxy in | |
ScrollView { | |
ForEach(messages) { message in | |
HStack { | |
if message.side != .left { | |
Spacer(minLength: 100) | |
} | |
Text(message.message) | |
.padding() | |
.background(message.side.background) | |
.foregroundStyle(message.side.foreground) | |
.padding() | |
.id(message.id) | |
if message.side != .right { | |
Spacer(minLength: 100) | |
} | |
} | |
} | |
} | |
TextField("Message", text: $textInput) | |
.onSubmit { | |
Task { | |
self.messages.append(.init(id: .init(), side: .right, message: AttributedString(self.textInput))) | |
self.loading = true | |
let newMessageId = UUID() | |
do { | |
let response = try await model.respond(to: .localizedStringWithFormat(self.textInput)) | |
self.messages.append( | |
.init( | |
id: newMessageId, | |
side: .left, | |
message: ( | |
try? AttributedString( | |
markdown: response.content, | |
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) | |
) | |
) ?? AttributedString(response.content) | |
) | |
) | |
} catch { | |
self.messages.append( | |
.init(id: newMessageId, side: .middle, message: AttributedString(error.localizedDescription))) | |
} | |
proxy.scrollTo(newMessageId) | |
textInput = "" | |
self.loading = false | |
} | |
} | |
.disabled(loading) | |
.foregroundStyle(loading ? Color.secondary : .primary) | |
.padding([.bottom, .horizontal]) | |
} | |
} | |
} | |
#Preview { | |
ContentView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment