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: detect vision capability while importing model

Louisd01ec56c75b2
diff --git a/.gitignore b/.gitignore
index 2d626353c..6994708ac 100644
--- a/.gitignore
+++ b/.gitignore
@@ -65,3 +65,4 @@ llm-docs
.claude/agents
mlx-server/.build
mlx-server/.swiftpm
+.claude
diff --git a/extensions/mlx-extension/settings.json b/extensions/mlx-extension/settings.json
index 44b551924..b3b643ce0 100644
--- a/extensions/mlx-extension/settings.json
+++ b/extensions/mlx-extension/settings.json
@@ -1,16 +1,4 @@
[
- {
- "key": "ctx_size",
- "title": "Context Size",
- "description": "Context window size for MLX inference",
- "controllerType": "input",
- "controllerProps": {
- "value": 4096,
- "placeholder": "4096",
- "type": "number",
- "textAlign": "right"
- }
- },
{
"key": "batch_size",
"title": "Batch Size",
diff --git a/extensions/mlx-extension/src/index.ts b/extensions/mlx-extension/src/index.ts
index 42d44f611..3c471fb51 100644
--- a/extensions/mlx-extension/src/index.ts
+++ b/extensions/mlx-extension/src/index.ts
@@ -332,7 +332,7 @@ export default class mlx_extension extends AIEngine {
)
return sInfo
} catch (error) {
- logger.error('Error loading MLX model:', error)
+ logger.error(`Error loading MLX model: ${JSON.stringify(error)}`)
throw error
}
}
@@ -629,13 +629,31 @@ export default class mlx_extension extends AIEngine {
}
)
+ // Detect capabilities after download
+ const isVision = await this.isVisionSupported(localPath)
+
+ // Build capabilities array
+ const capabilities: string[] = []
+ if (isVision) capabilities.push('vision')
+
// Create model.yml with relative path
- const modelConfig = {
+ const modelConfig: any = {
model_path: `mlx/models/${modelId}/model.safetensors`,
name: modelId,
size_bytes: opts.modelSize ?? 0,
}
+ // For vision models, add mmproj_path
+ if (isVision) {
+ modelConfig.mmproj_path = `mlx/models/${modelId}/model.safetensors`
+ logger.info(`Vision model detected: ${modelId}`)
+ }
+
+ // Add capabilities array
+ if (capabilities.length > 0) {
+ modelConfig.capabilities = capabilities
+ }
+
await fs.mkdir(modelDir)
await invoke<void>('write_yaml', {
data: modelConfig,
@@ -646,6 +664,7 @@ export default class mlx_extension extends AIEngine {
modelId,
modelPath: modelConfig.model_path,
size_bytes: modelConfig.size_bytes,
+ capabilities: capabilities,
})
} else {
// Local file - use absolute path directly
@@ -657,13 +676,32 @@ export default class mlx_extension extends AIEngine {
const stat = await fs.fileStat(sourcePath)
const size_bytes = stat.size
+ // Detect capabilities by checking model directory
+ const isVision = await this.isVisionSupported(sourcePath)
+
+ // Build capabilities array
+ const capabilities: string[] = []
+ if (isVision) capabilities.push('vision')
+
// Create model.yml with absolute path
- const modelConfig = {
+ const modelConfig: any = {
model_path: sourcePath,
name: modelId,
size_bytes,
}
+ // For vision models, add mmproj_path pointing to model.safetensors
+ if (isVision) {
+ const modelDir = sourcePath.substring(0, sourcePath.lastIndexOf('/'))
+ modelConfig.mmproj_path = sourcePath
+ logger.info(`Vision model detected: ${modelId}`)
+ }
+
+ // Add capabilities array
+ if (capabilities.length > 0) {
+ modelConfig.capabilities = capabilities
+ }
+
// Create model folder for model.yml only (no copying of safetensors)
const modelDir = await joinPath([
await this.getProviderPath(),
@@ -681,6 +719,7 @@ export default class mlx_extension extends AIEngine {
modelId,
modelPath: sourcePath,
size_bytes,
+ capabilities: capabilities,
})
}
}
@@ -698,6 +737,73 @@ export default class mlx_extension extends AIEngine {
}
}
+ async isVisionSupported(modelPath: string): Promise<boolean> {
+ // Check if model is a Vision Language Model by examining config.json
+ const modelDir = modelPath.substring(0, modelPath.lastIndexOf('/'))
+ const configPath = await joinPath([modelDir, 'config.json'])
+
+ if (!(await fs.existsSync(configPath))) {
+ return false
+ }
+
+ try {
+ const configContent = await invoke<string>('read_file_sync', {
+ args: [configPath],
+ })
+ const config = JSON.parse(configContent)
+
+ // Check architecture for vision models
+ const architectures = config.architectures
+ if (architectures && Array.isArray(architectures)) {
+ const archString = architectures[0]?.toString().toLowerCase() ?? ''
+ // Common VLM architecture suffixes
+ const vlmPatterns = [
+ 'vl', 'vlm', 'vision', 'llava', 'qwen2vl', 'qwen3vl',
+ 'idefics', 'fuyu', 'paligemma', 'clip', 'siglip'
+ ]
+ if (vlmPatterns.some(pattern => archString.includes(pattern))) {
+ logger.info(`Vision support detected from config.json: ${architectures[0]}`)
+ return true
+ }
+ }
+
+ // Check for vision-related configuration fields
+ if (config.visual_architectures || config.vision_config) {
+ logger.info('Vision support detected from visual_architectures/vision_config')
+ return true
+ }
+
+ // Check for image processor config
+ const imageProcessorPath = await joinPath([modelDir, 'image_processor_config.json'])
+ if (await fs.existsSync(imageProcessorPath)) {
+ logger.info('Vision support detected from image_processor_config.json')
+ return true
+ }
+
+ // Check preprocessor config for vision
+ const preprocessorConfigPath = await joinPath([modelDir, 'preprocessor_config.json'])
+ if (await fs.existsSync(preprocessorConfigPath)) {
+ try {
+ const preprocessorConfig = await invoke<string>('read_file_sync', {
+ args: [preprocessorConfigPath],
+ })
+ const pc = JSON.parse(preprocessorConfig)
+ if (pc.do_resize || pc.size || pc.patch_size) {
+ logger.info('Vision support detected from preprocessor_config.json')
+ return true
+ }
+ } catch (e) {
+ // Ignore
+ }
+ }
+
+ return false
+ } catch (e) {
+ logger.warn(`Failed to check vision support for ${modelPath}: ${e}`)
+ return false
+ }
+ }
+
async isToolSupported(modelId: string): Promise<boolean> {
// Check GGUF/safetensors metadata for tool support
const modelConfigPath = await joinPath([
diff --git a/mlx-server/README.md b/mlx-server/README.md
index 0e2271935..91ce49fdc 100644
--- a/mlx-server/README.md
+++ b/mlx-server/README.md
@@ -80,6 +80,7 @@ cp "$METALLIB_PATH" .build/arm64-apple-macosx/release/
| `--port` | 8080 | HTTP server port |
| `--ctx-size` | 4096 | Context window size |
| `--api-key` | "" | API key for authentication |
+| `--chat-template` | "" | Path to custom chat template file (for thinking models) |
| `--max-batch-size` | 0 | Maximum batch size (0 = disabled) |
| `--batch-timeout-ms` | 100 | Batch timeout in milliseconds |
| `--enable-continuous-batching` | false | Enable continuous batching |
@@ -217,18 +218,6 @@ mlx-server/
- **Continuous Batching** - Better GPU utilization under varying load
- **Priority Queue** - Request prioritization and adaptive sleep
-## Integration with Jan
-
-The mlx-server is designed to integrate with Jan for local LLM inference:
-
-```json
-{
- "backend": "mlx",
- "urls": ["http://127.0.0.1:8080/v1"],
- "apiKey": "optional-api-key"
-}
-```
-
## Troubleshooting
### Metal Library Not Found
@@ -273,4 +262,4 @@ This project is part of Jan - an open-source desktop AI application.
- [MLX Swift](https://github.com/ml-explore/mlx-swift)
- [MLX Swift LM](https://github.com/ml-explore/mlx-swift-lm)
-- [OpenAI Chat Completions API](https://platform.openai.com/docs/api-reference/chat)
\ No newline at end of file
+- [OpenAI Chat Completions API](https://platform.openai.com/docs/api-reference/chat)
diff --git a/mlx-server/Sources/MLXServer/MLXServerCommand.swift b/mlx-server/Sources/MLXServer/MLXServerCommand.swift
index bf496b0c9..f276cd297 100644
--- a/mlx-server/Sources/MLXServer/MLXServerCommand.swift
+++ b/mlx-server/Sources/MLXServer/MLXServerCommand.swift
@@ -1,6 +1,7 @@
import ArgumentParser
import Foundation
import Hummingbird
+import MLX
@main
struct MLXServerCommand: AsyncParsableCommand {
@@ -45,11 +46,15 @@ struct MLXServerCommand: AsyncParsableCommand {
var enablePrefixCaching: Bool = false
func run() async throws {
+ // Set GPU memory limit to prevent OOM issues
+ Memory.cacheLimit = 20 * 1024 * 1024 // 20GB limit
+
// Print startup info
log("[mlx] MLX-Swift Server starting...")
log("[mlx] Model path: \(model)")
log("[mlx] Port: \(port)")
log("[mlx] Context size: \(ctxSize)")
+ log("[mlx] Memory cache limit: \(Memory.cacheLimit / (1024 * 1024))MB")
// Print batching configuration if enabled
if maxBatchSize > 0 {
diff --git a/mlx-server/Sources/MLXServer/ModelRunner.swift b/mlx-server/Sources/MLXServer/ModelRunner.swift
index 0e9d010b4..88e191224 100644
--- a/mlx-server/Sources/MLXServer/ModelRunner.swift
+++ b/mlx-server/Sources/MLXServer/ModelRunner.swift
@@ -337,7 +337,8 @@ actor ModelRunner {
let userInput = UserInput(
chat: chat,
processing: .init(resize: .init(width: 1024, height: 1024)),
- tools: toolSpecs
+ tools: toolSpecs,
+ additionalContext: ["enable_thinking": true]
)
let result: (String, [ToolCallInfo], UsageInfo) = try await container.perform { context in
@@ -462,7 +463,8 @@ actor ModelRunner {
let userInput = UserInput(
chat: chat,
processing: .init(resize: .init(width: 1024, height: 1024)),
- tools: toolSpecs
+ tools: toolSpecs,
+ additionalContext: ["enable_thinking": true]
)
do {
@@ -699,104 +701,6 @@ public struct SpeculativeResult: Sendable {
}
}
-/// Manager for speculative decoding
-actor SpeculativeGenerator {
- private var medusaHeads: MedusaHeads?
- private var config: SpeculativeConfig?
-
- /// Setup speculative decoding with configuration
- func setup(config: SpeculativeConfig) async throws {
- guard config.enabled else {
- self.config = nil
- return
- }
-
- // Check if model supports speculative decoding
- // This would require checking for Medusa heads or creating them
- self.config = config
-
- log("[mlx] Speculative decoding enabled with \(config.numDraftTokens) draft tokens")
- }
-
- /// Generate with speculative decoding
- func speculativeGenerate(
- input: LMInput,
- cache: [KVCache],
- parameters: GenerateParameters,
- context: ModelContext
- ) async throws -> AsyncThrowingStream<String, Error> {
- guard config != nil else {
- throw MLXServerError.speculativeDecodingNotSupported
- }
-
- // Fall back to regular generation if speculative not set up
- return AsyncThrowingStream { continuation in
- Task {
- do {
- for try await generation in try MLXLMCommon.generate(
- input: input,
- cache: cache,
- parameters: parameters,
- context: context
- ) {
- switch generation {
- case .chunk(let text):
- continuation.yield(text)
- case .info(_), .toolCall(_):
- // Ignore info and tool calls for speculative generation
- break
- }
- }
- continuation.finish()
- } catch {
- continuation.finish(throwing: error)
- }
- }
- }
- }
-
- /// Get speculative decoding status
- func getStatus() -> SpeculativeStatus {
- SpeculativeStatus(
- enabled: config != nil,
- numDraftTokens: config?.numDraftTokens ?? 0,
- hasMedusaHeads: medusaHeads != nil
- )
- }
-}
-
-/// Medusa heads for speculative decoding
-struct MedusaHeads {
- /// Number of prediction heads
- let numHeads: Int
-
- /// Hidden dimension size
- let hiddenSize: Int
-
- /// Head configurations
- let heads: [MedusaHead]
-
- /// Tree mask for parallel decoding paths
- let treeMask: MLXArray?
-
- /// Tree indices for selecting paths
- let treeIndices: MLXArray?
-}
-
-/// Configuration for a single Medusa head
-struct MedusaHead {
- let index: Int
- let hiddenSize: Int
- let intermediateSize: Int
-}
-
-/// Status of speculative decoding
-struct SpeculativeStatus {
- let enabled: Bool
- let numDraftTokens: Int
- let hasMedusaHeads: Bool
-}
-
// MARK: - Paged Attention Support
/// Paged KV cache for memory-efficient attention computation
diff --git a/mlx-server/Sources/MLXServer/Server.swift b/mlx-server/Sources/MLXServer/Server.swift
index e505d16ea..8e690f10a 100644
--- a/mlx-server/Sources/MLXServer/Server.swift
+++ b/mlx-server/Sources/MLXServer/Server.swift
@@ -8,22 +8,22 @@ struct MLXHTTPServer {
let apiKey: String
let batchingConfig: BatchingConfig?
private var batchProcessor: BatchProcessor?
-
+
init(modelRunner: ModelRunner, modelId: String, apiKey: String, batchingConfig: BatchingConfig? = nil) {
self.modelRunner = modelRunner
self.modelId = modelId
self.apiKey = apiKey
self.batchingConfig = batchingConfig
-
+
// Initialize batch processor if batching is enabled
if let config = batchingConfig, config.maxBatchSize > 0 {
self.batchProcessor = BatchProcessor(modelRunner: modelRunner, config: config)
}
}
-
+
func buildRouter() -> Router<BasicRequestContext> {
let router = Router()
-
+
// Health check
router.get("/health") { _, _ in
let batchingStatus: String
@@ -38,7 +38,7 @@ struct MLXHTTPServer {
)
return try encodeJSON(response)
}
-
+
// Metrics endpoint
router.get("/metrics") { _, _ in
let metrics: [String: Any]
@@ -61,24 +61,24 @@ struct MLXHTTPServer {
"batching": "disabled",
]
}
-
+
// Build JSON response
var jsonString = "{\n"
for (key, value) in metrics {
jsonString += " \"\(key)\": \(value),\n"
}
jsonString += "}"
-
+
var buffer = ByteBufferAllocator().buffer(capacity: jsonString.count)
buffer.writeString(jsonString)
-
+
return Response(
status: .ok,
headers: [.contentType: "application/json"],
body: .init(byteBuffer: buffer)
)
}
-
+
// List models
router.get("/v1/models") { _, _ in
let response = ModelsResponse(
@@ -94,13 +94,13 @@ struct MLXHTTPServer {
)
return try encodeJSON(response)
}
-
+
// Chat completions
router.post("/v1/chat/completions") { request, context in
// Validate API key if set
if !self.apiKey.isEmpty {
let authHeader =
- request.headers[.authorization]
+ request.headers[.authorization]
let expectedAuth = "Bearer \(self.apiKey)"
if authHeader != expectedAuth {
let error = ErrorResponse(
@@ -118,12 +118,12 @@ struct MLXHTTPServer {
return response
}
}
-
+
// Parse request body
do {
let body = try await request.body.collect(upTo: 10 * 1024 * 1024) // 10MB max
let chatRequest = try JSONDecoder().decode(ChatCompletionRequest.self, from: body)
-
+
let temperature = chatRequest.temperature ?? 0.7
let topP = chatRequest.top_p ?? 1.0
let maxTokens = chatRequest.max_tokens ?? chatRequest.n_predict ?? 2048
@@ -131,9 +131,9 @@ struct MLXHTTPServer {
let stop = chatRequest.stop ?? []
let isStreaming = chatRequest.stream ?? false
let tools = chatRequest.tools
-
+
log("[mlx] Request: model=\(chatRequest.model), messages=\(chatRequest.messages.count), stream=\(isStreaming), tools=\(tools?.count ?? 0)")
-
+
if isStreaming {
return try await self.handleStreamingRequest(
chatRequest: chatRequest,
@@ -171,10 +171,10 @@ struct MLXHTTPServer {
)
}
}
-
+
return router
}
-
+
private func handleNonStreamingRequest(
chatRequest: ChatCompletionRequest,
temperature: Float,
@@ -193,14 +193,14 @@ struct MLXHTTPServer {
stop: stop,
tools: tools
)
-
+
let finishReason = toolCalls.isEmpty ? "stop" : "tool_calls"
let message = ChatMessage(
role: "assistant",
content: .string(text.isEmpty && !toolCalls.isEmpty ? "" : text),
tool_calls: toolCalls.isEmpty ? nil : toolCalls
)
-
+
let response = ChatCompletionResponse(
id: generateResponseId(),
object: "chat.completion",
@@ -215,16 +215,16 @@ struct MLXHTTPServer {
],
usage: usage
)
-
+
log("[mlx] Response: \(text.count) chars, \(toolCalls.count) tool call(s), finish=\(finishReason)")
-
+
return try Response(
status: .ok,
headers: [.contentType: "application/json"],
body: .init(byteBuffer: encodeJSONBuffer(response))
)
}
-
+
private func handleStreamingRequest(
chatRequest: ChatCompletionRequest,
temperature: Float,
@@ -237,7 +237,7 @@ struct MLXHTTPServer {
let responseId = generateResponseId()
let created = currentTimestamp()
let model = chatRequest.model
-
+
let stream = await modelRunner.generateStream(
messages: chatRequest.messages,
temperature: temperature,
@@ -247,7 +247,7 @@ struct MLXHTTPServer {
stop: stop,
tools: tools
)
-
+
// Build SSE response body
let responseStream = AsyncStream<ByteBuffer> { continuation in
Task {
@@ -270,105 +270,28 @@ struct MLXHTTPServer {
} else {
log("[mlx] Warning: Failed to encode initial chunk")
}
-
- // State for reasoning/thinking tag handling
- var isInThinkingBlock = false
- var accumulatedReasoning = ""
-
+
do {
for try await event in stream {
switch event {
case .chunk(let token):
- var remainingToken = token
- var reasoningContent = ""
-
- // State machine to handle thinking tags
- if isInThinkingBlock {
- // We're inside a thinking block, look for closing tag
- let lowerRemaining = remainingToken.lowercased()
- if lowerRemaining.contains("</thinking>") {
- // Found the closing tag
- if let range = remainingToken.range(of: "</thinking>", options: .caseInsensitive) {
- accumulatedReasoning += String(remainingToken[..<range.lowerBound])
- reasoningContent = accumulatedReasoning
- remainingToken = String(remainingToken[range.upperBound...])
- }
- isInThinkingBlock = false
- accumulatedReasoning = ""
- } else {
- // Still in thinking block, accumulate content
- accumulatedReasoning += remainingToken
- remainingToken = ""
- }
- } else {
- // Not in thinking block, check if we're starting one
- let lowerToken = token.lowercased()
- if lowerToken.contains("<thinking>") {
- isInThinkingBlock = true
- // Extract content after opening tag
- if let range = token.range(of: "<thinking>", options: .caseInsensitive) {
- let afterTag = String(token[range.upperBound...])
- // Check if there's a closing tag in the same chunk
- if afterTag.lowercased().contains("</thinking>") {
- if let endRange = afterTag.range(of: "</thinking>", options: .caseInsensitive) {
- reasoningContent = String(afterTag[..<endRange.lowerBound])
- remainingToken = String(afterTag[endRange.upperBound...])
- }
- isInThinkingBlock = false
- } else {
- accumulatedReasoning = afterTag
- remainingToken = ""
- }
- }
- } else {
- // Not a thinking block, emit as regular content
- remainingToken = token
- }
- }
-
- // Send chunk with reasoning content if we completed a thinking block
- let chunk: ChatCompletionChunk
- if !reasoningContent.isEmpty {
- chunk = ChatCompletionChunk(
- id: responseId,
- object: "chat.completion.chunk",
- created: created,
- model: model,
- choices: [
- ChatChunkChoice(
- index: 0,
- delta: ChatDelta(
- role: nil,
- content: remainingToken.isEmpty ? nil : remainingToken,
- reasoning_content: reasoningContent
- ),
- finish_reason: nil
- )
- ]
- )
- } else if !remainingToken.isEmpty {
- chunk = ChatCompletionChunk(
- id: responseId,
- object: "chat.completion.chunk",
- created: created,
- model: model,
- choices: [
- ChatChunkChoice(
- index: 0,
- delta: ChatDelta(role: nil, content: remainingToken),
- finish_reason: nil
- )
- ]
- )
- } else {
- // No content to send this iteration
- break
- }
-
+ let chunk = ChatCompletionChunk(
+ id: responseId,
+ object: "chat.completion.chunk",
+ created: created,
+ model: model,
+ choices: [
+ ChatChunkChoice(
+ index: 0,
+ delta: ChatDelta(role: nil, content: token),
+ finish_reason: nil
+ )
+ ]
+ )
if let data = try? encodeJSONData(chunk) {
continuation.yield(buildSSEFrame(data))
}
-
+
case .toolCall(let toolCallInfo):
let chunk = ChatCompletionChunk(
id: responseId,
@@ -400,28 +323,9 @@ struct MLXHTTPServer {
if let data = try? encodeJSONData(chunk) {
continuation.yield(buildSSEFrame(data))
}
-
+
case .done(let usage, let timings, let hasToolCalls):
- // Flush any remaining thinking content before done
- if isInThinkingBlock && !accumulatedReasoning.isEmpty {
- let thinkingChunk = ChatCompletionChunk(
- id: responseId,
- object: "chat.completion.chunk",
- created: created,
- model: model,
- choices: [
- ChatChunkChoice(
- index: 0,
- delta: ChatDelta(role: nil, content: nil, reasoning_content: accumulatedReasoning),
- finish_reason: nil
- )
- ]
- )
- if let data = try? encodeJSONData(thinkingChunk) {
- continuation.yield(buildSSEFrame(data))
- }
- }
-
+
let finishReason = hasToolCalls ? "tool_calls" : "stop"
// Final chunk with finish_reason
let finalChunk = ChatCompletionChunk(
@@ -442,7 +346,7 @@ struct MLXHTTPServer {
if let data = try? encodeJSONData(finalChunk) {
continuation.yield(buildSSEFrame(data))
}
-
+
// Send [DONE]
var doneBuffer = ByteBufferAllocator().buffer(capacity: 16)
doneBuffer.writeString("data: [DONE]\n\n")
@@ -457,11 +361,11 @@ struct MLXHTTPServer {
"error: {\"message\":\"\(error.localizedDescription)\"}\n\n")
continuation.yield(buffer)
}
-
+
continuation.finish()
}
}
-
+
return Response(
status: .ok,
headers: [
diff --git a/src-tauri/plugins/tauri-plugin-mlx/.gitignore b/src-tauri/plugins/tauri-plugin-mlx/.gitignore
new file mode 100644
index 000000000..5d3934a86
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-mlx/.gitignore
@@ -0,0 +1,12 @@
+/.vs
+.DS_Store
+package-lock.json
+yarn.lock
+
+/.tauri
+/target
+Cargo.lock
+node_modules/
+
+dist-js
+dist
diff --git a/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.cjs b/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.cjs
deleted file mode 100644
index 4548fb807..000000000
--- a/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.cjs
+++ /dev/null
@@ -1,62 +0,0 @@
-'use strict';
-
-var core = require('@tauri-apps/api/core');
-
-function asNumber(v, defaultValue = 0) {
- if (v === '' || v === null || v === undefined)
- return defaultValue;
- const n = Number(v);
- return isFinite(n) ? n : defaultValue;
-}
-function asString(v, defaultValue = '') {
- if (v === '' || v === null || v === undefined)
- return defaultValue;
- return String(v);
-}
-function normalizeMlxConfig(config) {
- return {
- ctx_size: asNumber(config.ctx_size),
- n_predict: asNumber(config.n_predict),
- threads: asNumber(config.threads),
- chat_template: asString(config.chat_template),
- };
-}
-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', {
- modelId,
- modelPath,
- port,
- config,
- envs,
- isEmbedding,
- timeout,
- });
-}
-async function unloadMlxModel(pid) {
- return await core.invoke('plugin:mlx|unload_mlx_model', { pid });
-}
-async function isMlxProcessRunning(pid) {
- return await core.invoke('plugin:mlx|is_mlx_process_running', { pid });
-}
-async function getMlxRandomPort() {
- return await core.invoke('plugin:mlx|get_mlx_random_port');
-}
-async function findMlxSessionByModel(modelId) {
- return await core.invoke('plugin:mlx|find_mlx_session_by_model', { modelId });
-}
-async function getMlxLoadedModels() {
- return await core.invoke('plugin:mlx|get_mlx_loaded_models');
-}
-async function getMlxAllSessions() {
- return await core.invoke('plugin:mlx|get_mlx_all_sessions');
-}
-
-exports.findMlxSessionByModel = findMlxSessionByModel;
-exports.getMlxAllSessions = getMlxAllSessions;
-exports.getMlxLoadedModels = getMlxLoadedModels;
-exports.getMlxRandomPort = getMlxRandomPort;
-exports.isMlxProcessRunning = isMlxProcessRunning;
-exports.loadMlxModel = loadMlxModel;
-exports.normalizeMlxConfig = normalizeMlxConfig;
-exports.unloadMlxModel = unloadMlxModel;
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
deleted file mode 100644
index 4e21012d6..000000000
--- a/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.d.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { SessionInfo, UnloadResult, MlxConfig } from './types';
-export { SessionInfo, UnloadResult, MlxConfig } from './types';
-export declare function normalizeMlxConfig(config: any): MlxConfig;
-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>;
-export declare function findMlxSessionByModel(modelId: string): Promise<SessionInfo | null>;
-export declare function getMlxLoadedModels(): Promise<string[]>;
-export declare function getMlxAllSessions(): Promise<SessionInfo[]>;
diff --git a/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.js b/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.js
deleted file mode 100644
index 7c94caf10..000000000
--- a/src-tauri/plugins/tauri-plugin-mlx/dist-js/index.js
+++ /dev/null
@@ -1,53 +0,0 @@
-import { invoke } from '@tauri-apps/api/core';
-
-function asNumber(v, defaultValue = 0) {
- if (v === '' || v === null || v === undefined)
- return defaultValue;
- const n = Number(v);
- return isFinite(n) ? n : defaultValue;
-}
-function asString(v, defaultValue = '') {
- if (v === '' || v === null || v === undefined)
- return defaultValue;
- return String(v);
-}
-function normalizeMlxConfig(config) {
- return {
- ctx_size: asNumber(config.ctx_size),
- n_predict: asNumber(config.n_predict),
- threads: asNumber(config.threads),
- chat_template: asString(config.chat_template),
- };
-}
-async function loadMlxModel(modelId, modelPath, port, cfg, envs, isEmbedding = false, timeout = 600) {
- const config = normalizeMlxConfig(cfg);
- return await invoke('plugin:mlx|load_mlx_model', {
- modelId,
- modelPath,
- port,
- config,
- envs,
- isEmbedding,
- timeout,
- });
-}
-async function unloadMlxModel(pid) {
- return await invoke('plugin:mlx|unload_mlx_model', { pid });
-}
-async function isMlxProcessRunning(pid) {
- return await invoke('plugin:mlx|is_mlx_process_running', { pid });
-}
-async function getMlxRandomPort() {
- return await invoke('plugin:mlx|get_mlx_random_port');
-}
-async function findMlxSessionByModel(modelId) {
- return await invoke('plugin:mlx|find_mlx_session_by_model', { modelId });
-}
-async function getMlxLoadedModels() {
- return await invoke('plugin:mlx|get_mlx_loaded_models');
-}
-async function getMlxAllSessions() {
- return await invoke('plugin:mlx|get_mlx_all_sessions');
-}
-
-export { findMlxSessionByModel, getMlxAllSessions, getMlxLoadedModels, getMlxRandomPort, isMlxProcessRunning, loadMlxModel, normalizeMlxConfig, unloadMlxModel };
diff --git a/src-tauri/plugins/tauri-plugin-mlx/dist-js/types.d.ts b/src-tauri/plugins/tauri-plugin-mlx/dist-js/types.d.ts
deleted file mode 100644
index 3f7feb0f4..000000000
--- a/src-tauri/plugins/tauri-plugin-mlx/dist-js/types.d.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-export interface SessionInfo {
- pid: number;
- port: number;
- model_id: string;
- model_path: string;
- is_embedding: boolean;
- api_key: string;
-}
-export interface UnloadResult {
- success: boolean;
- error?: string;
-}
-export type MlxConfig = {
- ctx_size: number;
- n_predict: number;
- threads: number;
- chat_template: string;
-};
diff --git a/src-tauri/plugins/tauri-plugin-mlx/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-mlx/guest-js/types.ts
index 2da8d442a..d2a615ff6 100644
--- a/src-tauri/plugins/tauri-plugin-mlx/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-mlx/guest-js/types.ts
@@ -17,4 +17,9 @@ export type MlxConfig = {
n_predict: number
threads: number
chat_template: string
+ batch_size: number
+ batch_timeout_ms: number
+ enable_continuous_batching: boolean
+ kv_block_size: number
+ enable_prefix_caching: boolean
}
diff --git a/web-app/src/hooks/useThreads.ts b/web-app/src/hooks/useThreads.ts
index 76b5c2c81..3ae8e2c24 100644
--- a/web-app/src/hooks/useThreads.ts
+++ b/web-app/src/hooks/useThreads.ts
@@ -38,12 +38,17 @@ type ThreadState = {
// Helper function to clean up vector DB collection for a thread
const cleanupVectorDB = async (threadId: string) => {
try {
- const vec = ExtensionManager.getInstance().get<VectorDBExtension>(ExtensionTypeEnum.VectorDB)
+ const vec = ExtensionManager.getInstance().get<VectorDBExtension>(
+ ExtensionTypeEnum.VectorDB
+ )
if (vec?.deleteCollection) {
await vec.deleteCollection(`attachments_${threadId}`)
}
} catch (e) {
- console.warn(`[Threads] Failed to delete vector DB collection for thread ${threadId}:`, e)
+ console.warn(
+ `[Threads] Failed to delete vector DB collection for thread ${threadId}:`,
+ e
+ )
}
}
@@ -57,16 +62,15 @@ export const useThreads = create<ThreadState>()((set, get) => ({
...thread,
model: thread.model
? {
- provider: thread.model.provider.replace(
- 'llama.cpp',
- 'llamacpp'
- ),
+ provider:
+ thread.model?.provider?.replace('llama.cpp', 'llamacpp') ??
+ 'llamacpp',
// Cortex migration: take first two parts of the ID (the last is file name which is not needed)
id:
- thread.model.provider === 'llama.cpp' ||
- thread.model.provider === 'llamacpp'
+ thread.model?.provider === 'llama.cpp' ||
+ thread.model?.provider === 'llamacpp'
? thread.model?.id
- .split(':')
+ ?.split(':')
.slice(0, 2)
.join(getServiceHub().path().sep())
: thread.model?.id,
@@ -78,7 +82,9 @@ export const useThreads = create<ThreadState>()((set, get) => ({
{} as Record<string, Thread>
)
// Filter out temporary chat for search index
- const filteredForSearch = Object.values(threadMap).filter(t => t.id !== TEMPORARY_CHAT_ID)
+ const filteredForSearch = Object.values(threadMap).filter(
+ (t) => t.id !== TEMPORARY_CHAT_ID
+ )
set({
threads: threadMap,
@@ -91,7 +97,9 @@ export const useThreads = create<ThreadState>()((set, get) => ({
const { threads, searchIndex } = get()
// Filter out temporary chat from all operations
- const filteredThreadsValues = Object.values(threads).filter(t => t.id !== TEMPORARY_CHAT_ID)
+ const filteredThreadsValues = Object.values(threads).filter(
+ (t) => t.id !== TEMPORARY_CHAT_ID
+ )
// If no search term, return all threads
if (!searchTerm) {
@@ -151,9 +159,14 @@ export const useThreads = create<ThreadState>()((set, get) => ({
return {
threads: remainingThreads,
- searchIndex: new Fzf<Thread[]>(Object.values(remainingThreads).filter(t => t.id !== TEMPORARY_CHAT_ID), {
- selector: (item: Thread) => item.title,
- }),
+ searchIndex: new Fzf<Thread[]>(
+ Object.values(remainingThreads).filter(
+ (t) => t.id !== TEMPORARY_CHAT_ID
+ ),
+ {
+ selector: (item: Thread) => item.title,
+ }
+ ),
}
})
},
@@ -192,9 +205,14 @@ export const useThreads = create<ThreadState>()((set, get) => ({
return {
threads: remainingThreads,
- searchIndex: new Fzf<Thread[]>(Object.values(remainingThreads).filter(t => t.id !== TEMPORARY_CHAT_ID), {
- selector: (item: Thread) => item.title,
- }),
+ searchIndex: new Fzf<Thread[]>(
+ Object.values(remainingThreads).filter(
+ (t) => t.id !== TEMPORARY_CHAT_ID
+ ),
+ {
+ selector: (item: Thread) => item.title,
+ }
+ ),
}
})
},
@@ -246,18 +264,25 @@ export const useThreads = create<ThreadState>()((set, get) => ({
setCurrentThreadId: (threadId) => {
if (threadId !== get().currentThreadId) set({ currentThreadId: threadId })
},
- createThread: async (model, title, assistant, projectMetadata, isTemporary) => {
+ createThread: async (
+ model,
+ title,
+ assistant,
+ projectMetadata,
+ isTemporary
+ ) => {
const newThread: Thread = {
id: isTemporary ? TEMPORARY_CHAT_ID : ulid(),
title: title ?? (isTemporary ? 'Temporary Chat' : 'New Thread'),
model,
updated: Date.now() / 1000,
assistants: assistant ? [assistant] : [],
- ...(projectMetadata && !isTemporary && {
- metadata: {
- project: projectMetadata,
- },
- }),
+ ...(projectMetadata &&
+ !isTemporary && {
+ metadata: {
+ project: projectMetadata,
+ },
+ }),
...(isTemporary && {
metadata: {
isTemporary: true,
@@ -341,9 +366,12 @@ export const useThreads = create<ThreadState>()((set, get) => ({
const newThreads = { ...state.threads, [threadId]: updatedThread }
return {
threads: newThreads,
- searchIndex: new Fzf<Thread[]>(Object.values(newThreads).filter(t => t.id !== TEMPORARY_CHAT_ID), {
- selector: (item: Thread) => item.title,
- }),
+ searchIndex: new Fzf<Thread[]>(
+ Object.values(newThreads).filter((t) => t.id !== TEMPORARY_CHAT_ID),
+ {
+ selector: (item: Thread) => item.title,
+ }
+ ),
}
})
},
@@ -371,9 +399,14 @@ export const useThreads = create<ThreadState>()((set, get) => ({
return {
threads: updatedThreads,
- searchIndex: new Fzf<Thread[]>(Object.values(updatedThreads).filter(t => t.id !== TEMPORARY_CHAT_ID), {
- selector: (item: Thread) => item.title,
- }),
+ searchIndex: new Fzf<Thread[]>(
+ Object.values(updatedThreads).filter(
+ (t) => t.id !== TEMPORARY_CHAT_ID
+ ),
+ {
+ selector: (item: Thread) => item.title,
+ }
+ ),
}
})
},
@@ -393,9 +426,12 @@ export const useThreads = create<ThreadState>()((set, get) => ({
const newThreads = { ...state.threads, [threadId]: updatedThread }
return {
threads: newThreads,
- searchIndex: new Fzf<Thread[]>(Object.values(newThreads).filter(t => t.id !== TEMPORARY_CHAT_ID), {
- selector: (item: Thread) => item.title,
- }),
+ searchIndex: new Fzf<Thread[]>(
+ Object.values(newThreads).filter((t) => t.id !== TEMPORARY_CHAT_ID),
+ {
+ selector: (item: Thread) => item.title,
+ }
+ ),
}
})
},
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index eae27064f..f16f6918d 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -25,7 +25,11 @@
* - Returns a unified LanguageModel interface compatible with Vercel AI SDK
*/
-import { type LanguageModel } from 'ai'
+import {
+ extractReasoningMiddleware,
+ wrapLanguageModel,
+ type LanguageModel,
+} from 'ai'
import { createOpenAI } from '@ai-sdk/openai'
import {
createOpenAICompatible,
@@ -51,7 +55,6 @@ interface LlamaCppChunk {
timings?: LlamaCppTimings
}
-
/**
* Custom metadata extractor for MLX that extracts timing information
* and converts it to token usage format. MLX uses the same timing structure
@@ -187,8 +190,14 @@ export class ModelFactory {
fetch: fetch,
})
- return openAICompatible.languageModel(modelId, {
- metadataExtractor: providerMetadataExtractor,
+ return wrapLanguageModel({
+ model: openAICompatible.languageModel(modelId, {
+ metadataExtractor: providerMetadataExtractor,
+ }),
+ middleware: extractReasoningMiddleware({
+ tagName: 'think',
+ separator: '\n',
+ }),
})
}
@@ -241,8 +250,16 @@ export class ModelFactory {
fetch: fetch,
metadataExtractor: providerMetadataExtractor,
})
- return model
+
+ return wrapLanguageModel({
+ model: model,
+ middleware: extractReasoningMiddleware({
+ tagName: 'think',
+ separator: '\n',
+ }),
+ })
}
+
/**
* Create an Anthropic model using the official AI SDK
*/
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 804911d1f..fab571a70 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -736,10 +736,10 @@ function ThreadDetail() {
<p className="text-sm text-muted-foreground">
{error.message}
</p>
- {(error.message.toLowerCase().includes('context') &&
- (error.message.toLowerCase().includes('size') ||
- error.message.toLowerCase().includes('length') ||
- error.message.toLowerCase().includes('limit'))) ||
+ {(error.message?.toLowerCase().includes('context') &&
+ (error.message?.toLowerCase().includes('size') ||
+ error.message?.toLowerCase().includes('length') ||
+ error.message?.toLowerCase().includes('limit'))) ||
error.message === OUT_OF_CONTEXT_SIZE ? (
<Button
variant="outline"