Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat: add prompt cache and fix binary bundle

Louis023e5dea1043
diff --git a/Makefile b/Makefile
index 7d40143f5..8b857a5e3 100644
--- a/Makefile
+++ b/Makefile
@@ -123,9 +123,18 @@ build-mlx-server:
ifeq ($(shell uname -s),Darwin)
@echo "Building MLX server for Apple Silicon..."
# cd mlx-server && swift build -c release
- cd mlx-server && xcodebuild build -scheme mlx-server -destination 'platform=OS X'
-# -configuration Release
- @echo "MLX server built successfully"
+ cd mlx-server && xcodebuild build -scheme mlx-server -destination 'platform=OS X' -configuration Release OTHER_LDFLAGS="-dead_strip"
+ @echo "Finding build products..."
+ @DERIVED_DATA=$$(find ~/Library/Developer/Xcode/DerivedData/mlx-server-*/Build/Products/Release -maxdepth 0 2>/dev/null | head -1); \
+ if [ -z "$$DERIVED_DATA" ]; then \
+ echo "Error: Could not find build products"; \
+ exit 1; \
+ fi; \
+ echo "Copying mlx-server from $$DERIVED_DATA..."; \
+ cp "$$DERIVED_DATA/mlx-server" src-tauri/resources/bin/mlx-server; \
+ cp -r "$$DERIVED_DATA/mlx-swift_Cmlx.bundle" src-tauri/resources/bin/; \
+ chmod +x src-tauri/resources/bin/mlx-server; \
+ echo "MLX server built and copied successfully"
else
@echo "Skipping MLX server build (macOS only)"
endif
diff --git a/extensions/mlx-extension/src/index.ts b/extensions/mlx-extension/src/index.ts
index a5d00b94d..e15a12d5f 100644
--- a/extensions/mlx-extension/src/index.ts
+++ b/extensions/mlx-extension/src/index.ts
@@ -300,9 +300,6 @@ export default class mlx_extension extends AIEngine {
])
}
- // Resolve the MLX server binary path
- const mlxServerPath = await this.getMlxServerBinaryPath()
-
const mlxConfig: MlxConfig = {
ctx_size: cfg.ctx_size ?? 4096,
n_predict: cfg.n_predict ?? 0,
@@ -319,7 +316,6 @@ export default class mlx_extension extends AIEngine {
try {
const sInfo = await loadMlxModel(
- mlxServerPath,
modelId,
modelPath,
port,
@@ -335,26 +331,6 @@ export default class mlx_extension extends AIEngine {
}
}
- private async getMlxServerBinaryPath(): Promise<string> {
- const janDataFolderPath = await getJanDataFolderPath()
- // Look for the MLX server binary in the Jan data folder
- const binaryPath = await joinPath([
- janDataFolderPath,
- 'mlx',
- 'mlx-server',
- ])
-
- if (await fs.existsSync(binaryPath)) {
- return binaryPath
- }
-
- // Fallback: check in the app resources
- throw new Error(
- 'MLX server binary not found. Please ensure mlx-server is installed at ' +
- binaryPath
- )
- }
-
override async unload(modelId: string): Promise<UnloadResult> {
const sInfo = await this.findSessionByModel(modelId)
if (!sInfo) {
diff --git a/mlx-server/Package.swift b/mlx-server/Package.swift
index 9278d77ae..35509dbab 100644
--- a/mlx-server/Package.swift
+++ b/mlx-server/Package.swift
@@ -22,11 +22,9 @@ let package = Package(
dependencies: [
.product(name: "MLX", package: "mlx-swift"),
.product(name: "MLXNN", package: "mlx-swift"),
- .product(name: "MLXOptimizers", package: "mlx-swift"),
- .product(name: "MLXRandom", package: "mlx-swift"),
.product(name: "MLXLLM", package: "mlx-swift-lm"),
- .product(name: "MLXVLM", package: "mlx-swift-lm"),
.product(name: "MLXLMCommon", package: "mlx-swift-lm"),
+ .product(name: "MLXVLM", package: "mlx-swift-lm"),
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "Hummingbird", package: "hummingbird"),
],
diff --git a/mlx-server/Sources/MLXServer/Logger.swift b/mlx-server/Sources/MLXServer/Logger.swift
new file mode 100644
index 000000000..55594d9c8
--- /dev/null
+++ b/mlx-server/Sources/MLXServer/Logger.swift
@@ -0,0 +1,9 @@
+import Foundation
+
+/// Write a message to stdout and flush immediately for capture by Rust process
+public func log(_ message: String) {
+ let output = message + "\n"
+ if let data = output.data(using: .utf8) {
+ FileHandle.standardOutput.write(data)
+ }
+}
\ No newline at end of file
diff --git a/mlx-server/Sources/MLXServer/MLXServerCommand.swift b/mlx-server/Sources/MLXServer/MLXServerCommand.swift
index 74a97c1bb..364cb6460 100644
--- a/mlx-server/Sources/MLXServer/MLXServerCommand.swift
+++ b/mlx-server/Sources/MLXServer/MLXServerCommand.swift
@@ -29,10 +29,10 @@ struct MLXServerCommand: AsyncParsableCommand {
func run() async throws {
// Print startup info
- print("[mlx] MLX-Swift Server starting...")
- print("[mlx] Model path: \(model)")
- print("[mlx] Port: \(port)")
- print("[mlx] Context size: \(ctxSize)")
+ log("[mlx] MLX-Swift Server starting...")
+ log("[mlx] Model path: \(model)")
+ log("[mlx] Port: \(port)")
+ log("[mlx] Context size: \(ctxSize)")
// Extract model ID from path
let modelURL = URL(fileURLWithPath: model)
@@ -44,10 +44,19 @@ struct MLXServerCommand: AsyncParsableCommand {
do {
try await modelRunner.load(modelPath: model, modelId: modelId)
} catch {
- print("[mlx] Failed to load model: \(error)")
+ log("[mlx] Failed to load model: \(error)")
throw error
}
+ // Warm up the model to initialize GPU kernels and optimize performance
+ log("[mlx] Warming up model...")
+ do {
+ try await modelRunner.warmUp()
+ log("[mlx] Model warm-up complete")
+ } catch {
+ log("[mlx] Warning: Model warm-up failed (\(error.localizedDescription)), continuing anyway...")
+ }
+
// Set up the HTTP server
let server = MLXHTTPServer(
modelRunner: modelRunner,
@@ -59,8 +68,8 @@ struct MLXServerCommand: AsyncParsableCommand {
let app = Application(router: router, configuration: .init(address: .hostname("127.0.0.1", port: port)))
// Print readiness signal (monitored by Tauri plugin)
- print("[mlx] http server listening on http://127.0.0.1:\(port)")
- print("[mlx] server is listening on 127.0.0.1:\(port)")
+ log("[mlx] http server listening on http://127.0.0.1:\(port)")
+ log("[mlx] server is listening on 127.0.0.1:\(port)")
try await app.run()
}
diff --git a/mlx-server/Sources/MLXServer/ModelRunner.swift b/mlx-server/Sources/MLXServer/ModelRunner.swift
index bf1b29bec..6a6b67063 100644
--- a/mlx-server/Sources/MLXServer/ModelRunner.swift
+++ b/mlx-server/Sources/MLXServer/ModelRunner.swift
@@ -2,13 +2,13 @@ import Foundation
import MLX
import MLXLLM
import MLXLMCommon
-import MLXRandom
import MLXVLM
/// Manages loading and running inference with MLX models
actor ModelRunner {
private var container: ModelContainer?
private var modelId: String = ""
+ private var promptCache: [String: PromptCache] = [:]
var isLoaded: Bool {
container != nil
@@ -18,9 +18,50 @@ actor ModelRunner {
modelId
}
+ /// Clear the prompt cache when loading a new model
+ private func clearPromptCache() {
+ promptCache.removeAll()
+ log("[mlx] Prompt cache cleared")
+ }
+
+ /// Warm up the model by running a short generation to initialize GPU kernels
+ func warmUp() async throws {
+ guard let container = container else {
+ throw MLXServerError.modelNotLoaded
+ }
+ log("[mlx] Running warm-up generation...")
+
+ let warmUpMessages = [ChatMessage(role: "user", content: "Hello")]
+ let warmUpParameters = GenerateParameters(
+ maxTokens: 1,
+ temperature: 0.1,
+ topP: 0.9,
+ repetitionPenalty: 1.0
+ )
+
+ let warmUpInput = UserInput(
+ chat: buildChat(from: warmUpMessages),
+ processing: .init(resize: .init(width: 1024, height: 1024)),
+ tools: nil
+ )
+
+ try await container.perform { context in
+ let input = try await context.processor.prepare(input: warmUpInput)
+
+ for try await _ in try MLXLMCommon.generate(
+ input: input, parameters: warmUpParameters, context: context
+ ) {
+ // Consume the stream - we only need one token to warm up
+ break
+ }
+ }
+
+ log("[mlx] Warm-up complete")
+ }
+
/// Load a model from the given path, trying LLM first then VLM
func load(modelPath: String, modelId: String) async throws {
- print("[mlx] Loading model from: \(modelPath)")
+ log("[mlx] Loading model from: \(modelPath)")
let modelURL = URL(fileURLWithPath: modelPath)
let modelDir = modelURL.deletingLastPathComponent()
@@ -31,26 +72,29 @@ actor ModelRunner {
self.container = try await LLMModelFactory.shared.loadContainer(
configuration: configuration
) { progress in
- print("[mlx] Loading progress: \(Int(progress.fractionCompleted * 100))%")
+ log("[mlx] Loading progress: \(Int(progress.fractionCompleted * 100))%")
}
- print("[mlx] Model loaded as LLM: \(modelId)")
+ log("[mlx] Model loaded as LLM: \(modelId)")
} catch {
- print("[mlx] LLM loading failed (\(error.localizedDescription)), trying VLM factory...")
+ log("[mlx] LLM loading failed (\(error.localizedDescription)), trying VLM factory...")
do {
self.container = try await VLMModelFactory.shared.loadContainer(
configuration: configuration
) { progress in
- print("[mlx] Loading progress: \(Int(progress.fractionCompleted * 100))%")
+ log("[mlx] Loading progress: \(Int(progress.fractionCompleted * 100))%")
}
- print("[mlx] Model loaded as VLM: \(modelId)")
+ log("[mlx] Model loaded as VLM: \(modelId)")
} catch {
- print("[mlx] Error: Failed to load model with both LLM and VLM factories: \(error.localizedDescription)")
+ log("[mlx] Error: Failed to load model with both LLM and VLM factories: \(error.localizedDescription)")
throw error
}
}
self.modelId = modelId
- print("[mlx] Model ready: \(modelId)")
+ log("[mlx] Model ready: \(modelId)")
+
+ // Clear prompt cache when loading a new model
+ clearPromptCache()
}
/// Build Chat.Message array from ChatMessages, including images and videos
@@ -72,7 +116,7 @@ actor ModelRunner {
let images: [UserInput.Image] = (message.images ?? []).compactMap { urlString in
guard let url = URL(string: urlString) else {
- print("[mlx] Warning: Invalid image URL: \(urlString)")
+ log("[mlx] Warning: Invalid image URL: \(urlString)")
return nil
}
return .url(url)
@@ -80,17 +124,17 @@ actor ModelRunner {
let videos: [UserInput.Video] = (message.videos ?? []).compactMap { urlString in
guard let url = URL(string: urlString) else {
- print("[mlx] Warning: Invalid video URL: \(urlString)")
+ log("[mlx] Warning: Invalid video URL: \(urlString)")
return nil
}
return .url(url)
}
if !images.isEmpty {
- print("[mlx] Message has \(images.count) image(s)")
+ log("[mlx] Message has \(images.count) image(s)")
}
if !videos.isEmpty {
- print("[mlx] Message has \(videos.count) video(s)")
+ log("[mlx] Message has \(videos.count) video(s)")
}
return Chat.Message(
@@ -104,10 +148,38 @@ actor ModelRunner {
let specs = tools.map { tool in
tool.toSendable() as! [String: any Sendable]
}
- print("[mlx] Tools provided: \(specs.count)")
+ log("[mlx] Tools provided: \(specs.count)")
return specs
}
+ /// Build GenerateParameters from individual parameters
+ private nonisolated func buildGenerateParameters(
+ temperature: Float,
+ topP: Float,
+ maxTokens: Int,
+ repetitionPenalty: Float
+ ) -> GenerateParameters {
+ GenerateParameters(
+ maxTokens: maxTokens,
+ temperature: temperature,
+ topP: topP,
+ repetitionPenalty: repetitionPenalty
+ )
+ }
+
+ /// Get or create a prompt cache for the current model
+ private func getPromptCache(context: ModelContext, parameters: GenerateParameters) -> PromptCache {
+ if let existingCache = promptCache[modelId] {
+ return existingCache
+ }
+ // Create new cache with the model's KV cache structure
+ let modelCache = context.model.newCache(parameters: parameters)
+ let newCache = PromptCache(cache: modelCache)
+ promptCache[modelId] = newCache
+ log("[mlx] Created new prompt cache with \(modelCache.count) KV layers for model: \(modelId)")
+ return newCache
+ }
+
/// Generate a chat completion (non-streaming)
func generate(
messages: [ChatMessage],
@@ -119,21 +191,19 @@ actor ModelRunner {
tools: [AnyCodable]? = nil
) async throws -> (String, [ToolCallInfo], UsageInfo) {
guard let container = container else {
- print("[mlx] Error: generate() called but no model is loaded")
+ log("[mlx] Error: generate() called but no model is loaded")
throw MLXServerError.modelNotLoaded
}
- print("[mlx] Generate: \(messages.count) messages, temp=\(temperature), topP=\(topP), maxTokens=\(maxTokens)")
+ log("[mlx] Generate: \(messages.count) messages, temp=\(temperature), topP=\(topP), maxTokens=\(maxTokens)")
let chat = buildChat(from: messages)
let toolSpecs = buildToolSpecs(from: tools)
-
- let generateParameters = GenerateParameters(
- maxTokens: maxTokens,
- temperature: temperature,
- topP: topP,
- repetitionPenalty: repetitionPenalty
+ let generateParameters = buildGenerateParameters(
+ temperature: temperature, topP: topP,
+ maxTokens: maxTokens, repetitionPenalty: repetitionPenalty
)
+
let userInput = UserInput(
chat: chat,
processing: .init(resize: .init(width: 1024, height: 1024)),
@@ -141,8 +211,22 @@ actor ModelRunner {
)
let result: (String, [ToolCallInfo], UsageInfo) = try await container.perform { context in
- let input = try await context.processor.prepare(input: userInput)
- let promptTokenCount = input.text.tokens.size
+ let fullInput = try await context.processor.prepare(input: userInput)
+ let fullTokens = fullInput.text.tokens
+ let promptTokenCount = fullTokens.size
+
+ // Get or create prompt cache
+ let cache = await getPromptCache(context: context, parameters: generateParameters)
+
+ // Determine if we can use cached prefix
+ let lmInput: LMInput
+ if let suffix = cache.getUncachedSuffix(prompt: fullTokens) {
+ lmInput = LMInput(text: LMInput.Text(tokens: suffix))
+ log("[mlx] Using cached prefix, processing \(suffix.size) new tokens")
+ } else {
+ lmInput = fullInput
+ log("[mlx] Cache miss, processing all \(fullTokens.size) tokens")
+ }
var output = ""
var completionTokenCount = 0
@@ -151,7 +235,7 @@ actor ModelRunner {
do {
for await generation in try MLXLMCommon.generate(
- input: input, parameters: generateParameters, context: context
+ input: lmInput, cache: cache.cache, parameters: generateParameters, context: context
) {
switch generation {
case .chunk(let chunk):
@@ -163,16 +247,18 @@ actor ModelRunner {
for s in stop where output.hasSuffix(s) {
output = String(output.dropLast(s.count))
hitStop = true
- print("[mlx] Hit stop sequence: \"\(s)\"")
+ log("[mlx] Hit stop sequence: \"\(s)\"")
break
}
if hitStop { break }
case .info(let info):
completionInfo = info
- print("[mlx] Generation info: \(info.promptTokenCount) prompt tokens, \(info.generationTokenCount) generated tokens")
- print("[mlx] Prompt: \(String(format: "%.1f", info.promptTokensPerSecond)) tokens/sec")
- print("[mlx] Generation: \(String(format: "%.1f", info.tokensPerSecond)) tokens/sec")
+ // Note: info.promptTokenCount is the tokens processed in this call (may be less due to caching)
+ // We report the full promptTokenCount in usage for accurate tracking
+ log("[mlx] Generation info: \(info.promptTokenCount) processed prompt tokens, \(info.generationTokenCount) generated tokens")
+ log("[mlx] Prompt: \(String(format: "%.1f", info.promptTokensPerSecond)) tokens/sec")
+ log("[mlx] Generation: \(String(format: "%.1f", info.tokensPerSecond)) tokens/sec")
case .toolCall(let toolCall):
let argsData = try JSONSerialization.data(
@@ -189,20 +275,21 @@ actor ModelRunner {
)
)
collectedToolCalls.append(info)
- print("[mlx] Tool call: \(toolCall.function.name)(\(argsString))")
+ log("[mlx] Tool call: \(toolCall.function.name)(\(argsString))")
}
}
} catch {
- print("[mlx] Error during generation: \(error.localizedDescription)")
+ log("[mlx] Error during generation: \(error.localizedDescription)")
throw error
}
let usage: UsageInfo
if let info = completionInfo {
+ // Use full prompt token count for accurate usage tracking (info.promptTokenCount may be smaller due to caching)
usage = UsageInfo(
- prompt_tokens: info.promptTokenCount,
+ prompt_tokens: promptTokenCount,
completion_tokens: info.generationTokenCount,
- total_tokens: info.promptTokenCount + info.generationTokenCount
+ total_tokens: promptTokenCount + info.generationTokenCount
)
} else {
usage = UsageInfo(
@@ -212,7 +299,7 @@ actor ModelRunner {
)
}
- print("[mlx] Generate complete: \(output.count) chars, \(collectedToolCalls.count) tool call(s)")
+ log("[mlx] Generate complete: \(output.count) chars, \(collectedToolCalls.count) tool call(s)")
return (output, collectedToolCalls, usage)
}
@@ -232,12 +319,12 @@ actor ModelRunner {
AsyncThrowingStream { continuation in
Task {
guard let container = self.container else {
- print("[mlx] Error: generateStream() called but no model is loaded")
+ log("[mlx] Error: generateStream() called but no model is loaded")
continuation.finish(throwing: MLXServerError.modelNotLoaded)
return
}
- print("[mlx] Stream generate: \(messages.count) messages, temp=\(temperature), topP=\(topP), maxTokens=\(maxTokens)")
+ log("[mlx] Stream generate: \(messages.count) messages, temp=\(temperature), topP=\(topP), maxTokens=\(maxTokens)")
let chat = self.buildChat(from: messages)
let toolSpecs = self.buildToolSpecs(from: tools)
@@ -250,14 +337,26 @@ actor ModelRunner {
do {
try await container.perform { context in
- let generateParameters = GenerateParameters(
- maxTokens: maxTokens,
- temperature: temperature,
- topP: topP,
- repetitionPenalty: repetitionPenalty
+ let generateParameters = self.buildGenerateParameters(
+ temperature: temperature, topP: topP,
+ maxTokens: maxTokens, repetitionPenalty: repetitionPenalty
)
- let input = try await context.processor.prepare(input: userInput)
+ let fullInput = try await context.processor.prepare(input: userInput)
+ let fullTokens = fullInput.text.tokens
+
+ // Get or create prompt cache
+ let cache = await self.getPromptCache(context: context, parameters: generateParameters)
+
+ // Determine if we can use cached prefix
+ let lmInput: LMInput
+ if let suffix = cache.getUncachedSuffix(prompt: fullTokens) {
+ lmInput = LMInput(text: LMInput.Text(tokens: suffix))
+ log("[mlx] Stream using cached prefix, processing \(suffix.size) new tokens")
+ } else {
+ lmInput = fullInput
+ log("[mlx] Stream cache miss, processing all \(fullTokens.size) tokens")
+ }
var completionTokenCount = 0
var accumulated = ""
@@ -265,7 +364,7 @@ actor ModelRunner {
do {
for await generation in try MLXLMCommon.generate(
- input: input, parameters: generateParameters, context: context
+ input: lmInput, cache: cache.cache, parameters: generateParameters, context: context
) {
switch generation {
case .chunk(let chunk):
@@ -278,23 +377,25 @@ actor ModelRunner {
var hitStop = false
for s in stop where accumulated.hasSuffix(s) {
hitStop = true
- print("[mlx] Hit stop sequence: \"\(s)\"")
+ log("[mlx] Hit stop sequence: \"\(s)\"")
break
}
if hitStop { break }
case .info(let info):
- print("[mlx] Stream generation info: \(info.promptTokenCount) prompt tokens, \(info.generationTokenCount) generated tokens")
- print("[mlx] Prompt: \(String(format: "%.1f", info.promptTokensPerSecond)) tokens/sec")
- print("[mlx] Generation: \(String(format: "%.1f", info.tokensPerSecond)) tokens/sec")
+ log("[mlx] Stream generation info: \(info.promptTokenCount) processed prompt tokens, \(info.generationTokenCount) generated tokens")
+ log("[mlx] Prompt: \(String(format: "%.1f", info.promptTokensPerSecond)) tokens/sec")
+ log("[mlx] Generation: \(String(format: "%.1f", info.tokensPerSecond)) tokens/sec")
+ // Use full prompt token count for accurate usage tracking
+ let promptTokenCount = fullTokens.size
let usage = UsageInfo(
- prompt_tokens: info.promptTokenCount,
+ prompt_tokens: promptTokenCount,
completion_tokens: info.generationTokenCount,
- total_tokens: info.promptTokenCount + info.generationTokenCount
+ total_tokens: promptTokenCount + info.generationTokenCount
)
let timings = TimingsInfo(
- prompt_n: info.promptTokenCount,
+ prompt_n: promptTokenCount,
predicted_n: info.generationTokenCount,
predicted_per_second: info.tokensPerSecond,
prompt_per_second: info.promptTokensPerSecond
@@ -316,22 +417,22 @@ actor ModelRunner {
arguments: argsString
)
)
- print("[mlx] Stream tool call: \(toolCall.function.name)(\(argsString))")
+ log("[mlx] Stream tool call: \(toolCall.function.name)(\(argsString))")
continuation.yield(.toolCall(info))
}
}
} catch {
- print("[mlx] Error during stream generation: \(error.localizedDescription)")
+ log("[mlx] Error during stream generation: \(error.localizedDescription)")
throw error
}
// If no .info was received, send done with fallback usage
// The .info case already yields .done, so only send if we haven't
- print("[mlx] Stream complete: \(accumulated.count) chars")
+ log("[mlx] Stream complete: \(accumulated.count) chars")
continuation.finish()
}
} catch {
- print("[mlx] Error in stream: \(error.localizedDescription)")
+ log("[mlx] Error in stream: \(error.localizedDescription)")
continuation.finish(throwing: error)
}
}
diff --git a/mlx-server/Sources/MLXServer/PromptCache.swift b/mlx-server/Sources/MLXServer/PromptCache.swift
new file mode 100644
index 000000000..bd2747e92
--- /dev/null
+++ b/mlx-server/Sources/MLXServer/PromptCache.swift
@@ -0,0 +1,81 @@
+import MLX
+import MLXLMCommon
+
+/// Manages KV cache between generate calls to avoid re-processing common prompt prefixes
+public class PromptCache: @unchecked Sendable {
+ /// The stored KV cache layers
+ private(set) var cache: [KVCache]
+ /// The tokens corresponding to the cached KV state
+ private(set) var tokens: MLXArray
+
+ public init(cache: [KVCache]) {
+ self.cache = cache
+ self.tokens = MLXArray()
+ }
+
+ /// Returns the suffix of the prompt not already in cache
+ /// If nil is returned, the entire prompt should be processed
+ public func getUncachedSuffix(prompt: MLXArray) -> MLXArray? {
+ let comPrefixLength = commonPrefixLength(newPromptTokens: prompt)
+
+ if comPrefixLength == self.tokens.size {
+ // All tokens already cached, return suffix to append
+ let suffix = prompt[comPrefixLength..<prompt.size]
+ if suffix.size > 0 {
+ self.tokens = concatenated([self.tokens, suffix], axis: 0)
+ return suffix
+ }
+ return nil
+ } else if comPrefixLength < self.tokens.size {
+ // Part of the prompt diverges from cache
+ // Check if we can trim the cache
+ if isTrimmable() {
+ let _ = trim(self.tokens.size - comPrefixLength)
+ self.tokens = self.tokens[0..<comPrefixLength]
+ let suffix = prompt[comPrefixLength..<prompt.size]
+ if suffix.size > 0 {
+ self.tokens = concatenated([self.tokens, suffix], axis: 0)
+ return suffix
+ }
+ }
+ return nil
+ }
+
+ return nil
+ }
+
+ /// Checks if all KV cache layers are trimmable
+ public func isTrimmable() -> Bool {
+ return cache.isEmpty || cache.allSatisfy { $0.isTrimmable }
+ }
+
+ /// Trims the cache by n tokens, returning the actual number trimmed
+ @discardableResult
+ public func trim(_ n: Int) -> Int {
+ if cache.isEmpty || !isTrimmable() { return 0 }
+ return cache.map { $0.trim(n) }.max() ?? 0
+ }
+
+ /// Returns the length of the common prefix between cached and new tokens
+ public func commonPrefixLength(newPromptTokens: MLXArray) -> Int {
+ let cachedCount = Int(self.tokens.size)
+ let newCount = Int(newPromptTokens.size)
+
+ let limit = min(cachedCount, newCount)
+ for i in 0..<limit {
+ let cachedToken = self.tokens[Int(i)].item(Int32.self)
+ let newToken = newPromptTokens[Int(i)].item(Int32.self)
+ if cachedToken != newToken {
+ return i
+ }
+ }
+ return limit
+ }
+
+ /// Updates the cache with new KV cache and tokens
+ public func update(cache: [KVCache], tokens: MLXArray) {
+ self.cache = cache
+ self.tokens = tokens
+ log("[mlx] Prompt cache updated with \(tokens.size) tokens, \(cache.count) layers")
+ }
+}
diff --git a/mlx-server/Sources/MLXServer/Server.swift b/mlx-server/Sources/MLXServer/Server.swift
index 085c0d0d3..795144232 100644
--- a/mlx-server/Sources/MLXServer/Server.swift
+++ b/mlx-server/Sources/MLXServer/Server.swift
@@ -68,7 +68,7 @@ struct MLXHTTPServer {
let isStreaming = chatRequest.stream ?? false
let tools = chatRequest.tools
- print("[mlx] Request: model=\(chatRequest.model), messages=\(chatRequest.messages.count), stream=\(isStreaming), tools=\(tools?.count ?? 0)")
+ log("[mlx] Request: model=\(chatRequest.model), messages=\(chatRequest.messages.count), stream=\(isStreaming), tools=\(tools?.count ?? 0)")
if isStreaming {
return try await self.handleStreamingRequest(
@@ -137,7 +137,7 @@ struct MLXHTTPServer {
usage: usage
)
- print("[mlx] Response: \(text.count) chars, \(toolCalls.count) tool call(s), finish=\(finishReason)")
+ log("[mlx] Response: \(text.count) chars, \(toolCalls.count) tool call(s), finish=\(finishReason)")
return try Response(
status: .ok,
@@ -187,11 +187,9 @@ struct MLXHTTPServer {
]
)
if let data = try? encodeJSONData(initialChunk) {
- var buffer = ByteBufferAllocator().buffer(capacity: data.count + 8)
- buffer.writeString("data: ")
- buffer.writeBytes(data)
- buffer.writeString("\n\n")
- continuation.yield(buffer)
+ continuation.yield(buildSSEFrame(data))
+ } else {
+ log("[mlx] Warning: Failed to encode initial chunk")
}
do {
@@ -212,12 +210,7 @@ struct MLXHTTPServer {
]
)
if let data = try? encodeJSONData(chunk) {
- var buffer = ByteBufferAllocator().buffer(
- capacity: data.count + 8)
- buffer.writeString("data: ")
- buffer.writeBytes(data)
- buffer.writeString("\n\n")
- continuation.yield(buffer)
+ continuation.yield(buildSSEFrame(data))
}
case .toolCall(let toolCallInfo):
@@ -249,12 +242,7 @@ struct MLXHTTPServer {
]
)
if let data = try? encodeJSONData(chunk) {
- var buffer = ByteBufferAllocator().buffer(
- capacity: data.count + 8)
- buffer.writeString("data: ")
- buffer.writeBytes(data)
- buffer.writeString("\n\n")
- continuation.yield(buffer)
+ continuation.yield(buildSSEFrame(data))
}
case .done(let usage, let timings, let hasToolCalls):
@@ -276,12 +264,7 @@ struct MLXHTTPServer {
timings: timings
)
if let data = try? encodeJSONData(finalChunk) {
- var buffer = ByteBufferAllocator().buffer(
- capacity: data.count + 8)
- buffer.writeString("data: ")
- buffer.writeBytes(data)
- buffer.writeString("\n\n")
- continuation.yield(buffer)
+ continuation.yield(buildSSEFrame(data))
}
// Send [DONE]
@@ -291,7 +274,7 @@ struct MLXHTTPServer {
}
}
} catch {
- print("[mlx] Error in SSE stream: \(error.localizedDescription)")
+ log("[mlx] Error in SSE stream: \(error.localizedDescription)")
// Send error as SSE event
var buffer = ByteBufferAllocator().buffer(capacity: 256)
buffer.writeString(
@@ -317,8 +300,16 @@ struct MLXHTTPServer {
// MARK: - JSON Encoding Helpers
+/// Shared JSON encoder for consistent encoding and better performance
+private let jsonEncoder: JSONEncoder = {
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .secondsSince1970
+ encoder.keyEncodingStrategy = .convertToSnakeCase
+ return encoder
+}()
+
private func encodeJSON<T: Encodable>(_ value: T) throws -> Response {
- let data = try JSONEncoder().encode(value)
+ let data = try jsonEncoder.encode(value)
var buffer = ByteBufferAllocator().buffer(capacity: data.count)
buffer.writeBytes(data)
return Response(
@@ -329,12 +320,24 @@ private func encodeJSON<T: Encodable>(_ value: T) throws -> Response {
}
private func encodeJSONBuffer<T: Encodable>(_ value: T) throws -> ByteBuffer {
- let data = try JSONEncoder().encode(value)
+ let data = try jsonEncoder.encode(value)
var buffer = ByteBufferAllocator().buffer(capacity: data.count)
buffer.writeBytes(data)
return buffer
}
private func encodeJSONData<T: Encodable>(_ value: T) throws -> Data {
- try JSONEncoder().encode(value)
+ try jsonEncoder.encode(value)
+}
+
+/// Reusable buffer allocator for SSE responses to reduce allocations
+private let sseBufferAllocator = ByteBufferAllocator()
+
+/// Builds an SSE data frame with the given JSON data
+private func buildSSEFrame(_ data: Data) -> ByteBuffer {
+ var buffer = sseBufferAllocator.buffer(capacity: data.count + 8)
+ buffer.writeString("data: ")
+ buffer.writeBytes(data)
+ buffer.writeString("\n\n")
+ return buffer
}
diff --git a/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.cjs b/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.cjs
index bf33a9629..4548fb807 100644
--- a/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.cjs
+++ b/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.cjs
@@ -21,10 +21,9 @@ function normalizeMlxConfig(config) {
chat_template: asString(config.chat_template),
};
}
-async function loadMlxModel(binaryPath, modelId, modelPath, port, cfg, envs, isEmbedding = false, timeout = 600) {
+async function loadMlxModel(modelId, modelPath, port, cfg, envs, isEmbedding = false, timeout = 600) {
const config = normalizeMlxConfig(cfg);
return await core.invoke('plugin:mlx|load_mlx_model', {
- binaryPath,
modelId,
modelPath,
port,
diff --git a/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.d.ts b/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.d.ts
index df7e585ce..4e21012d6 100644
--- a/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.d.ts
+++ b/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.d.ts
@@ -1,7 +1,7 @@
import { SessionInfo, UnloadResult, MlxConfig } from './types';
export { SessionInfo, UnloadResult, MlxConfig } from './types';
export declare function normalizeMlxConfig(config: any): MlxConfig;
-export declare function loadMlxModel(binaryPath: string, modelId: string, modelPath: string, port: number, cfg: MlxConfig, envs: Record<string, string>, isEmbedding?: boolean, timeout?: number): Promise<SessionInfo>;
+export declare function loadMlxModel(modelId: string, modelPath: string, port: number, cfg: MlxConfig, envs: Record<string, string>, isEmbedding?: boolean, timeout?: number): Promise<SessionInfo>;
export declare function unloadMlxModel(pid: number): Promise<UnloadResult>;
export declare function isMlxProcessRunning(pid: number): Promise<boolean>;
export declare function getMlxRandomPort(): Promise<number>;
diff --git a/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.js b/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.js
index 39176ec63..7c94caf10 100644
--- a/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.js
+++ b/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.js
@@ -19,10 +19,9 @@ function normalizeMlxConfig(config) {
chat_template: asString(config.chat_template),
};
}
-async function loadMlxModel(binaryPath, modelId, modelPath, port, cfg, envs, isEmbedding = false, timeout = 600) {
+async function loadMlxModel(modelId, modelPath, port, cfg, envs, isEmbedding = false, timeout = 600) {
const config = normalizeMlxConfig(cfg);
return await invoke('plugin:mlx|load_mlx_model', {
- binaryPath,
modelId,
modelPath,
port,
diff --git a/src-tauri/plugins/tauri-plugin-mlx/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-mlx/guest-js/index.ts
index f436738be..6e0401812 100644
--- a/src-tauri/plugins/tauri-plugin-mlx/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-mlx/guest-js/index.ts
@@ -24,7 +24,6 @@ export function normalizeMlxConfig(config: any): MlxConfig {
}
export async function loadMlxModel(
- binaryPath: string,
modelId: string,
modelPath: string,
port: number,
@@ -35,7 +34,6 @@ export async function loadMlxModel(
): Promise<SessionInfo> {
const config = normalizeMlxConfig(cfg)
return await invoke('plugin:mlx|load_mlx_model', {
- binaryPath,
modelId,
modelPath,
port,
diff --git a/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs b/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs
index def1a8ceb..ec65847c8 100644
--- a/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs
@@ -41,7 +41,6 @@ pub struct MlxConfig {
#[tauri::command]
pub async fn load_mlx_model<R: Runtime>(
app_handle: tauri::AppHandle<R>,
- binary_path: String,
model_id: String,
model_path: String,
port: u16,
@@ -53,6 +52,13 @@ pub async fn load_mlx_model<R: Runtime>(
let state: State<MlxState> = app_handle.state();
let mut process_map = state.mlx_server_process.lock().await;
+ // Resolve binary path from app resources
+ let binary_path = app_handle
+ .path()
+ .resource_dir()
+ .map_err(|e| MlxError::new(ErrorCode::BinaryNotFound, "Failed to get resource dir".to_string(), Some(e.to_string())))?
+ .join("resources/bin/mlx-server");
+
log::info!("Attempting to launch MLX server at path: {:?}", binary_path);
log::info!("Using MLX configuration: {:?}", config);
@@ -61,7 +67,7 @@ pub async fn load_mlx_model<R: Runtime>(
if !bin_path.exists() {
return Err(MlxError::new(
ErrorCode::BinaryNotFound,
- format!("MLX server binary not found at: {}", binary_path),
+ format!("MLX server binary not found at: {}", binary_path.display()),
None,
)
.into());
diff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.json
index f50c0e5d9..2326f498a 100644
--- a/src-tauri/tauri.macos.conf.json
+++ b/src-tauri/tauri.macos.conf.json
@@ -1,7 +1,7 @@
{
"bundle": {
"targets": ["app", "dmg"],
- "resources": ["resources/pre-install/**/*", "resources/LICENSE"],
+ "resources": ["resources/pre-install/**/*", "resources/LICENSE", "resources/bin/mlx-server", "resources/bin/mlx-swift_Cmlx.bundle"],
"externalBin": ["resources/bin/bun", "resources/bin/uv"],
"macOS": {
"entitlements": "./Entitlements.plist"
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index e03f8806a..a615bd2ec 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -243,6 +243,8 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
system: this.systemMessage,
})
+ var tokensPerSecond = 0
+
return result.toUIMessageStream({
messageMetadata: ({ part }) => {
// Track stream start time on start
@@ -261,34 +263,31 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
}
}
+ if (part.type === 'finish-step') {
+ tokensPerSecond =
+ (part.providerMetadata?.providerMetadata
+ ?.tokensPerSecond as number) || 0
+ }
+
// Add usage and token speed to metadata on finish
if (part.type === 'finish') {
const finishPart = part as {
type: 'finish'
totalUsage: LanguageModelUsage
finishReason: string
- providerMetadata?: {
- llamacpp?: {
- promptTokens?: number | null
- completionTokens?: number | null
- tokensPerSecond?: number | null
- }
- }
}
const usage = finishPart.totalUsage
const durationMs = streamStartTime ? Date.now() - streamStartTime : 0
const durationSec = durationMs / 1000
// Use provider's outputTokens, or llama.cpp completionTokens, or fall back to text delta count
- const outputTokens =
- usage?.outputTokens ??
- textDeltaCount
+ const outputTokens = usage?.outputTokens ?? textDeltaCount
const inputTokens = usage?.inputTokens
// Use llama.cpp's tokens per second if available, otherwise calculate from duration
let tokenSpeed: number
if (durationSec > 0 && outputTokens > 0) {
- tokenSpeed = outputTokens / durationSec
+ tokenSpeed = tokensPerSecond > 0 ? tokensPerSecond : outputTokens / durationSec
} else {
tokenSpeed = 0
}
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index e88118145..eae27064f 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -27,7 +27,11 @@
import { type LanguageModel } from 'ai'
import { createOpenAI } from '@ai-sdk/openai'
-import { createOpenAICompatible } from '@ai-sdk/openai-compatible'
+import {
+ createOpenAICompatible,
+ MetadataExtractor,
+ OpenAICompatibleChatLanguageModel,
+} from '@ai-sdk/openai-compatible'
import { createAnthropic } from '@ai-sdk/anthropic'
import { invoke } from '@tauri-apps/api/core'
import { SessionInfo } from '@janhq/core'
@@ -47,16 +51,18 @@ interface LlamaCppChunk {
timings?: LlamaCppTimings
}
+
/**
- * Custom metadata extractor for llama.cpp that extracts timing information
- * and converts it to token usage format
+ * Custom metadata extractor for MLX that extracts timing information
+ * and converts it to token usage format. MLX uses the same timing structure
+ * as llama.cpp.
*/
-const llamaCppMetadataExtractor = {
+const providerMetadataExtractor: MetadataExtractor = {
extractMetadata: async ({ parsedBody }: { parsedBody: unknown }) => {
const body = parsedBody as LlamaCppChunk
if (body?.timings) {
return {
- llamacpp: {
+ providerMetadata: {
promptTokens: body.timings.prompt_n ?? null,
completionTokens: body.timings.predicted_n ?? null,
tokensPerSecond: body.timings.predicted_per_second ?? null,
@@ -79,7 +85,7 @@ const llamaCppMetadataExtractor = {
buildMetadata: () => {
if (lastTimings) {
return {
- llamacpp: {
+ providerMetadata: {
promptTokens: lastTimings.prompt_n ?? null,
completionTokens: lastTimings.predicted_n ?? null,
tokensPerSecond: lastTimings.predicted_per_second ?? null,
@@ -182,7 +188,7 @@ export class ModelFactory {
})
return openAICompatible.languageModel(modelId, {
- metadataExtractor: llamaCppMetadataExtractor,
+ metadataExtractor: providerMetadataExtractor,
})
}
@@ -221,23 +227,22 @@ export class ModelFactory {
throw new Error(`No running MLX session found for model: ${modelId}`)
}
- // Create OpenAI-compatible client for MLX server
- const openAICompatible = createOpenAICompatible({
- name: 'mlx',
- baseURL: `http://localhost:${sessionInfo.port}/v1`,
- headers: {
+ const model = new OpenAICompatibleChatLanguageModel(modelId, {
+ provider: 'mlx',
+ headers: () => ({
Authorization: `Bearer ${sessionInfo.api_key}`,
Origin: 'tauri://localhost',
+ }),
+ url: ({ path }) => {
+ const url = new URL(`http://localhost:${sessionInfo.port}/v1/${path}`)
+
+ return url.toString()
},
- includeUsage: true,
fetch: fetch,
+ metadataExtractor: providerMetadataExtractor,
})
-
- return openAICompatible.languageModel(modelId, {
- metadataExtractor: llamaCppMetadataExtractor,
- })
+ return model
}
-
/**
* Create an Anthropic model using the official AI SDK
*/
diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsx
index 514e0ee94..19196d1d6 100644
--- a/web-app/src/routes/settings/providers/$providerName.tsx
+++ b/web-app/src/routes/settings/providers/$providerName.tsx
@@ -707,38 +707,42 @@ function ProviderDetail() {
provider={provider}
modelId={model.id}
/>
- {provider && provider.provider === 'llamacpp' && (
- <div className="ml-2">
- {activeModels.some(
- (activeModel) => activeModel === model.id
- ) ? (
- <Button
- size="sm"
- variant="destructive"
- onClick={() => handleStopModel(model.id)}
- >
- {t('providers:stop')}
- </Button>
- ) : (
- <Button
- size="sm"
- disabled={loadingModels.includes(model.id)}
- onClick={() => handleStartModel(model.id)}
- >
- {loadingModels.includes(model.id) ? (
- <div className="flex items-center gap-2">
- <IconLoader
- size={16}
- className="animate-spin"
- />
- </div>
- ) : (
- t('providers:start')
- )}
- </Button>
- )}
- </div>
- )}
+ {provider &&
+ (provider.provider === 'llamacpp' ||
+ provider.provider === 'mlx') && (
+ <div className="ml-2">
+ {activeModels.some(
+ (activeModel) => activeModel === model.id
+ ) ? (
+ <Button
+ size="sm"
+ variant="destructive"
+ onClick={() => handleStopModel(model.id)}
+ >
+ {t('providers:stop')}
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ disabled={loadingModels.includes(
+ model.id
+ )}
+ onClick={() => handleStartModel(model.id)}
+ >
+ {loadingModels.includes(model.id) ? (
+ <div className="flex items-center gap-2">
+ <IconLoader
+ size={16}
+ className="animate-spin"
+ />
+ </div>
+ ) : (
+ t('providers:start')
+ )}
+ </Button>
+ )}
+ </div>
+ )}
</div>
}
/>