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
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ let package = Package(
),
.package(url: "https://github.com/mattt/JSONSchema", from: "1.3.0"),
.package(url: "https://github.com/mattt/llama.swift", .upToNextMajor(from: "3.0.0")),
.package(url: "https://github.com/ml-explore/mlx-swift-lm", .upToNextMinor(from: "3.32.3")),
.package(url: "https://github.com/ml-explore/mlx-swift-lm", .upToNextMinor(from: "3.33.0")),
.package(url: "https://github.com/swiftlang/swift-syntax", "602.0.0" ..< "605.0.0"),
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.24.0"),
.package(url: "https://github.com/apple/swift-http-types", from: "1.5.0"),
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ dependencies: [
> traits: ["CoreML", "MLX", "Llama"]
> ),
> .package(url: "https://github.com/huggingface/swift-transformers", from: "1.0.0"), // CoreML
> .package(url: "https://github.com/ml-explore/mlx-swift-lm", .upToNextMinor(from: "3.32.3")), // MLX
> .package(url: "https://github.com/ml-explore/mlx-swift-lm", .upToNextMinor(from: "3.33.0")), // MLX
> .package(url: "https://github.com/mattt/llama.swift", .upToNextMajor(from: "3.0.0")), // Llama
> ]
> ```
Expand Down
48 changes: 47 additions & 1 deletion Sources/AnyLanguageModel/Models/MLXLanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1145,6 +1145,7 @@ import Foundation
let stream = resolved.stream

var chunks: [String] = []
var thinking = ""
var collectedToolCalls: [MLXLMCommon.ToolCall] = []
var rejectedToolCall: MLXLMCommon.RejectedToolCall?

Expand All @@ -1164,6 +1165,11 @@ import Foundation
collectedToolCalls.append(call)
case .rejectedToolCall(let rejection):
rejectedToolCall = rejectedToolCall ?? rejection
case .reasoning(let text):
thinking += text
case .steering:
// Only an MLX chat session emits steering events.
break
}
}
// The stream ends early when the task is cancelled,
Expand All @@ -1190,10 +1196,19 @@ import Foundation

let assistantText = chunks.joined()
allTextChunks.append(assistantText)
let reasoning = thinking.isEmpty ? nil : Transcript.Reasoning.mlx(thinking)

// If there are tool calls, execute them and continue
if !collectedToolCalls.isEmpty {
try session.recordToolRound(toolRounds, completed: allEntries)
if let reasoning {
allEntries.append(.reasoning(reasoning))
try await session.profileDidProduceEntries(
[.reasoning(reasoning)],
requestContext: requestContext,
currentRoundEntries: allEntries
)
}

let (callsEntry, resolution) = try await resolveToolCalls(
collectedToolCalls,
Expand Down Expand Up @@ -1229,6 +1244,8 @@ import Foundation
continue
}
}
} else if let reasoning {
allEntries.append(.reasoning(reasoning))
}

// No more tool calls, exit loop
Expand Down Expand Up @@ -1423,6 +1440,7 @@ import Foundation
let mlxStream = resolved.stream

let roundStartTextCount = accumulatedText.count
var thinking = ""
var collectedToolCalls: [MLXLMCommon.ToolCall] = []
var rejectedToolCall: MLXLMCommon.RejectedToolCall?

Expand All @@ -1437,6 +1455,11 @@ import Foundation
collectedToolCalls.append(call)
case .rejectedToolCall(let rejection):
rejectedToolCall = rejectedToolCall ?? rejection
case .reasoning(let text):
thinking += text
case .steering:
// Only an MLX chat session emits steering events.
break
case .info(let info):
usage.add(
LocalGenerationUsage(
Expand All @@ -1461,9 +1484,25 @@ import Foundation
session: session
)

guard !collectedToolCalls.isEmpty else { break }
let reasoning = thinking.isEmpty ? nil : Transcript.Reasoning.mlx(thinking)
guard !collectedToolCalls.isEmpty else {
// The final round's reasoning reaches the last snapshot.
if let reasoning {
accumulatedEntries.append(.reasoning(reasoning))
yieldSnapshot()
}
break
}

try session.recordToolRound(toolRounds, completed: accumulatedEntries)
if let reasoning {
accumulatedEntries.append(.reasoning(reasoning))
try await session.profileDidProduceEntries(
[.reasoning(reasoning)],
requestContext: requestContext,
currentRoundEntries: accumulatedEntries
)
}

let (callsEntry, resolution) = try await resolveToolCalls(
collectedToolCalls,
Expand Down Expand Up @@ -2265,6 +2304,13 @@ import Foundation
return sampledToken.item(Int.self)
}
}
private extension Transcript.Reasoning {
/// The model's reasoning, as it streamed, with its delimiters already removed.
static func mlx(_ thinking: String) -> Self {
.init(origin: .mlx, segments: [.text(.init(content: thinking))])
}
}

extension AnyLanguageModel.JSONValue {
/// Recursively converts a `JSONValue` to its primitive Swift equivalent.
func toSendable() -> any Sendable {
Expand Down
1 change: 1 addition & 0 deletions Sources/AnyLanguageModel/Transcript.swift
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,7 @@ extension Transcript.Reasoning {
/// given back only to that provider.
enum Origin: String, Sendable, Equatable, CaseIterable {
case anthropic
case mlx
case ollama
/// OpenAI's Chat Completions API, or another host that serves it.
case chatCompletions = "openai.chatCompletions"
Expand Down
Loading