Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 55 additions & 39 deletions Sources/AnyLanguageModel/LanguageModelSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,17 @@ import Observation

@Observable
public final class LanguageModelSession: @unchecked Sendable {
public private(set) var isResponding: Bool = false
public private(set) var transcript: Transcript
public var isResponding: Bool {
access(keyPath: \.isResponding)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to Philippe Hausler on the Swift Forums, the access() and withMutation() calls need to happen outside of locks.

return state.access { $0.isResponding }
}

public var transcript: Transcript {
access(keyPath: \.transcript)
return state.access { $0.transcript }
}

@ObservationIgnored private let state: Locked<State>

private let model: any LanguageModel
public let tools: [any Tool]
Expand All @@ -20,8 +29,6 @@ public final class LanguageModelSession: @unchecked Sendable {
/// with the Foundation Models framework.
@ObservationIgnored public var toolExecutionDelegate: (any ToolExecutionDelegate)?

@ObservationIgnored private let respondingState = RespondingState()

public convenience init(
model: any LanguageModel,
tools: [any Tool] = [],
Expand Down Expand Up @@ -84,37 +91,33 @@ public final class LanguageModelSession: @unchecked Sendable {
}
}

self.transcript = finalTranscript
self.state = .init(.init(finalTranscript))
}

public func prewarm(promptPrefix: Prompt? = nil) {
model.prewarm(for: self, promptPrefix: promptPrefix)
}

nonisolated private func beginResponding() async {
let count = await respondingState.increment()
let active = count > 0
await MainActor.run {
self.isResponding = active
nonisolated private func beginResponding() {
withMutation(keyPath: \.isResponding) {
state.access { $0.beginResponding() }
Comment on lines +102 to +103
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to Philippe Hausler on the Swift Forums, the access() and withMutation() calls need to happen outside of locks.

}
}

nonisolated private func endResponding() async {
let count = await respondingState.decrement()
let active = count > 0
await MainActor.run {
self.isResponding = active
nonisolated private func endResponding() {
withMutation(keyPath: \.isResponding) {
state.access { $0.endResponding() }
}
}

nonisolated private func wrapRespond<T>(_ operation: () async throws -> T) async throws -> T {
await beginResponding()
beginResponding()
do {
let result = try await operation()
await endResponding()
endResponding()
return result
} catch {
await endResponding()
endResponding()
throw error
}
}
Expand All @@ -127,7 +130,7 @@ public final class LanguageModelSession: @unchecked Sendable {
let relay = AsyncThrowingStream<ResponseStream<Content>.Snapshot, any Error> { continuation in
let stream = upstream
Task {
await session.beginResponding()
session.beginResponding()
var lastSnapshot: ResponseStream<Content>.Snapshot?
do {
for try await snapshot in stream {
Expand All @@ -152,14 +155,14 @@ public final class LanguageModelSession: @unchecked Sendable {
segments: [.text(.init(content: textContent))]
)
)
await MainActor.run {
session.transcript.append(responseEntry)
session.withMutation(keyPath: \.transcript) {
session.state.access { $0.transcript.append(responseEntry) }
}
}
} catch {
continuation.finish(throwing: error)
}
await session.endResponding()
session.endResponding()
}
}
return ResponseStream(stream: relay)
Expand Down Expand Up @@ -202,8 +205,8 @@ public final class LanguageModelSession: @unchecked Sendable {
responseFormat: nil
)
)
await MainActor.run {
self.transcript.append(promptEntry)
withMutation(keyPath: \.transcript) {
state.access { $0.transcript.append(promptEntry) }
}

let response = try await model.respond(
Expand All @@ -230,9 +233,11 @@ public final class LanguageModelSession: @unchecked Sendable {
)

// Add tool entries and response to transcript
await MainActor.run {
self.transcript.append(contentsOf: response.transcriptEntries)
self.transcript.append(responseEntry)
withMutation(keyPath: \.transcript) {
state.access { state in
state.transcript.append(contentsOf: response.transcriptEntries)
state.transcript.append(responseEntry)
}
}

return response
Expand All @@ -253,7 +258,9 @@ public final class LanguageModelSession: @unchecked Sendable {
responseFormat: nil
)
)
transcript.append(promptEntry)
withMutation(keyPath: \.transcript) {
state.access { $0.transcript.append(promptEntry) }
}

return wrapStream(
model.streamResponse(
Expand Down Expand Up @@ -547,8 +554,8 @@ extension LanguageModelSession {
responseFormat: nil
)
)
await MainActor.run {
self.transcript.append(promptEntry)
withMutation(keyPath: \.transcript) {
state.access { $0.transcript.append(promptEntry) }
}

// Extract text content for the Prompt parameter
Expand Down Expand Up @@ -578,9 +585,11 @@ extension LanguageModelSession {
)

// Add tool entries and response to transcript
await MainActor.run {
self.transcript.append(contentsOf: response.transcriptEntries)
self.transcript.append(responseEntry)
withMutation(keyPath: \.transcript) {
state.access { state in
state.transcript.append(contentsOf: response.transcriptEntries)
state.transcript.append(responseEntry)
}
}

return response
Expand Down Expand Up @@ -651,7 +660,9 @@ extension LanguageModelSession {
responseFormat: nil
)
)
transcript.append(promptEntry)
withMutation(keyPath: \.transcript) {
state.access { $0.transcript.append(promptEntry) }
}

// Extract text content for the Prompt parameter
let textPrompt = Prompt(prompt)
Expand Down Expand Up @@ -902,16 +913,21 @@ private enum ResponseStreamError: Error {

// MARK: -

private actor RespondingState {
private struct State: Equatable, Sendable {
var transcript: Transcript

var isResponding: Bool { count > 0 }
private var count = 0

func increment() -> Int {
init(_ transcript: Transcript) {
self.transcript = transcript
}

mutating func beginResponding() {
count += 1
return count
}

func decrement() -> Int {
mutating func endResponding() {
count = max(0, count - 1)
return count
}
}
81 changes: 81 additions & 0 deletions Sources/AnyLanguageModel/Locked.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#if canImport(Darwin)
import Darwin
private typealias PlatformLock = os_unfair_lock
#elseif canImport(Glibc)
import Glibc
#if os(FreeBSD) || os(OpenBSD)
private typealias PlatformLock = pthread_mutex_t?
#else
private typealias PlatformLock = pthread_mutex_t
#endif
#else
#error("Unsupported platform")
#endif

struct Locked<State> {
private final class Buffer: ManagedBuffer<State, PlatformLock> {
deinit { withUnsafeMutablePointerToElements { $0.destroy() } }
}

private let buffer: ManagedBuffer<State, PlatformLock>

init(_ state: State) {
buffer = Buffer.create(minimumCapacity: 1) { buffer in
buffer.withUnsafeMutablePointerToElements { PlatformLockPointer.initialize($0) }
return state
}
}

func access<T>(_ block: (inout State) throws -> T) rethrows -> T {
try buffer.withUnsafeMutablePointers { header, lock in
lock.lock()
defer { lock.unlock() }
return try block(&header.pointee)
}
}
}

extension Locked: @unchecked Sendable where State: Sendable {}

private typealias PlatformLockPointer = UnsafeMutablePointer<PlatformLock>
private extension PlatformLockPointer {
static func initialize(_ pointer: PlatformLockPointer) {
#if canImport(Darwin)
pointer.initialize(to: os_unfair_lock())
#elseif canImport(Glibc)
let result = pthread_mutex_init(pointer, nil)
precondition(result == 0, "pthread_mutex_init failed")
#else
#error("Unsupported platform")
#endif
}

func destroy() {
#if canImport(Glibc)
let result = pthread_mutex_destroy(self)
precondition(result == 0, "pthread_mutex_destroy failed")
#endif
deinitialize(count: 1)
}

func lock() {
#if canImport(Darwin)
os_unfair_lock_lock(self)
#elseif canImport(Glibc)
pthread_mutex_lock(self)
#else
#error("Unsupported platform")
#endif
}

func unlock() {
#if canImport(Darwin)
os_unfair_lock_unlock(self)
#elseif canImport(Glibc)
let result = pthread_mutex_unlock(self)
precondition(result == 0, "pthread_mutex_unlock failed")
#else
#error("Unsupported platform")
#endif
}
}
Loading