diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index fee791a..f8861ca 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -8,11 +8,21 @@ on:
jobs:
build-and-test:
- runs-on: macos-15
+ # mlx-swift-lm 3.x and its dependencies need Swift tools 6.3–6.4 (Xcode 26.x).
+ runs-on: macos-26
steps:
- uses: actions/checkout@v7
+ - name: Select the newest Xcode
+ # Plain shell, not a third-party action: the repo only allows GitHub-owned
+ # and verified actions, and setup-xcode is neither (startup_failure).
+ run: |
+ X=$(ls -d /Applications/Xcode_*.app | grep -v -i beta | sort -V | tail -1)
+ sudo xcode-select -s "$X"
+ xcodebuild -version
+ swift --version
+
- name: Install Metal Toolchain
# MLX Code bundles mlx-swift, which compiles Metal shaders; recent Xcode no
# longer ships the Metal Toolchain by default, so the build fails without this.
@@ -25,6 +35,8 @@ jobs:
-project "MLX Code.xcodeproj" \
-scheme "MLX Code" \
-destination 'platform=macOS' \
+ -skipMacroValidation \
+ -skipPackagePluginValidation \
CODE_SIGNING_ALLOWED=NO \
CODE_SIGNING_REQUIRED=NO \
SWIFT_TREAT_WARNINGS_AS_ERRORS=NO \
diff --git a/.gitignore b/.gitignore
index cfc8ecb..d8c3fbe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,6 +25,8 @@ build/
Packages/
Package.pins
Package.resolved
+# ...but commit the app's pinned dependency graph
+!MLX Code.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
# macOS
.DS_Store
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c782333..914882e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [6.4.0] - 2026-11-06
+
+### Changed
+- **mlx-swift-lm 2.30 → 3.32.3** and **mlx-swift 0.30 → 0.32.3** (0.32.3 is the newest mlx-swift that mlx-swift-lm 3.32.3 accepts; it requires `upToNextMinor(0.32.3)`). Migrated per the upstream 3.x upgrade guide: `HubApi`/`defaultHubApi` → `HuggingFace.HubClient`, `loadContainer(hub:)` → `loadContainer(from: URL, using: #huggingFaceTokenizerLoader())`. Added the `MLXHuggingFace`, `HuggingFace` (swift-huggingface 0.13) and `Tokenizers` (swift-transformers 1.4) products
+- `Package.resolved` is now committed so every build resolves the same dependency graph
+- Default repetition penalty lowered from 1.8 to 1.1; persisted models still carrying the old 1.8 default are migrated on load
+- `topK`, `minP` and `repetitionContextSize` are now passed to the sampler (previously only temperature/top-p/penalty were)
+- Model catalog refreshed with current mlx-community 4-bit repos supported by mlx-swift-lm 3.x: Qwen3.5 9B (new default), Qwen3-Coder 30B-A3B, Devstral Small 2 24B, Qwen3.6 35B-A3B, Qwen3.6 27B, Gemma 4 E4B, Qwen3.5 2B (Qwen 2.5 7B kept as legacy)
+- CI passes `-skipMacroValidation -skipPackagePluginValidation` (required for the MLXHuggingFace macros)
+
### Added
+- **Native tool calling**: ToolRegistry tools are converted to `ToolSpec`s and passed to the chat template; `Generation.toolCall` events (including several per response) are mapped into the existing `` approval/execution flow. The text `` parser remains as a fallback
+- **KV-cache settings** (Settings → Model): KV quantization none/8-bit/4-bit, max KV size (rotating cache), prefill step size — mapped into `GenerateParameters`
+- `InferenceGenerator` protocol + `MLXContainerGenerator`, `GenerationParameterMapper`, `ToolSpecBuilder`, `NativeToolCallFormatter`, `ModelConfigInspector` (new `InferenceEngine.swift`)
+- `InferenceEngineTests` and a rewritten `MLXServiceTests` (32 tests, mock generator, no model download) plus an opt-in real-model integration test (`MLXCODE_INTEGRATION=1`)
- Multi-model load balancing: optionally spread each chat across all installed local models (native MLX + Ollama), all frontier models (OpenRouter), and an optional Nova Gateway — health-gated and load-balanced — instead of a single pinned model
- Three independent, persisted toggles in **Settings → Balancer**: All local models, All frontier models (OpenRouter), Nova Gateway (with a configurable gateway URL and Keychain-stored OpenRouter key)
- `ModelRegistry` (model discovery + pool composition), `LoadBalancer` (round-robin / least-busy with health gating), `OpenRouterProvider` / `OpenAICompatibleRequest`, and `KeychainStore` — pure, network-free, unit-tested building blocks ported from AIStudio
@@ -17,6 +31,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- `ChatViewModel` routes generation through the balancer when any toggle is on; falls back cleanly to the single pinned MLX model when the pool is empty or all toggles are off (existing behavior preserved)
+### Fixed
+- **Stop now stops generation.** Previously Stop only flipped UI flags while MLXService kept generating to `maxTokens`, so the next request failed with "inference already in progress". Generation now runs in a stored, cancellable Task; MLXService checks cancellation in the stream loop, terminates the mlx-swift-lm token stream, and always resets its busy flag. The agentic tool loop does not continue after Stop, and the load balancer no longer fails over on cancellation
+- Repetition/length guards now actually stop the model instead of discarding tokens while generation continues
+- Model downloads only fetched `*.safetensors` and `*.json`, silently dropping `chat_template.jinja`, `merges.txt`, `tokenizer.model` etc. Patterns now live in `MLXService.downloadPatterns` and include `*.jinja`, `*.txt`, `*.model`
+- Context window is now read from nested `text_config` as well as top-level `config.json` keys (Qwen3.5/3.6, Gemma 4, Devstral 2 previously fell back to 8K); discovered and downloaded models record it too
+- `Python/setup.sh`: version specifiers are quoted (unquoted `mlx>=…` was a shell redirect that created the stray `Python/=0.0.10`-style files)
+
+### Removed
+- Dead Python inference scripts (`mlx_inference.py`, `mlx_daemon.py`) and the unused `huggingface_downloader.py` / `rag_system.py`, their bundle Resources entries, and the junk `Python/=*` files
+- `MLXServiceTests` cases that exercised the removed Python daemon protocol
+
### Notes
- Nova is never a hard requirement — the balancer works with zero Nova present; the Nova Gateway is one optional, health-probed entry that drops out if unavailable
diff --git a/MLX Code Tests/InferenceEngineTests.swift b/MLX Code Tests/InferenceEngineTests.swift
new file mode 100644
index 0000000..22f2e8e
--- /dev/null
+++ b/MLX Code Tests/InferenceEngineTests.swift
@@ -0,0 +1,286 @@
+//
+// InferenceEngineTests.swift
+// MLX Code Tests
+//
+// Pure unit tests for the mlx-swift-lm 3.x seam: parameter mapping, KV-cache
+// settings, ModelParameters decoding/migration, model catalog, config.json
+// context-window parsing, ToolRegistry -> ToolSpec, native tool-call rendering.
+// No model download required.
+//
+
+import XCTest
+@testable import MLX_Code
+
+/// Minimal tool used to exercise schema conversion of enum/items/default.
+private struct SchemaProbeTool: Tool {
+ let name = "schema_probe"
+ let description = "Probe tool for schema tests"
+ let parameters = ToolParameterSchema(
+ properties: [
+ "mode": ParameterProperty(type: "string", description: "Mode", enum: ["fast", "slow"], default: "fast"),
+ "paths": ParameterProperty(
+ type: "array",
+ description: "Paths",
+ items: ParameterProperty(type: "string", description: "A path")
+ ),
+ "limit": ParameterProperty(type: "integer", description: "Max results"),
+ ],
+ required: ["paths"]
+ )
+
+ func execute(parameters: [String: Any], context: ToolContext) async throws -> ToolResult {
+ .success("ok")
+ }
+}
+
+@MainActor
+final class InferenceEngineTests: XCTestCase {
+
+ // MARK: - Parameter mapping
+
+ func testParameterMappingCoversAllFields() {
+ let params = ModelParameters(
+ temperature: 0.7,
+ maxTokens: 1234,
+ topP: 0.85,
+ topK: 33,
+ minP: 0.05,
+ repetitionPenalty: 1.15,
+ repetitionContextSize: 128
+ )
+ let kv = KVCacheSettings(bits: 8, maxSize: 16384, prefillStepSize: 2048)
+ let mapped = GenerationParameterMapper.map(params, kvCache: kv)
+
+ XCTAssertEqual(mapped.maxTokens, 1234)
+ XCTAssertEqual(mapped.temperature, 0.7, accuracy: 1e-6)
+ XCTAssertEqual(mapped.topP, 0.85, accuracy: 1e-6)
+ XCTAssertEqual(mapped.topK, 33)
+ XCTAssertEqual(mapped.minP, 0.05, accuracy: 1e-6)
+ XCTAssertEqual(mapped.repetitionPenalty ?? 0, 1.15, accuracy: 1e-6)
+ XCTAssertEqual(mapped.repetitionContextSize, 128)
+ XCTAssertEqual(mapped.kvBits, 8)
+ XCTAssertEqual(mapped.maxKVSize, 16384)
+ XCTAssertEqual(mapped.prefill.stepSize, 2048)
+ }
+
+ func testParameterMappingDefaults() {
+ let mapped = GenerationParameterMapper.map(ModelParameters())
+ XCTAssertNil(mapped.kvBits, "Default KV cache is full precision")
+ XCTAssertNil(mapped.maxKVSize, "Default KV cache is unbounded")
+ XCTAssertEqual(mapped.prefill.stepSize, 512)
+ XCTAssertEqual(mapped.topK, 40)
+ XCTAssertEqual(mapped.minP, 0, accuracy: 1e-6)
+ XCTAssertEqual(mapped.repetitionPenalty ?? 0, 1.1, accuracy: 1e-6)
+ XCTAssertEqual(mapped.repetitionContextSize, 256)
+ }
+
+ func testKVCacheSettingsSanitized() {
+ let bad = KVCacheSettings(bits: 3, maxSize: 100, prefillStepSize: -5).sanitized()
+ XCTAssertEqual(bad, KVCacheSettings(bits: 0, maxSize: 0, prefillStepSize: 0))
+
+ let huge = KVCacheSettings(bits: 4, maxSize: 10_000_000, prefillStepSize: 100_000).sanitized()
+ XCTAssertEqual(huge.bits, 4)
+ XCTAssertEqual(huge.maxSize, 1_048_576)
+ XCTAssertEqual(huge.prefillStepSize, 8192)
+
+ // Invalid values never reach GenerateParameters
+ let mapped = GenerationParameterMapper.map(ModelParameters(), kvCache: KVCacheSettings(bits: 3, maxSize: 10, prefillStepSize: 0))
+ XCTAssertNil(mapped.kvBits)
+ XCTAssertNil(mapped.maxKVSize)
+ XCTAssertNil(mapped.prefill.stepSize, "0 = let the model choose")
+ }
+
+ func testAppSettingsExposeSanitizedKVSettings() {
+ let settings = AppSettings.shared
+ let saved = (settings.kvCacheBits, settings.maxKVSize, settings.prefillStepSize)
+ defer {
+ settings.kvCacheBits = saved.0
+ settings.maxKVSize = saved.1
+ settings.prefillStepSize = saved.2
+ }
+ settings.kvCacheBits = 4
+ settings.maxKVSize = 32768
+ settings.prefillStepSize = 1024
+ XCTAssertEqual(settings.kvCacheSettings, KVCacheSettings(bits: 4, maxSize: 32768, prefillStepSize: 1024))
+ settings.kvCacheBits = 5
+ XCTAssertEqual(settings.kvCacheSettings.bits, 0)
+ }
+
+ // MARK: - ModelParameters
+
+ func testDefaultRepetitionPenaltyLowered() {
+ XCTAssertEqual(ModelParameters().repetitionPenalty, 1.1, accuracy: 1e-9)
+ XCTAssertTrue(ModelParameters().isValid())
+ }
+
+ func testMinPValidation() {
+ XCTAssertTrue(ModelParameters(minP: 0).isValid())
+ XCTAssertTrue(ModelParameters(minP: 1).isValid())
+ XCTAssertFalse(ModelParameters(minP: -0.1).isValid())
+ XCTAssertFalse(ModelParameters(minP: 1.1).isValid())
+ }
+
+ func testLegacyParametersDecodeWithMigration() throws {
+ // Persisted before minP existed, with the old 1.8 default penalty.
+ let legacy = #"{"temperature":0.3,"maxTokens":999,"topP":0.8,"topK":20,"repetitionPenalty":1.8,"repetitionContextSize":64}"#
+ let decoded = try JSONDecoder().decode(ModelParameters.self, from: Data(legacy.utf8))
+ XCTAssertEqual(decoded.minP, 0)
+ XCTAssertEqual(decoded.repetitionPenalty, 1.1, accuracy: 1e-9, "Legacy 1.8 default migrates to 1.1")
+ XCTAssertEqual(decoded.maxTokens, 999)
+ XCTAssertEqual(decoded.repetitionContextSize, 64)
+
+ // A deliberately chosen penalty is preserved.
+ let custom = #"{"temperature":0.3,"maxTokens":999,"topP":0.8,"topK":20,"repetitionPenalty":1.3,"repetitionContextSize":64,"minP":0.1}"#
+ let decodedCustom = try JSONDecoder().decode(ModelParameters.self, from: Data(custom.utf8))
+ XCTAssertEqual(decodedCustom.repetitionPenalty, 1.3, accuracy: 1e-9)
+ XCTAssertEqual(decodedCustom.minP, 0.1, accuracy: 1e-9)
+
+ // Round-trip
+ let data = try JSONEncoder().encode(decodedCustom)
+ XCTAssertEqual(try JSONDecoder().decode(ModelParameters.self, from: data), decodedCustom)
+ }
+
+ // MARK: - Model catalog
+
+ func testCatalogIdsAreMLXCommunityQuantizedRepos() {
+ let models = MLXModel.commonModels(basePath: "/tmp/catalog-test") + [MLXModel.default(basePath: "/tmp/catalog-test")]
+ let quantized = try! NSRegularExpression(pattern: #"-(3|4|5|6|8)bit$"#)
+ for model in models {
+ let id = model.huggingFaceId ?? ""
+ XCTAssertTrue(id.hasPrefix("mlx-community/"), "\(id) is not an mlx-community repo")
+ let range = NSRange(id.startIndex..., in: id)
+ XCTAssertNotNil(quantized.firstMatch(in: id, range: range), "\(id) is not a quantized repo")
+ XCTAssertGreaterThan(model.contextWindowSize ?? 0, 0, "\(model.name) needs a context window")
+ XCTAssertTrue(model.isValid())
+ }
+ let ids = models.dropLast().compactMap(\.huggingFaceId)
+ XCTAssertEqual(Set(ids).count, ids.count, "Catalog IDs must be unique")
+ }
+
+ func testCatalogIncludesCurrentGeneration() {
+ let ids = Set(MLXModel.commonModels(basePath: "/tmp/catalog-test").compactMap(\.huggingFaceId))
+ for expected in [
+ "mlx-community/Qwen3-Coder-30B-A3B-Instruct-4bit",
+ "mlx-community/Qwen3.5-9B-4bit",
+ "mlx-community/Qwen3.6-27B-4bit",
+ "mlx-community/Qwen3.6-35B-A3B-4bit",
+ "mlx-community/gemma-4-e4b-it-4bit",
+ "mlx-community/Devstral-Small-2-24B-Instruct-2512-4bit",
+ "mlx-community/Qwen3.5-2B-4bit",
+ ] {
+ XCTAssertTrue(ids.contains(expected), "Catalog is missing \(expected)")
+ }
+ }
+
+ // MARK: - config.json context window
+
+ func testContextWindowTopLevel() {
+ let json = #"{"model_type":"qwen3_moe","max_position_embeddings":262144}"#
+ XCTAssertEqual(ModelConfigInspector.contextWindow(fromConfig: Data(json.utf8)), 262144)
+ }
+
+ func testContextWindowNestedTextConfig() {
+ // Shape of Qwen3.5 / Gemma 4 / Mistral 3 configs on mlx-community
+ let json = #"{"model_type":"gemma4","vision_config":{"max_position_embeddings":4096},"text_config":{"max_position_embeddings":131072,"sliding_window":512}}"#
+ XCTAssertEqual(ModelConfigInspector.contextWindow(fromConfig: Data(json.utf8)), 131072)
+ }
+
+ func testContextWindowTopLevelWinsOverNested() {
+ let json = #"{"max_position_embeddings":8192,"text_config":{"max_position_embeddings":131072}}"#
+ XCTAssertEqual(ModelConfigInspector.contextWindow(fromConfig: Data(json.utf8)), 8192)
+ }
+
+ func testContextWindowAlternateKeys() {
+ XCTAssertEqual(ModelConfigInspector.contextWindow(fromConfig: Data(#"{"seq_length":32768}"#.utf8)), 32768)
+ XCTAssertEqual(ModelConfigInspector.contextWindow(fromConfig: Data(#"{"text_config":{"max_sequence_length":65536}}"#.utf8)), 65536)
+ }
+
+ func testContextWindowMissingOrInvalid() {
+ XCTAssertNil(ModelConfigInspector.contextWindow(fromConfig: Data(#"{"model_type":"llama"}"#.utf8)))
+ XCTAssertNil(ModelConfigInspector.contextWindow(fromConfig: Data(#"{"max_position_embeddings":0}"#.utf8)))
+ XCTAssertNil(ModelConfigInspector.contextWindow(fromConfig: Data("not json".utf8)))
+ }
+
+ // MARK: - ToolRegistry -> ToolSpec
+
+ func testToolRegistryProducesValidToolSpecs() throws {
+ let tools = ToolRegistry.shared.getAllTools()
+ XCTAssertFalse(tools.isEmpty)
+ let specs = ToolSpecBuilder.specs(for: tools)
+ XCTAssertEqual(specs.count, tools.count)
+
+ var names: [String] = []
+ for spec in specs {
+ XCTAssertEqual(spec["type"] as? String, "function")
+ let function = try XCTUnwrap(spec["function"] as? [String: any Sendable])
+ let name = try XCTUnwrap(function["name"] as? String)
+ names.append(name)
+ XCTAssertFalse((function["description"] as? String ?? "").isEmpty, "\(name) needs a description")
+
+ let parameters = try XCTUnwrap(function["parameters"] as? [String: any Sendable])
+ XCTAssertEqual(parameters["type"] as? String, "object")
+ let properties = try XCTUnwrap(parameters["properties"] as? [String: any Sendable])
+ let required = try XCTUnwrap(parameters["required"] as? [String])
+ for key in required {
+ XCTAssertNotNil(properties[key], "\(name): required '\(key)' missing from properties")
+ }
+ for (_, value) in properties {
+ let property = try XCTUnwrap(value as? [String: any Sendable])
+ XCTAssertNotNil(property["type"] as? String)
+ }
+ // Must be serializable to JSON (chat templates render it)
+ XCTAssertTrue(JSONSerialization.isValidJSONObject(spec), "\(name) spec is not JSON-serializable")
+ }
+ XCTAssertEqual(names, names.sorted(), "Specs are sorted for a stable prompt")
+ XCTAssertEqual(Set(names), Set(tools.map(\.name)))
+ }
+
+ func testToolSpecSchemaDetails() throws {
+ let spec = ToolSpecBuilder.spec(for: SchemaProbeTool())
+ let function = try XCTUnwrap(spec["function"] as? [String: any Sendable])
+ XCTAssertEqual(function["name"] as? String, "schema_probe")
+ let parameters = try XCTUnwrap(function["parameters"] as? [String: any Sendable])
+ XCTAssertEqual(parameters["required"] as? [String], ["paths"])
+ let properties = try XCTUnwrap(parameters["properties"] as? [String: any Sendable])
+
+ let mode = try XCTUnwrap(properties["mode"] as? [String: any Sendable])
+ XCTAssertEqual(mode["enum"] as? [String], ["fast", "slow"])
+ XCTAssertEqual(mode["default"] as? String, "fast")
+
+ let paths = try XCTUnwrap(properties["paths"] as? [String: any Sendable])
+ XCTAssertEqual(paths["type"] as? String, "array")
+ let items = try XCTUnwrap(paths["items"] as? [String: any Sendable])
+ XCTAssertEqual(items["type"] as? String, "string")
+
+ let limit = try XCTUnwrap(properties["limit"] as? [String: any Sendable])
+ XCTAssertEqual(limit["type"] as? String, "integer")
+ XCTAssertNil(limit["enum"])
+ }
+
+ // MARK: - Native tool call rendering
+
+ func testNativeToolCallRendersParsableToolBlock() throws {
+ let call = NativeToolCall(name: "bash", arguments: ["command": "ls -la", "timeout": 30, "dry_run": false])
+ let text = NativeToolCallFormatter.render(call)
+ XCTAssertTrue(text.contains(""))
+ XCTAssertTrue(text.contains(""))
+
+ let vm = ChatViewModel(conversationsDirectory: nil)
+ let raw = try XCTUnwrap(vm.extractToolCalls(text).first)
+ let parsed = try XCTUnwrap(ToolRegistry.shared.parseToolCallJSON(raw))
+ XCTAssertEqual(parsed.name, "bash")
+ XCTAssertEqual(parsed.parameters["command"] as? String, "ls -la")
+ XCTAssertEqual(parsed.parameters["timeout"] as? String, "30")
+ XCTAssertEqual(parsed.parameters["dry_run"] as? String, "false")
+ }
+
+ func testTwoNativeToolCallsInOneResponseBothExtracted() {
+ let response = "Checking." +
+ NativeToolCallFormatter.render(NativeToolCall(name: "glob", arguments: ["pattern": "*.swift"])) +
+ NativeToolCallFormatter.render(NativeToolCall(name: "grep", arguments: ["pattern": "FIXME"]))
+ let vm = ChatViewModel(conversationsDirectory: nil)
+ let calls = vm.extractToolCalls(response)
+ XCTAssertEqual(calls.count, 2)
+ XCTAssertEqual(calls.compactMap { ToolRegistry.shared.parseToolCallJSON($0)?.name }, ["glob", "grep"])
+ }
+}
diff --git a/MLX Code Tests/MLXModelTests.swift b/MLX Code Tests/MLXModelTests.swift
index 06e8f6a..35b35cc 100644
--- a/MLX Code Tests/MLXModelTests.swift
+++ b/MLX Code Tests/MLXModelTests.swift
@@ -194,7 +194,8 @@ final class MLXModelTests: XCTestCase {
func testDefaultModelIsQwen() {
let model = MLXModel.default(basePath: "/tmp/test-models")
XCTAssertTrue(model.name.contains("Qwen"), "Default model should be Qwen")
- XCTAssertEqual(model.contextWindowSize, 32768)
+ XCTAssertEqual(model.huggingFaceId, "mlx-community/Qwen3.5-9B-4bit")
+ XCTAssertEqual(model.contextWindowSize, 262144)
}
// MARK: - Equatable / Hashable
diff --git a/MLX Code Tests/MLXServiceTests.swift b/MLX Code Tests/MLXServiceTests.swift
index 9e8fea5..18be08d 100644
--- a/MLX Code Tests/MLXServiceTests.swift
+++ b/MLX Code Tests/MLXServiceTests.swift
@@ -2,209 +2,369 @@
// MLXServiceTests.swift
// MLX Code Tests
//
-// Unit tests for MLXService model loading
+// Unit tests for MLXService's generation state machine: streaming, cancellation
+// (Stop), busy-flag reset, KV/parameter plumbing, native tool-call mapping and
+// download file patterns. Uses a mock InferenceGenerator — no model download.
+//
+// Optional integration test: set MLXCODE_INTEGRATION=1 and MLXCODE_MODEL_PATH= (via `TEST_RUNNER_MLXCODE_INTEGRATION=1` etc. with xcodebuild).
//
import XCTest
@testable import MLX_Code
-@MainActor
-class MLXServiceTests: XCTestCase {
-
- func testPythonResponseDecoding() throws {
- // Test all response types the daemon can send
- let testCases: [(json: String, shouldSucceed: Bool, description: String)] = [
- (
- json: #"{"type":"ready","message":"Daemon started and ready"}"#,
- shouldSucceed: true,
- description: "Ready response"
- ),
- (
- json: #"{"type":"debug","message":"load_model() called with: /path"}"#,
- shouldSucceed: true,
- description: "Debug response"
- ),
- (
- json: #"{"success":true,"path":"/Users/testuser/.mlx/models/phi-3.5-mini","name":"phi-3.5-mini","cached":false,"message":"Model loaded successfully"}"#,
- shouldSucceed: true,
- description: "Load success response (missing 'type' field)"
- ),
- (
- json: #"{"type":"token","token":"Hello"}"#,
- shouldSucceed: true,
- description: "Token response"
- ),
- (
- json: #"{"type":"complete","message":"Generation finished"}"#,
- shouldSucceed: true,
- description: "Complete response"
- ),
- (
- json: #"{"type":"error","error":"Something failed"}"#,
- shouldSucceed: true,
- description: "Error response"
- )
- ]
-
- print("\n=== Testing JSON Response Decoding ===\n")
-
- for (index, testCase) in testCases.enumerated() {
- print("Test \(index + 1): \(testCase.description)")
- print(" JSON: \(testCase.json)")
-
- guard let jsonData = testCase.json.data(using: .utf8) else {
- XCTFail("Failed to convert JSON string to data")
- continue
- }
+// MARK: - Mock Generator
- do {
- let decoder = JSONDecoder()
- let response = try decoder.decode(PythonResponse.self, from: jsonData)
- print(" ✅ Decoded successfully")
- print(" type: \(response.type ?? "nil")")
- print(" success: \(response.success ?? false)")
- print(" message: \(response.message ?? "nil")")
- print(" path: \(response.path ?? "nil")")
-
- if testCase.shouldSucceed {
- print(" ✅ PASS\n")
- } else {
- XCTFail("Should have failed but succeeded")
- print(" ❌ FAIL: Should have thrown error\n")
- }
- } catch {
- print(" ❌ Decode error: \(error)")
-
- if !testCase.shouldSucceed {
- print(" ✅ PASS (expected to fail)\n")
- } else {
- XCTFail("Decoding failed: \(error)")
- print(" ❌ FAIL: \(error)\n")
+/// Scripted generator: yields `events`, then (optionally) keeps streaming until cancelled.
+final class MockInferenceGenerator: InferenceGenerator, @unchecked Sendable {
+ private let lock = NSLock()
+ private let events: [InferenceEvent]
+ private let streamUntilCancelled: Bool
+ private var _requests: [InferenceRequest] = []
+ private var _terminations = 0
+
+ init(events: [InferenceEvent], streamUntilCancelled: Bool = false) {
+ self.events = events
+ self.streamUntilCancelled = streamUntilCancelled
+ }
+
+ var requests: [InferenceRequest] { lock.withLock { _requests } }
+ var terminations: Int { lock.withLock { _terminations } }
+
+ func generate(_ request: InferenceRequest) async throws -> AsyncStream {
+ lock.withLock { _requests.append(request) }
+ let events = self.events
+ let endless = streamUntilCancelled
+ return AsyncStream { continuation in
+ let producer = Task {
+ for event in events { continuation.yield(event) }
+ var counter = 0
+ while endless && !Task.isCancelled {
+ // Unique chunks so ChatViewModel's RepetitionDetector never trips.
+ counter += 1
+ continuation.yield(.chunk("w\(counter)-\(UUID().uuidString.prefix(6)) "))
+ try? await Task.sleep(nanoseconds: 2_000_000)
}
+ continuation.finish()
+ }
+ continuation.onTermination = { [weak self] _ in
+ producer.cancel()
+ self?.lock.withLock { self?._terminations += 1 }
}
}
}
+}
- func testModelPathValidation() throws {
- print("\n=== Testing Model Path Validation ===\n")
+/// Thread-safe collector for streamed chunks.
+final class ChunkSink: @unchecked Sendable {
+ private let lock = NSLock()
+ private var _chunks: [String] = []
+ var chunks: [String] { lock.withLock { _chunks } }
+ func append(_ chunk: String) { lock.withLock { _chunks.append(chunk) } }
+}
- let fileManager = FileManager.default
- let testPaths = [
- "~/.mlx/models/phi-3.5-mini",
- "/Users/testuser/.mlx/models/phi-3.5-mini",
- "/Users/testuser/Downloads/MLXCode/phi-3.5-mini"
- ]
+@MainActor
+final class MLXServiceTests: XCTestCase {
- for path in testPaths {
- let expanded = (path as NSString).expandingTildeInPath
- print("Path: \(path)")
- print(" Expanded: \(expanded)")
+ private let testModel = MLXModel(name: "Mock", path: "/dev/null/mock", isDownloaded: true)
- var isDir: ObjCBool = false
- let exists = fileManager.fileExists(atPath: expanded, isDirectory: &isDir)
- print(" Exists: \(exists)")
- print(" Is directory: \(isDir.boolValue)")
+ private func makeService(
+ _ generator: MockInferenceGenerator,
+ kv: KVCacheSettings = .default
+ ) -> MLXService {
+ MLXService(generator: generator, model: testModel, contextWindow: 4096, kvCacheSettings: kv)
+ }
- if exists {
- let configPath = (expanded as NSString).appendingPathComponent("config.json")
- let configExists = fileManager.fileExists(atPath: configPath)
- print(" config.json exists: \(configExists)")
+ /// Polls until `condition` is true or the timeout elapses.
+ private func waitUntil(timeout: TimeInterval = 5, _ condition: () async -> Bool) async -> Bool {
+ let deadline = Date().addingTimeInterval(timeout)
+ while Date() < deadline {
+ if await condition() { return true }
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ return await condition()
+ }
- if configExists {
- print(" ✅ VALID MODEL\n")
- } else {
- print(" ❌ Missing config.json\n")
- }
- } else {
- print(" ❌ Path does not exist\n")
- }
+ // MARK: - Download patterns
+
+ func testDownloadPatternsCoverTokenizerAndTemplateFiles() {
+ let patterns = MLXService.downloadPatterns
+ for required in ["*.safetensors", "*.json", "*.jinja", "*.txt", "*.model"] {
+ XCTAssertTrue(patterns.contains(required), "Missing download pattern \(required)")
}
+
+ func matches(_ file: String) -> Bool {
+ patterns.contains { fnmatch($0, file, 0) == 0 }
+ }
+ for file in ["chat_template.jinja", "merges.txt", "tokenizer.model", "tokenizer.json",
+ "tokenizer_config.json", "config.json", "model-00001-of-00004.safetensors"] {
+ XCTAssertTrue(matches(file), "\(file) would be skipped by the downloader")
+ }
+ // Never fetch pickle weights
+ XCTAssertFalse(matches("pytorch_model.bin"))
+ XCTAssertFalse(matches("model.pt"))
}
- func testDaemonCommunication() async throws {
- print("\n=== Testing Daemon JSON Communication ===\n")
+ func testDownloadDestinationKeepsLegacyHubLayout() {
+ let base = URL(fileURLWithPath: "/Volumes/Data/models")
+ let dest = MLXService.downloadDestination(for: "mlx-community/Qwen3.5-9B-4bit", in: base)
+ XCTAssertEqual(dest.path, "/Volumes/Data/models/models/mlx-community/Qwen3.5-9B-4bit")
+ }
- // Simulate what the daemon sends
- let daemonResponses = [
- #"{"type":"ready","message":"Daemon started and ready"}"#,
- #"{"success":true,"path":"/Users/testuser/.mlx/models/phi-3.5-mini","name":"phi-3.5-mini","cached":false,"message":"Model loaded successfully"}"#
- ]
+ // MARK: - Streaming + request mapping
- for response in daemonResponses {
- print("Response: \(response)")
+ func testChatCompletionStreamsChunksAndBuildsRequest() async throws {
+ let mock = MockInferenceGenerator(events: [.chunk("Hello"), .chunk(", "), .chunk("world")])
+ let service = makeService(mock)
+ let sink = ChunkSink()
- guard let data = response.data(using: .utf8) else {
- print(" ❌ Cannot convert to data\n")
- XCTFail("Failed to convert response to data")
- continue
- }
+ let result = try await service.chatCompletion(
+ messages: [.system("sys"), .user("hi")],
+ parameters: ModelParameters(temperature: 0.4, topK: 12),
+ streamHandler: { sink.append($0) }
+ )
- do {
- let decoded = try JSONDecoder().decode(PythonResponse.self, from: data)
- print(" ✅ Decoded: type=\(decoded.type ?? "nil"), success=\(decoded.success ?? false)\n")
- } catch {
- print(" ❌ Decode failed: \(error)\n")
- XCTFail("Failed to decode: \(error)")
- }
+ XCTAssertEqual(result, "Hello, world")
+ XCTAssertEqual(sink.chunks, ["Hello", ", ", "world"])
+
+ let request = try XCTUnwrap(mock.requests.first)
+ XCTAssertEqual(request.prompt, .messages([
+ ["role": "system", "content": "sys"],
+ ["role": "user", "content": "hi"],
+ ]))
+ XCTAssertNotNil(request.fallbackPrompt, "Chat requests carry a flat-prompt fallback")
+ XCTAssertNil(request.tools, "No tools passed -> no native tool specs")
+ XCTAssertEqual(request.parameters.temperature, 0.4, accuracy: 0.0001)
+ XCTAssertEqual(request.parameters.topK, 12)
+ let busy = await service.isGenerating()
+ XCTAssertFalse(busy)
+ }
+
+ func testGenerateUsesTextPrompt() async throws {
+ let mock = MockInferenceGenerator(events: [.chunk("ok")])
+ let service = makeService(mock)
+ let result = try await service.generate(prompt: "summarize")
+ XCTAssertEqual(result, "ok")
+ XCTAssertEqual(mock.requests.first?.prompt, .text("summarize"))
+ }
+
+ func testKVCacheSettingsReachGenerateParameters() async throws {
+ let mock = MockInferenceGenerator(events: [.chunk("x")])
+ let service = makeService(mock, kv: KVCacheSettings(bits: 4, maxSize: 8192, prefillStepSize: 1024))
+ _ = try await service.chatCompletion(messages: [.user("hi")])
+
+ let params = try XCTUnwrap(mock.requests.first?.parameters)
+ XCTAssertEqual(params.kvBits, 4)
+ XCTAssertEqual(params.maxKVSize, 8192)
+ XCTAssertEqual(params.prefill.stepSize, 1024)
+ }
+
+ func testInvalidParametersRejectedAndStateReset() async {
+ let service = makeService(MockInferenceGenerator(events: [.chunk("x")]))
+ do {
+ _ = try await service.chatCompletion(messages: [.user("hi")], parameters: ModelParameters(temperature: 9))
+ XCTFail("Expected invalidParameters")
+ } catch MLXServiceError.invalidParameters {
+ // expected
+ } catch {
+ XCTFail("Unexpected error \(error)")
}
+ let busy = await service.isGenerating()
+ XCTAssertFalse(busy, "Busy flag must be cleared after a failed request")
}
- func testFileSystemAccess() throws {
- print("\n=== Testing File System Access ===\n")
-
- let paths = [
- "~/.mlx/models",
- "/Users/testuser/.mlx/models",
- "/Users/testuser/Downloads/MLXCode"
- ]
-
- for path in paths {
- let expanded = (path as NSString).expandingTildeInPath
- print("Testing: \(expanded)")
-
- do {
- let contents = try FileManager.default.contentsOfDirectory(atPath: expanded)
- print(" ✅ Can list directory (\(contents.count) items)")
-
- // Try reading first few items
- for item in contents.prefix(2) {
- let itemPath = (expanded as NSString).appendingPathComponent(item)
- var isDir: ObjCBool = false
- if FileManager.default.fileExists(atPath: itemPath, isDirectory: &isDir) {
- if isDir.boolValue {
- print(" 📁 \(item)")
- } else {
- print(" 📄 \(item)")
- }
- }
- }
- print("")
- } catch {
- print(" ❌ Cannot access: \(error)\n")
- }
+ // MARK: - Stop / cancellation
+
+ func testCancelStopsGenerationAndResetsState() async throws {
+ let mock = MockInferenceGenerator(events: [.chunk("start ")], streamUntilCancelled: true)
+ let service = makeService(mock)
+ let sink = ChunkSink()
+
+ let task = Task {
+ try await service.chatCompletion(messages: [.user("hi")], streamHandler: { sink.append($0) })
}
+
+ let started = await waitUntil { sink.chunks.count >= 3 }
+ XCTAssertTrue(started, "Mock should have streamed a few chunks")
+ let busyWhileRunning = await service.isGenerating()
+ XCTAssertTrue(busyWhileRunning)
+
+ task.cancel()
+ do {
+ _ = try await task.value
+ XCTFail("Cancelled generation should throw CancellationError")
+ } catch is CancellationError {
+ // expected
+ }
+
+ let busyAfterCancel = await service.isGenerating()
+ XCTAssertFalse(busyAfterCancel, "isInferenceRunning must reset after cancellation")
+ let terminated = await waitUntil { mock.terminations >= 1 }
+ XCTAssertTrue(terminated, "The underlying token stream must be terminated, not left running")
+
+ // Chunks stop arriving after cancellation.
+ let countAfterCancel = sink.chunks.count
+ try await Task.sleep(nanoseconds: 50_000_000)
+ XCTAssertEqual(sink.chunks.count, countAfterCancel)
}
-}
-// Make PythonResponse accessible for testing
-private struct PythonResponse: Codable {
- // 'type' is optional: the daemon's model-load success response omits it entirely
- // (see the "Load success response (missing 'type' field)" case below), so requiring
- // it here would reject a legitimate message.
- let type: String?
- let success: Bool?
- let error: String?
- let message: String?
- let token: String?
- let text: String?
- let cached: Bool?
- let path: String?
- let name: String?
- let stage: String?
- let skipped: Bool?
- let repo_id: String?
- let size_bytes: Int?
- let size_gb: Double?
- let quantization: String?
- let converted_to_mlx: Bool?
+ func testNextRequestSucceedsAfterCancel() async throws {
+ let endless = MockInferenceGenerator(events: [], streamUntilCancelled: true)
+ let service = makeService(endless)
+ let task = Task { try await service.chatCompletion(messages: [.user("one")]) }
+ _ = await waitUntil { await service.isGenerating() }
+ task.cancel()
+ _ = try? await task.value
+
+ // Previously the service stayed busy and threw inferenceInProgress here.
+ let second = Task { try await service.chatCompletion(messages: [.user("two")]) }
+ _ = await waitUntil { endless.requests.count == 2 }
+ second.cancel()
+ do {
+ _ = try await second.value
+ } catch is CancellationError {
+ // expected: we cancelled the endless stream; the point is it was accepted
+ } catch {
+ XCTFail("Second request should be accepted after Stop, got \(error)")
+ }
+ XCTAssertEqual(endless.requests.count, 2)
+ }
+
+ func testConcurrentRequestIsRejectedWhileBusy() async throws {
+ let endless = MockInferenceGenerator(events: [], streamUntilCancelled: true)
+ let service = makeService(endless)
+ let first = Task { try await service.chatCompletion(messages: [.user("one")]) }
+ _ = await waitUntil { await service.isGenerating() }
+
+ do {
+ _ = try await service.chatCompletion(messages: [.user("two")])
+ XCTFail("Expected inferenceInProgress")
+ } catch MLXServiceError.inferenceInProgress {
+ // expected
+ }
+ first.cancel()
+ _ = try? await first.value
+ }
+
+ func testChatViewModelStopCancelsServiceAndResetsUI() async throws {
+ let endless = MockInferenceGenerator(events: [.chunk("partial ")], streamUntilCancelled: true)
+ let service = makeService(endless)
+ let vm = ChatViewModel(conversationsDirectory: nil, inference: service)
+ vm.allowLoadBalancing = false
+ vm.isModelLoaded = true
+ vm.currentConversation = Conversation.new(withFirstMessage: "hello")
+
+ let run = Task { await vm.generateResponse() }
+ let streaming = await waitUntil { vm.currentTokenCount >= 3 }
+ XCTAssertTrue(streaming)
+ XCTAssertTrue(vm.isGenerating)
+ XCTAssertNotNil(vm.generationTask)
+
+ vm.stopGeneration()
+ XCTAssertFalse(vm.isGenerating)
+ XCTAssertEqual(vm.statusMessage, "Generation stopped")
+ await run.value
+
+ XCTAssertNil(vm.generationTask)
+ XCTAssertNil(vm.errorMessage, "Stop is not an error")
+ let busy = await service.isGenerating()
+ XCTAssertFalse(busy, "MLXService must be free after Stop")
+ let lastAssistant = vm.currentConversation?.messages.last { $0.role == .assistant }
+ XCTAssertTrue(lastAssistant?.content.hasPrefix("partial") ?? false, "Partial response is kept")
+
+ // The agentic loop must not start another turn after Stop...
+ await vm.generateResponse()
+ XCTAssertEqual(endless.requests.count, 1)
+ // ...but a new user request works immediately.
+ vm.stopRequested = false
+ let second = Task { await vm.generateResponse() }
+ _ = await waitUntil { endless.requests.count == 2 }
+ vm.stopGeneration()
+ await second.value
+ XCTAssertEqual(endless.requests.count, 2)
+ }
+
+ // MARK: - Tool calls
+
+ func testNativeToolCallsMapToToolProtocolIncludingTwoCalls() async throws {
+ let mock = MockInferenceGenerator(events: [
+ .chunk("Let me look."),
+ .toolCall(NativeToolCall(name: "read_file", arguments: ["path": "/tmp/a.swift"])),
+ .toolCall(NativeToolCall(name: "grep", arguments: ["pattern": "TODO", "max_results": 5, "recursive": true])),
+ ])
+ let service = makeService(mock)
+ let sink = ChunkSink()
+ let response = try await service.chatCompletion(
+ messages: [.user("find todos")],
+ tools: [["type": "function", "function": ["name": "read_file"]]],
+ streamHandler: { sink.append($0) }
+ )
+
+ XCTAssertNotNil(mock.requests.first?.tools, "Tool specs must be forwarded to the generator")
+ XCTAssertTrue(response.hasPrefix("Let me look."))
+ XCTAssertEqual(sink.chunks.count, 3, "Rendered tool calls are streamed to the UI too")
+
+ let vm = ChatViewModel(conversationsDirectory: nil, inference: service)
+ XCTAssertTrue(vm.containsToolCalls(response))
+ let calls = vm.extractToolCalls(response)
+ XCTAssertEqual(calls.count, 2, "Both native tool calls must survive mapping")
+
+ let registry = ToolRegistry.shared
+ let first = try XCTUnwrap(registry.parseToolCallJSON(calls[0]))
+ XCTAssertEqual(first.name, "read_file")
+ XCTAssertEqual(first.parameters["path"] as? String, "/tmp/a.swift")
+
+ let second = try XCTUnwrap(registry.parseToolCallJSON(calls[1]))
+ XCTAssertEqual(second.name, "grep")
+ XCTAssertEqual(second.parameters["pattern"] as? String, "TODO")
+ XCTAssertEqual(second.parameters["max_results"] as? String, "5")
+ XCTAssertEqual(second.parameters["recursive"] as? String, "true")
+ }
+
+ func testTextToolProtocolFallbackStillStopsAtClosingTag() async throws {
+ let mock = MockInferenceGenerator(events: [
+ .chunk("\n"),
+ .chunk(#"{"name": "glob", "args": {"pattern": "*.swift"}}"#),
+ .chunk("\n"),
+ .chunk("SHOULD NOT APPEAR"),
+ ])
+ let service = makeService(mock)
+ let response = try await service.chatCompletion(messages: [.user("list")])
+ XCTAssertFalse(response.contains("SHOULD NOT APPEAR"))
+
+ let vm = ChatViewModel(conversationsDirectory: nil, inference: service)
+ let calls = vm.extractToolCalls(response)
+ XCTAssertEqual(calls.count, 1)
+ XCTAssertEqual(ToolRegistry.shared.parseToolCallJSON(calls[0])?.name, "glob")
+ }
+
+ func testEmptyToolListIsNotForwarded() async throws {
+ let mock = MockInferenceGenerator(events: [.chunk("x")])
+ let service = makeService(mock)
+ _ = try await service.chatCompletion(messages: [.user("hi")], tools: [])
+ XCTAssertNil(mock.requests.first?.tools)
+ }
+
+ // MARK: - Optional integration test (real model, opt-in)
+
+ func testIntegrationLoadAndStreamRealModel() async throws {
+ let env = ProcessInfo.processInfo.environment
+ guard env["MLXCODE_INTEGRATION"] == "1" else {
+ throw XCTSkip("Set MLXCODE_INTEGRATION=1 and MLXCODE_MODEL_PATH to run")
+ }
+ guard let path = env["MLXCODE_MODEL_PATH"] else {
+ throw XCTSkip("MLXCODE_MODEL_PATH not set")
+ }
+ let service = MLXService.shared
+ let model = MLXModel(name: "integration", path: path, isDownloaded: true)
+ try await service.loadModel(model)
+ let window = await service.loadedModelContextWindow
+ XCTAssertNotNil(window, "Context window should be read from config.json")
+ let text = try await service.chatCompletion(
+ messages: [.user("Reply with the single word: ok")],
+ parameters: ModelParameters(temperature: 0, maxTokens: 16)
+ )
+ XCTAssertFalse(text.isEmpty)
+ await service.unloadModel()
+ }
}
diff --git a/MLX Code.xcodeproj/project.pbxproj b/MLX Code.xcodeproj/project.pbxproj
index f56b280..22daab0 100644
--- a/MLX Code.xcodeproj/project.pbxproj
+++ b/MLX Code.xcodeproj/project.pbxproj
@@ -11,6 +11,8 @@
AABB02000000000000000002 /* OpenRouterProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = AABB02000000000000000001 /* OpenRouterProvider.swift */; };
AABB03000000000000000002 /* KeychainStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = AABB03000000000000000001 /* KeychainStore.swift */; };
AABB04000000000000000002 /* LLMBalancer.swift in Sources */ = {isa = PBXBuildFile; fileRef = AABB04000000000000000001 /* LLMBalancer.swift */; };
+ AABB06000000000000000002 /* InferenceEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = AABB06000000000000000001 /* InferenceEngine.swift */; };
+ AABB07000000000000000002 /* InferenceEngineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AABB07000000000000000001 /* InferenceEngineTests.swift */; };
AABB05000000000000000002 /* LoadBalancerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AABB05000000000000000001 /* LoadBalancerTests.swift */; };
043C4E7F3FCA17ECD6EB1A51 /* PromptTemplatesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 942A3F3878CD789BDF616A78 /* PromptTemplatesView.swift */; };
0475B2DD296EECD045126C17 /* PrerequisitesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22BF0FCAFA31E5516E7B5EC6 /* PrerequisitesView.swift */; };
@@ -39,7 +41,6 @@
375B23CD55B79FC1C62A5B23 /* MemorySystem.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2F90FA396C5680D706B96B9 /* MemorySystem.swift */; };
3BB85EED3A53FFBB2C040746 /* GitService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01A056387C5D6883F0932FA4 /* GitService.swift */; };
3CEE60DFFD9C4E6F5C07E7A4 /* ModernDesign.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76E1CC6DC5CF4943D05FF452 /* ModernDesign.swift */; };
- 3E0C215F286586A6A3FB0DA1 /* rag_system.py in Resources */ = {isa = PBXBuildFile; fileRef = 36512DB9403F2C61AD03ECF3 /* rag_system.py */; };
406CEA4CA10F45879033D10841AF85C6 /* MessageRowView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7294A0A7EFE8407C852ADC2F428A1167 /* MessageRowView.swift */; };
40A41D7F5CA9B0C7666F953C /* SecurityUtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2C5C8715E9DF0CD60700C51 /* SecurityUtilsTests.swift */; };
4446DD89E33C99BFDB36347F /* LogEntry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 266478D14D864C5C22CB0D15 /* LogEntry.swift */; };
@@ -121,7 +122,6 @@
E9092BA47E894E33897524DF0DDAEF6E /* PythonService.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3FFCCE81A9942AD88F69691662852EC /* PythonService.swift */; };
EA3DD729B1A1D45A5484F4CE /* ThinkingIndicatorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D18CD3C400C3AD1177178192 /* ThinkingIndicatorView.swift */; };
EC5EC65B8FD9A5025E274336 /* HelpView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61B7E2C6F89FEDAA54C278A7 /* HelpView.swift */; };
- ECB016DEEB77015CF0327B53 /* mlx_inference.py in Resources */ = {isa = PBXBuildFile; fileRef = 254D9DD9EEB20CA0D74A5E00 /* mlx_inference.py */; };
ED15B41EF1DB3130F9B71173 /* SharedDataManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C8ECCA430CED7181E9845C7 /* SharedDataManager.swift */; };
ED42A86D2B4D4BCE84B60AA7411AEFCF /* SecurityUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7492C8D46DB847CFABCF1E5B031731B3 /* SecurityUtils.swift */; };
EE5F6A7B8C9D0E1F2A3B4C5D /* ToolApprovalView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF6A7B8C9D0E1F2A3B4C5D6E /* ToolApprovalView.swift */; };
@@ -187,6 +187,8 @@
AABB02000000000000000001 /* OpenRouterProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenRouterProvider.swift; sourceTree = ""; };
AABB03000000000000000001 /* KeychainStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeychainStore.swift; sourceTree = ""; };
AABB04000000000000000001 /* LLMBalancer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LLMBalancer.swift; sourceTree = ""; };
+ AABB06000000000000000001 /* InferenceEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InferenceEngine.swift; sourceTree = ""; };
+ AABB07000000000000000001 /* InferenceEngineTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InferenceEngineTests.swift; sourceTree = ""; };
AABB05000000000000000001 /* LoadBalancerTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LoadBalancerTests.swift; sourceTree = ""; };
0095C89C8F1E4539863AE74D96B702F4 /* MLXService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MLXService.swift; sourceTree = ""; };
01A056387C5D6883F0932FA4 /* GitService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GitService.swift; path = "MLX Code/Services/GitService.swift"; sourceTree = ""; };
@@ -204,7 +206,6 @@
22BF0FCAFA31E5516E7B5EC6 /* PrerequisitesView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrerequisitesView.swift; path = "MLX Code/Views/PrerequisitesView.swift"; sourceTree = ""; };
2366C310D2A09B3F23571AF5 /* ToolParameterParsingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ToolParameterParsingTests.swift; sourceTree = ""; };
2484B300512B2B737C691AF5 /* WidgetDataSync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = WidgetDataSync.swift; sourceTree = ""; };
- 254D9DD9EEB20CA0D74A5E00 /* mlx_inference.py */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.python; name = mlx_inference.py; path = Python/mlx_inference.py; sourceTree = ""; };
266478D14D864C5C22CB0D15 /* LogEntry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogEntry.swift; sourceTree = ""; };
2B297A603876CBEB5317C8DE /* WidgetData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = WidgetData.swift; sourceTree = ""; };
2C8ECCA430CED7181E9845C7 /* SharedDataManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SharedDataManager.swift; sourceTree = ""; };
@@ -212,7 +213,6 @@
2E4D71253A090F8C814711B9 /* MLXServiceTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MLXServiceTests.swift; sourceTree = ""; };
3072558342FD102B940FF3DB /* GettingStarted.md */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = net.daringfireball.markdown; name = GettingStarted.md; path = Help/GettingStarted.md; sourceTree = ""; };
3417A99CC7EF0780993CEAF5 /* NovaAPIServer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NovaAPIServer.swift; path = "MLX Code/Services/NovaAPIServer.swift"; sourceTree = ""; };
- 36512DB9403F2C61AD03ECF3 /* rag_system.py */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.python; name = rag_system.py; path = Python/rag_system.py; sourceTree = ""; };
3BA6541CD08A3BD34802C064 /* HelpView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HelpView.swift; sourceTree = ""; };
41314070C970B31CB3C15767 /* RepetitionDetectorTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = RepetitionDetectorTests.swift; sourceTree = ""; };
416CC836CD6FD1509FE5E7E4 /* Features.md */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = net.daringfireball.markdown; name = Features.md; path = Help/Features.md; sourceTree = ""; };
@@ -234,7 +234,6 @@
64071C1709105BE6194D0570 /* DiffPreviewTool.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DiffPreviewTool.swift; path = Tools/DiffPreviewTool.swift; sourceTree = ""; };
64FB3692EC085C7E8F420ABC /* LogViewerPanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogViewerPanel.swift; sourceTree = ""; };
6610B63C407D26B6EF1E3F90 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = "MLX Code/Services/SessionManager.swift"; sourceTree = ""; };
- 6CC6C830E9E5801EFE2690F2 /* mlx_daemon.py */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.python; name = mlx_daemon.py; path = Python/mlx_daemon.py; sourceTree = ""; };
6FD0BB3BC560F8D474C00FAC /* Troubleshooting.md */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = net.daringfireball.markdown; name = Troubleshooting.md; path = Help/Troubleshooting.md; sourceTree = ""; };
6FF8710DDF681985366DCED2 /* MessageTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MessageTests.swift; sourceTree = ""; };
7047E47FAE5738E4C3742DD4 /* BuildErrorParserTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = BuildErrorParserTests.swift; sourceTree = ""; };
@@ -320,7 +319,6 @@
FD5FD20620CC8E07FFA1428A /* BashTool.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BashTool.swift; path = Tools/BashTool.swift; sourceTree = ""; };
FDF863EF632E990FA28CCD29 /* MLX_Code_Widget.entitlements */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.entitlements; path = MLX_Code_Widget.entitlements; sourceTree = ""; };
FE07B6436E0D401DBA11F15F8CDA7B09 /* Message.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Message.swift; sourceTree = ""; };
- FEDDB0ED1A61C0892F6EDF1B /* huggingface_downloader.py */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.python; name = huggingface_downloader.py; path = Python/huggingface_downloader.py; sourceTree = ""; };
FF6A7B8C9D0E1F2A3B4C5D6E /* ToolApprovalView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToolApprovalView.swift; path = "MLX Code/Views/ToolApprovalView.swift"; sourceTree = SOURCE_ROOT; };
FF7455C7A2CE4EAA997C11353C876821 /* SecureLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecureLogger.swift; sourceTree = ""; };
FF9E24703A8FCDC2C9B4B0BA /* FileOperationsTool.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FileOperationsTool.swift; path = Tools/FileOperationsTool.swift; sourceTree = ""; };
@@ -387,16 +385,6 @@
path = Resources;
sourceTree = "";
};
- 512191759EAFD5368C431D56 /* Python */ = {
- isa = PBXGroup;
- children = (
- FEDDB0ED1A61C0892F6EDF1B /* huggingface_downloader.py */,
- 254D9DD9EEB20CA0D74A5E00 /* mlx_inference.py */,
- 36512DB9403F2C61AD03ECF3 /* rag_system.py */,
- );
- name = Python;
- sourceTree = SOURCE_ROOT;
- };
6B35EA916216071CF5CC28C7 /* MLX Code Widget */ = {
isa = PBXGroup;
children = (
@@ -501,6 +489,7 @@
AABB02000000000000000001 /* OpenRouterProvider.swift */,
AABB03000000000000000001 /* KeychainStore.swift */,
AABB04000000000000000001 /* LLMBalancer.swift */,
+ AABB06000000000000000001 /* InferenceEngine.swift */,
0095C89C8F1E4539863AE74D96B702F4 /* MLXService.swift */,
BB001CDEF123456789ABCDE000022222 /* XcodeActionHandler.swift */,
2113E8E02AFC404C917BDECE45AD0C31 /* XcodeService.swift */,
@@ -538,6 +527,7 @@
isa = PBXGroup;
children = (
AABB05000000000000000001 /* LoadBalancerTests.swift */,
+ AABB07000000000000000001 /* InferenceEngineTests.swift */,
1B364AD048BC9F2567D45CC7 /* AppSettingsTests.swift */,
8C37CB4BC161157E297B1C70 /* CommandValidatorTests.swift */,
F975089CB3BD79BDBC9F5CD3 /* ContextManagerTests.swift */,
@@ -650,8 +640,6 @@
E2EF41EA1A31A3E9484FC8C3 /* Views */,
6F0229DF0B6AF4821D6BC3FE /* Services */,
7E5FCD73CEE595B2B243ACB7 /* Utilities */,
- 512191759EAFD5368C431D56 /* Python */,
- 6CC6C830E9E5801EFE2690F2 /* mlx_daemon.py */,
0E5675694C64139E1C905003 /* CodeBlockView.swift */,
564D43E7BF13C063A567706B /* EnhancedMessageView.swift */,
86DA95C55CF31CAA085E0CD4 /* CodebaseIndexer.swift */,
@@ -748,6 +736,9 @@
B2CDB41D8A69A6A26D70BBE7 /* MLXNN */,
B38BA712F974D727652E810F /* MLXLLM */,
5BA7AB349C44E6745850757A /* MLXLMCommon */,
+ A1F00000000000000000B001 /* MLXHuggingFace */,
+ A1F00000000000000000B002 /* HuggingFace */,
+ A1F00000000000000000B003 /* Tokenizers */,
);
productName = "MLX Code";
productReference = A618C93267C54CBEA8B15E4321B53726 /* MLX Code.app */;
@@ -803,6 +794,8 @@
packageReferences = (
2A5EF90852B06B563B319AD6 /* XCRemoteSwiftPackageReference "mlx-swift" */,
588B05B0E11878C953EE0334 /* XCRemoteSwiftPackageReference "mlx-swift-lm" */,
+ A1F00000000000000000A001 /* XCRemoteSwiftPackageReference "swift-huggingface" */,
+ A1F00000000000000000A002 /* XCRemoteSwiftPackageReference "swift-transformers" */,
);
productRefGroup = DBD46EBB13194FBBA1D0AADBCBBFE22B /* Products */;
projectDirPath = "";
@@ -829,8 +822,6 @@
buildActionMask = 2147483647;
files = (
C95840B1287C494587897311FF59BBC8 /* Assets.xcassets in Resources */,
- ECB016DEEB77015CF0327B53 /* mlx_inference.py in Resources */,
- 3E0C215F286586A6A3FB0DA1 /* rag_system.py in Resources */,
EEE1340E1501B4ACBEFF3472 /* GettingStarted.md in Resources */,
BC51340E6DC042F101EC852C /* Features.md in Resources */,
7A0F8C83531AC0524598D2AF /* KeyboardShortcuts.md in Resources */,
@@ -875,6 +866,7 @@
buildActionMask = 2147483647;
files = (
AABB05000000000000000002 /* LoadBalancerTests.swift in Sources */,
+ AABB07000000000000000002 /* InferenceEngineTests.swift in Sources */,
678CCB7627496E9731B7D734 /* AppSettingsTests.swift in Sources */,
AA74C582F22930DF98A0CB7B /* CommandValidatorTests.swift in Sources */,
2CAAE35717EEF0F0BB6889D1 /* ContextManagerTests.swift in Sources */,
@@ -919,6 +911,7 @@
AABB02000000000000000002 /* OpenRouterProvider.swift in Sources */,
AABB03000000000000000002 /* KeychainStore.swift in Sources */,
AABB04000000000000000002 /* LLMBalancer.swift in Sources */,
+ AABB06000000000000000002 /* InferenceEngine.swift in Sources */,
E2FCF04057F99E48BF46CCF3 /* CommandValidator.swift in Sources */,
A0013163E03EA758655F244E /* ModelSecurityValidator.swift in Sources */,
4A14B6380E9E4A44949059C9DE2D703A /* MLXCodeApp.swift in Sources */,
@@ -1056,7 +1049,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 8;
+ CURRENT_PROJECT_VERSION = 9;
DEVELOPMENT_ASSET_PATHS = "";
DEVELOPMENT_TEAM = QRRCB8HB3W;
ENABLE_HARDENED_RUNTIME = YES;
@@ -1071,7 +1064,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 6.3.0;
+ MARKETING_VERSION = 6.4.0;
PRODUCT_BUNDLE_IDENTIFIER = com.local.mlxcode;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -1161,7 +1154,7 @@
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
CODE_SIGN_ENTITLEMENTS = "MLX Code Widget/MLX_Code_Widget.entitlements";
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 8;
+ CURRENT_PROJECT_VERSION = 9;
DEVELOPMENT_TEAM = QRRCB8HB3W;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "MLX Code Widget/Info.plist";
@@ -1171,7 +1164,7 @@
"@executable_path/../../../../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 6.3.0;
+ MARKETING_VERSION = 6.4.0;
PRODUCT_BUNDLE_IDENTIFIER = com.local.mlxcode.widget;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
@@ -1251,7 +1244,7 @@
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
CODE_SIGN_ENTITLEMENTS = "MLX Code Widget/MLX_Code_Widget.entitlements";
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 8;
+ CURRENT_PROJECT_VERSION = 9;
DEVELOPMENT_TEAM = QRRCB8HB3W;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "MLX Code Widget/Info.plist";
@@ -1261,7 +1254,7 @@
"@executable_path/../../../../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 6.3.0;
+ MARKETING_VERSION = 6.4.0;
PRODUCT_BUNDLE_IDENTIFIER = com.local.mlxcode.widget;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
@@ -1279,7 +1272,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 1;
+ CURRENT_PROJECT_VERSION = 2;
DEVELOPMENT_TEAM = QRRCB8HB3W;
ENABLE_APP_SANDBOX = YES;
ENABLE_HARDENED_RUNTIME = YES;
@@ -1293,7 +1286,7 @@
"@executable_path/../../../../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 26.2;
- MARKETING_VERSION = 1.0;
+ MARKETING_VERSION = 1.1;
PRODUCT_BUNDLE_IDENTIFIER = com.local.mlxcode.xcodeeditor;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
@@ -1314,7 +1307,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 1;
+ CURRENT_PROJECT_VERSION = 2;
DEVELOPMENT_TEAM = QRRCB8HB3W;
ENABLE_APP_SANDBOX = YES;
ENABLE_HARDENED_RUNTIME = YES;
@@ -1328,7 +1321,7 @@
"@executable_path/../../../../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 26.2;
- MARKETING_VERSION = 1.0;
+ MARKETING_VERSION = 1.1;
PRODUCT_BUNDLE_IDENTIFIER = com.local.mlxcode.xcodeeditor;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
@@ -1351,7 +1344,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 8;
+ CURRENT_PROJECT_VERSION = 9;
DEVELOPMENT_ASSET_PATHS = "";
DEVELOPMENT_TEAM = QRRCB8HB3W;
ENABLE_HARDENED_RUNTIME = YES;
@@ -1366,7 +1359,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 6.3.0;
+ MARKETING_VERSION = 6.4.0;
PRODUCT_BUNDLE_IDENTIFIER = com.local.mlxcode;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -1431,7 +1424,7 @@
repositoryURL = "https://github.com/ml-explore/mlx-swift";
requirement = {
kind = upToNextMinorVersion;
- minimumVersion = 0.30.3;
+ minimumVersion = 0.32.3;
};
};
588B05B0E11878C953EE0334 /* XCRemoteSwiftPackageReference "mlx-swift-lm" */ = {
@@ -1439,7 +1432,23 @@
repositoryURL = "https://github.com/ml-explore/mlx-swift-lm";
requirement = {
kind = upToNextMinorVersion;
- minimumVersion = 2.30.3;
+ minimumVersion = 3.32.3;
+ };
+ };
+ A1F00000000000000000A001 /* XCRemoteSwiftPackageReference "swift-huggingface" */ = {
+ isa = XCRemoteSwiftPackageReference;
+ repositoryURL = "https://github.com/huggingface/swift-huggingface";
+ requirement = {
+ kind = upToNextMinorVersion;
+ minimumVersion = 0.13.0;
+ };
+ };
+ A1F00000000000000000A002 /* XCRemoteSwiftPackageReference "swift-transformers" */ = {
+ isa = XCRemoteSwiftPackageReference;
+ repositoryURL = "https://github.com/huggingface/swift-transformers";
+ requirement = {
+ kind = upToNextMinorVersion;
+ minimumVersion = 1.4.0;
};
};
/* End XCRemoteSwiftPackageReference section */
@@ -1465,6 +1474,21 @@
package = 2A5EF90852B06B563B319AD6 /* XCRemoteSwiftPackageReference "mlx-swift" */;
productName = MLX;
};
+ A1F00000000000000000B001 /* MLXHuggingFace */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = 588B05B0E11878C953EE0334 /* XCRemoteSwiftPackageReference "mlx-swift-lm" */;
+ productName = MLXHuggingFace;
+ };
+ A1F00000000000000000B002 /* HuggingFace */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = A1F00000000000000000A001 /* XCRemoteSwiftPackageReference "swift-huggingface" */;
+ productName = HuggingFace;
+ };
+ A1F00000000000000000B003 /* Tokenizers */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = A1F00000000000000000A002 /* XCRemoteSwiftPackageReference "swift-transformers" */;
+ productName = Tokenizers;
+ };
/* End XCSwiftPackageProductDependency section */
};
rootObject = F9BDA8E4425A4DF7A39133B70A11CD1F /* Project object */;
diff --git a/MLX Code.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/MLX Code.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
new file mode 100644
index 0000000..38f1123
--- /dev/null
+++ b/MLX Code.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -0,0 +1,114 @@
+{
+ "originHash" : "46d8193fe91ecec1a58adc572540d20c94e368d77b3556cc81870f008c4371fe",
+ "pins" : [
+ {
+ "identity" : "eventsource",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/mattt/EventSource.git",
+ "state" : {
+ "revision" : "bb4b61273b5a976bb571859c17f903ebc3439df1",
+ "version" : "1.6.0"
+ }
+ },
+ {
+ "identity" : "mlx-swift",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/ml-explore/mlx-swift",
+ "state" : {
+ "revision" : "19601207e9a0de51e03ee6ec0c3c5f3784275075",
+ "version" : "0.32.3"
+ }
+ },
+ {
+ "identity" : "mlx-swift-lm",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/ml-explore/mlx-swift-lm",
+ "state" : {
+ "revision" : "3b339ad6e3b3f44c8121ecff5131c7fd55e075e6",
+ "version" : "3.32.3"
+ }
+ },
+ {
+ "identity" : "swift-asn1",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-asn1.git",
+ "state" : {
+ "revision" : "917b472dbe53ba699cbb0495f9a95a084bc6364d",
+ "version" : "1.7.4"
+ }
+ },
+ {
+ "identity" : "swift-collections",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-collections.git",
+ "state" : {
+ "revision" : "f96b909e1a9e469620bc5037c1e24e00153f376f",
+ "version" : "1.7.5"
+ }
+ },
+ {
+ "identity" : "swift-crypto",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-crypto.git",
+ "state" : {
+ "revision" : "da9d28d69ebe3894b18376c8f2395c2f37b8448f",
+ "version" : "4.5.2"
+ }
+ },
+ {
+ "identity" : "swift-huggingface",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/huggingface/swift-huggingface",
+ "state" : {
+ "revision" : "f0a0cb43cb1b402d2bbf6fb10d8981328c449c48",
+ "version" : "0.13.0"
+ }
+ },
+ {
+ "identity" : "swift-jinja",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/huggingface/swift-jinja.git",
+ "state" : {
+ "revision" : "a091d6ae559ee97e904a0f3c2890b21949d0306f",
+ "version" : "3.0.0"
+ }
+ },
+ {
+ "identity" : "swift-numerics",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-numerics",
+ "state" : {
+ "revision" : "0c0290ff6b24942dadb83a929ffaaa1481df04a2",
+ "version" : "1.1.1"
+ }
+ },
+ {
+ "identity" : "swift-syntax",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/swiftlang/swift-syntax.git",
+ "state" : {
+ "revision" : "79e4b74a295b6eb74a8b585e3a39d29e70c1dbd1",
+ "version" : "603.0.2"
+ }
+ },
+ {
+ "identity" : "swift-transformers",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/huggingface/swift-transformers",
+ "state" : {
+ "revision" : "402a8a1105f52038b0949d9596981fc9e32bed17",
+ "version" : "1.4.0"
+ }
+ },
+ {
+ "identity" : "yyjson",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/ibireme/yyjson.git",
+ "state" : {
+ "revision" : "6447536015f3d600f3d65323b10976103b337ca7",
+ "version" : "0.13.0"
+ }
+ }
+ ],
+ "version" : 3
+}
diff --git a/MLX Code/Models/AppSettings.swift b/MLX Code/Models/AppSettings.swift
index 3a66a66..d3c41e9 100644
--- a/MLX Code/Models/AppSettings.swift
+++ b/MLX Code/Models/AppSettings.swift
@@ -37,6 +37,20 @@ class AppSettings: ObservableObject {
/// Top-k sampling parameter
@Published var topK: Int = 40
+ /// KV-cache quantization bits: 0 (none), 8 or 4. Lower = less memory, slight quality cost.
+ @Published var kvCacheBits: Int = KVCacheSettings.default.bits
+
+ /// Maximum KV-cache size in tokens (rotating cache). 0 = unlimited.
+ @Published var maxKVSize: Int = KVCacheSettings.default.maxSize
+
+ /// Prompt prefill step size in tokens. 0 = model default.
+ @Published var prefillStepSize: Int = KVCacheSettings.default.prefillStepSize
+
+ /// KV-cache settings snapshot passed to MLXService for every generation.
+ var kvCacheSettings: KVCacheSettings {
+ KVCacheSettings(bits: kvCacheBits, maxSize: maxKVSize, prefillStepSize: prefillStepSize).sanitized()
+ }
+
/// Path to Python executable
@Published var pythonPath: String = "/usr/bin/python3"
@@ -136,6 +150,9 @@ class AppSettings: ObservableObject {
static let maxTokens = "maxTokens"
static let topP = "topP"
static let topK = "topK"
+ static let kvCacheBits = "kvCacheBits"
+ static let maxKVSize = "maxKVSize"
+ static let prefillStepSize = "prefillStepSize"
static let pythonPath = "pythonPath"
static let theme = "theme"
static let fontSize = "fontSize"
@@ -257,6 +274,18 @@ class AppSettings: ObservableObject {
topK = min(max(loadedTopK, 1), 1000)
}
+ // Load KV-cache settings (sanitized: unknown values fall back to defaults)
+ if userDefaults.object(forKey: Keys.kvCacheBits) != nil {
+ let stored = KVCacheSettings(
+ bits: userDefaults.integer(forKey: Keys.kvCacheBits),
+ maxSize: userDefaults.integer(forKey: Keys.maxKVSize),
+ prefillStepSize: userDefaults.integer(forKey: Keys.prefillStepSize)
+ ).sanitized()
+ kvCacheBits = stored.bits
+ maxKVSize = stored.maxSize
+ prefillStepSize = stored.prefillStepSize
+ }
+
// Load python path with validation
if let path = userDefaults.string(forKey: Keys.pythonPath), !path.isEmpty {
pythonPath = path
@@ -380,6 +409,9 @@ class AppSettings: ObservableObject {
userDefaults.set(maxTokens, forKey: Keys.maxTokens)
userDefaults.set(topP, forKey: Keys.topP)
userDefaults.set(topK, forKey: Keys.topK)
+ userDefaults.set(kvCacheBits, forKey: Keys.kvCacheBits)
+ userDefaults.set(maxKVSize, forKey: Keys.maxKVSize)
+ userDefaults.set(prefillStepSize, forKey: Keys.prefillStepSize)
userDefaults.set(pythonPath, forKey: Keys.pythonPath)
userDefaults.set(theme.rawValue, forKey: Keys.theme)
userDefaults.set(fontSize, forKey: Keys.fontSize)
@@ -429,6 +461,9 @@ class AppSettings: ObservableObject {
maxTokens = 2048
topP = 0.9
topK = 40
+ kvCacheBits = KVCacheSettings.default.bits
+ maxKVSize = KVCacheSettings.default.maxSize
+ prefillStepSize = KVCacheSettings.default.prefillStepSize
pythonPath = "/usr/bin/python3"
theme = .system
fontSize = 14.0
@@ -590,6 +625,11 @@ class AppSettings: ObservableObject {
.sink { [weak self] _ in self?.saveSettings() }
.store(in: &cancellables)
+ Publishers.Merge3($kvCacheBits.dropFirst(), $maxKVSize.dropFirst(), $prefillStepSize.dropFirst())
+ .debounce(for: .seconds(1.0), scheduler: DispatchQueue.main)
+ .sink { [weak self] _ in self?.saveSettings() }
+ .store(in: &cancellables)
+
$pythonPath
.dropFirst()
.debounce(for: .seconds(1.0), scheduler: DispatchQueue.main)
diff --git a/MLX Code/Models/MLXModel.swift b/MLX Code/Models/MLXModel.swift
index f70d38e..8396c80 100644
--- a/MLX Code/Models/MLXModel.swift
+++ b/MLX Code/Models/MLXModel.swift
@@ -73,6 +73,13 @@ struct MLXModel: Identifiable, Codable, Equatable, Hashable {
/// Model inference parameters
struct ModelParameters: Codable, Equatable, Hashable {
+ /// Repetition penalty shipped as the default before v6.4 (too aggressive: it
+ /// degraded code output). Persisted values equal to it are migrated on decode.
+ static let legacyDefaultRepetitionPenalty = 1.8
+
+ /// Current default repetition penalty
+ static let defaultRepetitionPenalty = 1.1
+
/// Temperature for sampling (0.0 to 2.0)
var temperature: Double
@@ -85,6 +92,9 @@ struct ModelParameters: Codable, Equatable, Hashable {
/// Top-k sampling parameter
var topK: Int
+ /// Min-p sampling threshold relative to the most likely token (0 disables)
+ var minP: Double
+
/// Repetition penalty
var repetitionPenalty: Double
@@ -97,23 +107,45 @@ struct ModelParameters: Codable, Equatable, Hashable {
/// - maxTokens: Maximum tokens to generate (default: 2048)
/// - topP: Top-p sampling (default: 0.9)
/// - topK: Top-k sampling (default: 40)
- /// - repetitionPenalty: Repetition penalty (default: 1.2, higher = less repetition)
- /// - repetitionContextSize: Context size for repetition (default: 64, look back farther)
+ /// - minP: Min-p sampling (default: 0.0, disabled)
+ /// - repetitionPenalty: Repetition penalty (default: 1.1)
+ /// - repetitionContextSize: Context size for repetition (default: 256)
init(
temperature: Double = 0.2,
maxTokens: Int = 2048, // Restored: chat templates + RepetitionDetector prevent loops
topP: Double = 0.9,
topK: Int = 40,
- repetitionPenalty: Double = 1.8, // Keep high to penalize repetition
- repetitionContextSize: Int = 256 // Keep wide lookback for repetition detection
+ minP: Double = 0.0,
+ repetitionPenalty: Double = ModelParameters.defaultRepetitionPenalty,
+ repetitionContextSize: Int = 256
) {
self.temperature = temperature
self.maxTokens = maxTokens
self.topP = topP
self.topK = topK
+ self.minP = minP
self.repetitionPenalty = repetitionPenalty
self.repetitionContextSize = repetitionContextSize
}
+
+ private enum CodingKeys: String, CodingKey {
+ case temperature, maxTokens, topP, topK, minP, repetitionPenalty, repetitionContextSize
+ }
+
+ /// Tolerant decoder: fields added later (e.g. `minP`) default when missing, and the
+ /// legacy 1.8 repetition-penalty default is migrated to the current default.
+ init(from decoder: Decoder) throws {
+ let defaults = ModelParameters()
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ temperature = try c.decodeIfPresent(Double.self, forKey: .temperature) ?? defaults.temperature
+ maxTokens = try c.decodeIfPresent(Int.self, forKey: .maxTokens) ?? defaults.maxTokens
+ topP = try c.decodeIfPresent(Double.self, forKey: .topP) ?? defaults.topP
+ topK = try c.decodeIfPresent(Int.self, forKey: .topK) ?? defaults.topK
+ minP = try c.decodeIfPresent(Double.self, forKey: .minP) ?? defaults.minP
+ let penalty = try c.decodeIfPresent(Double.self, forKey: .repetitionPenalty) ?? defaults.repetitionPenalty
+ repetitionPenalty = penalty == Self.legacyDefaultRepetitionPenalty ? Self.defaultRepetitionPenalty : penalty
+ repetitionContextSize = try c.decodeIfPresent(Int.self, forKey: .repetitionContextSize) ?? defaults.repetitionContextSize
+ }
}
// MARK: - Validation
@@ -142,6 +174,11 @@ extension ModelParameters {
return false
}
+ // Min-p should be between 0.0 and 1.0
+ guard minP >= 0.0 && minP <= 1.0 else {
+ return false
+ }
+
// Repetition penalty should be positive
guard repetitionPenalty > 0.0 && repetitionPenalty <= 2.0 else {
return false
@@ -208,21 +245,25 @@ extension MLXModel {
extension MLXModel {
/// Creates a default model configuration
/// - Parameter basePath: Base directory for models (uses smart default if not provided)
- /// - Returns: A new MLXModel with default settings (Qwen 2.5 7B — best for coding)
+ /// - Returns: A new MLXModel with default settings (Qwen3.5 9B — fast, strong coder, native tool calling)
static func `default`(basePath: String? = nil) -> MLXModel {
let modelBasePath = basePath ?? AppSettings.detectWritableModelsPath()
return MLXModel(
- name: "Qwen 2.5 7B",
- path: "\(modelBasePath)/qwen-2.5-7b",
+ name: "Qwen3.5 9B",
+ path: "\(modelBasePath)/qwen3.5-9b",
parameters: ModelParameters(),
isDownloaded: false,
- huggingFaceId: "mlx-community/Qwen2.5-7B-Instruct-4bit",
- description: "Alibaba's Qwen 2.5 7B — Best for coding tasks. ~4GB",
- contextWindowSize: 32768
+ huggingFaceId: "mlx-community/Qwen3.5-9B-4bit",
+ description: "Alibaba's Qwen3.5 9B — fast all-rounder with native tool calling. ~5GB",
+ contextWindowSize: 262144
)
}
- /// Creates model configurations for common MLX models
+ /// Creates model configurations for common MLX models.
+ ///
+ /// Every entry is an `mlx-community` quantized repo whose `model_type` is supported by
+ /// mlx-swift-lm 3.32 (verified against huggingface.co and LLMModelFactory, Nov 2026).
+ /// Context sizes come from each repo's config.json (`text_config` where nested).
/// - Parameter basePath: Base directory for models (uses smart default if not provided)
/// - Returns: Array of pre-configured MLXModel instances
static func commonModels(basePath: String? = nil) -> [MLXModel] {
@@ -231,97 +272,87 @@ extension MLXModel {
return [
// RECOMMENDED: Best Quality/Performance Balance
MLXModel(
- name: "Qwen 2.5 7B ⭐ RECOMMENDED",
- path: "\(modelBasePath)/qwen-2.5-7b",
+ name: "Qwen3.5 9B ⭐ RECOMMENDED",
+ path: "\(modelBasePath)/qwen3.5-9b",
parameters: ModelParameters(),
isDownloaded: false,
- huggingFaceId: "mlx-community/Qwen2.5-7B-Instruct-4bit",
- description: "Alibaba's Qwen 2.5 - Excellent quality, good instruction following. Best for coding. ~4GB",
- contextWindowSize: 32768
+ huggingFaceId: "mlx-community/Qwen3.5-9B-4bit",
+ description: "Qwen3.5 9B - Fast, strong at code, native tool calling. 16GB+ Macs. ~5GB",
+ contextWindowSize: 262144
),
+ // Coding specialists
MLXModel(
- name: "Mistral 7B v0.3 ⭐ POPULAR",
- path: "\(modelBasePath)/mistral-7b",
+ name: "Qwen3-Coder 30B-A3B (MoE) ⭐ CODING",
+ path: "\(modelBasePath)/qwen3-coder-30b-a3b",
parameters: ModelParameters(),
isDownloaded: false,
- huggingFaceId: "mlx-community/Mistral-7B-Instruct-v0.3-4bit",
- description: "Mistral AI's 7B - Very popular, versatile, good for code. ~4GB",
- contextWindowSize: 32768
- ),
-
- // Larger Models (Better Quality)
- MLXModel(
- name: "Qwen 2.5 14B (Best Quality)",
- path: "\(modelBasePath)/qwen-2.5-14b",
- parameters: ModelParameters(),
- isDownloaded: false,
- huggingFaceId: "mlx-community/Qwen2.5-14B-Instruct-4bit",
- description: "Qwen 2.5 14B - Best quality, slower but excellent results. ~8GB",
- contextWindowSize: 32768
+ huggingFaceId: "mlx-community/Qwen3-Coder-30B-A3B-Instruct-4bit",
+ description: "Qwen3-Coder MoE (3B active) - Agentic coding model, fast for its size. 32GB+ Macs. ~17GB",
+ contextWindowSize: 262144
),
MLXModel(
- name: "Llama 3.1 8B",
- path: "\(modelBasePath)/llama-3.1-8b",
+ name: "Devstral Small 2 24B",
+ path: "\(modelBasePath)/devstral-small-2-24b",
parameters: ModelParameters(),
isDownloaded: false,
- huggingFaceId: "mlx-community/Meta-Llama-3.1-8B-Instruct-4bit",
- description: "Meta's Llama 3.1 8B - Solid performance, good for general use. ~5GB",
- contextWindowSize: 131072
+ huggingFaceId: "mlx-community/Devstral-Small-2-24B-Instruct-2512-4bit",
+ description: "Mistral's Devstral Small 2 - Software-engineering agent model. 32GB+ Macs. ~14GB",
+ contextWindowSize: 393216
),
- // Specialized Models
+ // Larger general models (better quality)
MLXModel(
- name: "DeepSeek Coder 6.7B",
- path: "\(modelBasePath)/deepseek-coder",
+ name: "Qwen3.6 35B-A3B (MoE)",
+ path: "\(modelBasePath)/qwen3.6-35b-a3b",
parameters: ModelParameters(),
isDownloaded: false,
- huggingFaceId: "mlx-community/deepseek-coder-6.7b-instruct",
- description: "DeepSeek Coder - Specialized for code, excellent for programming tasks. ~4GB",
- contextWindowSize: 16384
+ huggingFaceId: "mlx-community/Qwen3.6-35B-A3B-4bit",
+ description: "Qwen3.6 MoE (3B active) - High quality with MoE speed. 32GB+ Macs. ~20GB",
+ contextWindowSize: 262144
),
MLXModel(
- name: "CodeLlama 7B",
- path: "\(modelBasePath)/codellama-7b",
+ name: "Qwen3.6 27B (Best Quality)",
+ path: "\(modelBasePath)/qwen3.6-27b",
parameters: ModelParameters(),
isDownloaded: false,
- huggingFaceId: "mlx-community/CodeLlama-7b-Instruct-hf-4bit-MLX",
- description: "Meta's CodeLlama - Trained specifically for code generation. ~4GB",
- contextWindowSize: 16384
+ huggingFaceId: "mlx-community/Qwen3.6-27B-4bit",
+ description: "Qwen3.6 27B dense - Best quality, slower. 32GB+ Macs. ~16GB",
+ contextWindowSize: 262144
),
- // Compact Models (Faster)
+ // Compact models (faster)
MLXModel(
- name: "Phi-3.5 Mini (Fast)",
- path: "\(modelBasePath)/phi-3.5-mini",
+ name: "Gemma 4 E4B",
+ path: "\(modelBasePath)/gemma-4-e4b",
parameters: ModelParameters(),
isDownloaded: false,
- huggingFaceId: "mlx-community/Phi-3.5-mini-instruct-4bit",
- description: "Microsoft's Phi-3.5 - Small but capable, very fast. ~2GB",
- contextWindowSize: 4096
+ huggingFaceId: "mlx-community/gemma-4-e4b-it-4bit",
+ description: "Google's Gemma 4 E4B - Efficient on-device model, good instruction following. ~4GB",
+ contextWindowSize: 131072
),
MLXModel(
- name: "Gemma 2 9B",
- path: "\(modelBasePath)/gemma-2-9b",
+ name: "Qwen3.5 2B (Fast)",
+ path: "\(modelBasePath)/qwen3.5-2b",
parameters: ModelParameters(),
isDownloaded: false,
- huggingFaceId: "mlx-community/gemma-2-9b-it-4bit",
- description: "Google's Gemma 2 9B - Excellent quality, good instruction following. ~5GB",
- contextWindowSize: 8192
+ huggingFaceId: "mlx-community/Qwen3.5-2B-4bit",
+ description: "Qwen3.5 2B - Very fast, low memory. Good for quick edits on 8GB Macs. ~1.5GB",
+ contextWindowSize: 262144
),
- // Keep original for backwards compatibility
+ // Kept for existing installs
MLXModel(
- name: "Llama 3.2 3B (Small - NOT RECOMMENDED)",
- path: "\(modelBasePath)/llama-3.2-3b",
+ name: "Qwen 2.5 7B (Legacy)",
+ path: "\(modelBasePath)/qwen-2.5-7b",
parameters: ModelParameters(),
isDownloaded: false,
- huggingFaceId: "mlx-community/Llama-3.2-3B-Instruct-4bit",
- description: "Meta's Llama 3.2 3B - Too small, causes loops. Use Qwen or Mistral instead. ~2GB",
- contextWindowSize: 8192
+ huggingFaceId: "mlx-community/Qwen2.5-7B-Instruct-4bit",
+ description: "Qwen 2.5 7B - Previous default, kept for existing installs. ~4GB",
+ contextWindowSize: 32768
)
]
}
diff --git a/MLX Code/Services/InferenceEngine.swift b/MLX Code/Services/InferenceEngine.swift
new file mode 100644
index 0000000..6ebd3b9
--- /dev/null
+++ b/MLX Code/Services/InferenceEngine.swift
@@ -0,0 +1,282 @@
+//
+// InferenceEngine.swift
+// MLX Code
+//
+// Created on 2026-11-06.
+// Small, testable seam between MLXService and mlx-swift-lm 3.x.
+//
+// - `InferenceGenerator` abstracts "turn a request into a stream of events" so the
+// service's state machine (busy flag, cancellation, tool-call mapping) can be
+// unit-tested with a mock and no model download.
+// - `GenerationParameterMapper` maps app-level ModelParameters + KV-cache settings
+// into mlx-swift-lm's `GenerateParameters`.
+// - `ToolSpecBuilder` turns the app's ToolRegistry tools into native `ToolSpec`s.
+// - `NativeToolCallFormatter` renders native `Generation.toolCall` events into the
+// existing `{...}` text protocol so the approval/execution flow is reused.
+// - `ModelConfigInspector` reads the context window from config.json (top level or
+// nested `text_config`).
+//
+
+import Foundation
+import MLXLMCommon
+
+// MARK: - Events and Requests
+
+/// A tool call emitted natively by the model (parsed by mlx-swift-lm).
+struct NativeToolCall: @unchecked Sendable {
+ /// Function name
+ let name: String
+ /// Decoded JSON arguments (String, Int, Double, Bool, NSNull, arrays, dictionaries)
+ let arguments: [String: Any]
+
+ init(name: String, arguments: [String: Any]) {
+ self.name = name
+ self.arguments = arguments
+ }
+
+ /// Bridges an mlx-swift-lm tool call.
+ init(_ call: ToolCall) {
+ self.name = call.function.name
+ self.arguments = call.function.arguments.mapValues { $0.anyValue }
+ }
+}
+
+/// Model-agnostic generation event.
+enum InferenceEvent: @unchecked Sendable {
+ /// Streamed text chunk
+ case chunk(String)
+ /// Natively parsed tool call
+ case toolCall(NativeToolCall)
+}
+
+/// What to feed the model.
+enum InferencePrompt: Sendable, Equatable {
+ /// Raw text prompt
+ case text(String)
+ /// Structured chat messages (`role` / `content`) rendered with the model's chat template
+ case messages([[String: String]])
+}
+
+/// A single generation request.
+struct InferenceRequest: Sendable {
+ var prompt: InferencePrompt
+ /// Flat prompt used when the model's Jinja chat template cannot be applied
+ var fallbackPrompt: String?
+ /// Native tool specifications (nil = no native tool calling)
+ var tools: [ToolSpec]?
+ /// Fully mapped generation parameters
+ var parameters: GenerateParameters
+}
+
+/// Anything that can turn a request into a stream of events.
+/// Production: `MLXContainerGenerator`. Tests: a mock.
+protocol InferenceGenerator: Sendable {
+ func generate(_ request: InferenceRequest) async throws -> AsyncStream
+}
+
+// MARK: - Production Generator
+
+/// Wraps an mlx-swift-lm `ModelContainer`.
+struct MLXContainerGenerator: InferenceGenerator {
+ let container: ModelContainer
+
+ func generate(_ request: InferenceRequest) async throws -> AsyncStream {
+ let lmInput: LMInput
+ switch request.prompt {
+ case .text(let text):
+ lmInput = try await container.prepare(input: UserInput(prompt: .text(text), tools: request.tools))
+ case .messages(let messages):
+ let dicts: [[String: any Sendable]] = messages.map { $0 as [String: any Sendable] }
+ do {
+ lmInput = try await container.prepare(input: UserInput(prompt: .messages(dicts), tools: request.tools))
+ } catch {
+ // Some chat templates use Jinja features swift-jinja doesn't support yet.
+ guard let fallback = request.fallbackPrompt else { throw error }
+ await SecureLogger.shared.warning(
+ "Chat template failed (\(error.localizedDescription)), falling back to flat prompt",
+ category: "MLXService"
+ )
+ lmInput = try await container.prepare(input: UserInput(prompt: .text(fallback)))
+ }
+ }
+
+ let upstream = try await container.generate(
+ input: lmInput,
+ parameters: request.parameters,
+ tools: request.tools
+ )
+
+ return AsyncStream { continuation in
+ let pump = Task {
+ for await generation in upstream {
+ if Task.isCancelled { break }
+ switch generation {
+ case .chunk(let text):
+ continuation.yield(.chunk(text))
+ case .toolCall(let call):
+ continuation.yield(.toolCall(NativeToolCall(call)))
+ case .rejectedToolCall(let rejected):
+ await SecureLogger.shared.warning(
+ "Rejected tool call (\(rejected.reason)): \(rejected.rawTextPreview.prefix(120))",
+ category: "MLXService"
+ )
+ case .info:
+ break
+ }
+ }
+ continuation.finish()
+ }
+ // Consumer cancelled/finished -> stop pumping. Ending iteration of
+ // `upstream` cancels mlx-swift-lm's own generation task.
+ continuation.onTermination = { _ in pump.cancel() }
+ }
+ }
+}
+
+// MARK: - KV Cache Settings
+
+/// User-facing KV-cache controls (Settings → Model).
+struct KVCacheSettings: Codable, Equatable, Sendable {
+ /// Supported KV quantization choices. 0 = full precision (no quantization).
+ static let allowedBits = [0, 8, 4]
+
+ /// KV cache quantization bits: 0 (none), 8 or 4
+ var bits: Int
+ /// Maximum KV cache size in tokens (rotating cache). 0 = unlimited.
+ var maxSize: Int
+ /// Prompt prefill step size (tokens per forward pass). 0 = model default.
+ var prefillStepSize: Int
+
+ /// Defaults: full-precision cache, unlimited size, 512-token prefill steps
+ /// (mlx-swift-lm's own default).
+ static let `default` = KVCacheSettings(bits: 0, maxSize: 0, prefillStepSize: 512)
+
+ /// Returns a copy with out-of-range values replaced by defaults.
+ func sanitized() -> KVCacheSettings {
+ KVCacheSettings(
+ bits: Self.allowedBits.contains(bits) ? bits : 0,
+ maxSize: maxSize >= 256 ? min(maxSize, 1_048_576) : 0,
+ prefillStepSize: prefillStepSize > 0 ? min(prefillStepSize, 8192) : 0
+ )
+ }
+}
+
+// MARK: - Parameter Mapping
+
+enum GenerationParameterMapper {
+ /// Maps app parameters + KV settings into mlx-swift-lm `GenerateParameters`.
+ static func map(_ parameters: ModelParameters, kvCache: KVCacheSettings = .default) -> GenerateParameters {
+ let kv = kvCache.sanitized()
+ return GenerateParameters(
+ maxTokens: parameters.maxTokens,
+ maxKVSize: kv.maxSize > 0 ? kv.maxSize : nil,
+ kvBits: kv.bits > 0 ? kv.bits : nil,
+ temperature: Float(parameters.temperature),
+ topP: Float(parameters.topP),
+ topK: parameters.topK,
+ minP: Float(parameters.minP),
+ repetitionPenalty: Float(parameters.repetitionPenalty),
+ repetitionContextSize: parameters.repetitionContextSize,
+ prefill: PrefillParameters(stepSize: kv.prefillStepSize > 0 ? kv.prefillStepSize : nil)
+ )
+ }
+}
+
+// MARK: - Tool Specs
+
+enum ToolSpecBuilder {
+ /// OpenAI-style function schema for one tool, as consumed by chat templates.
+ static func spec(for tool: Tool) -> ToolSpec {
+ let schema = tool.parameters
+ var properties: [String: any Sendable] = [:]
+ for (name, property) in schema.properties {
+ properties[name] = propertySchema(property)
+ }
+ let parameters: [String: any Sendable] = [
+ "type": schema.type,
+ "properties": properties,
+ "required": schema.required,
+ ]
+ return [
+ "type": "function",
+ "function": [
+ "name": tool.name,
+ "description": tool.description,
+ "parameters": parameters,
+ ] as [String: any Sendable],
+ ]
+ }
+
+ /// Specs for all tools, sorted by name for a stable prompt (better prompt-cache hits).
+ static func specs(for tools: [Tool]) -> [ToolSpec] {
+ tools.sorted { $0.name < $1.name }.map(spec(for:))
+ }
+
+ private static func propertySchema(_ property: ParameterProperty) -> [String: any Sendable] {
+ var dict: [String: any Sendable] = [
+ "type": property.type,
+ "description": property.description,
+ ]
+ if let values = property.enum { dict["enum"] = values }
+ if let items = property.items { dict["items"] = propertySchema(items) }
+ if let defaultValue = property.default { dict["default"] = defaultValue }
+ return dict
+ }
+}
+
+// MARK: - Native Tool Call → Text Protocol
+
+enum NativeToolCallFormatter {
+ /// Renders a native tool call in the app's `{"name":..,"args":{..}}` format
+ /// so the existing approval / execution / agentic-loop flow handles it unchanged.
+ static func render(_ call: NativeToolCall) -> String {
+ let payload: [String: Any] = ["name": call.name, "args": call.arguments]
+ let json: String
+ if JSONSerialization.isValidJSONObject(payload),
+ let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]),
+ let string = String(data: data, encoding: .utf8) {
+ json = string
+ } else {
+ json = #"{"name":"\#(call.name)","args":{}}"#
+ }
+ return "\n\n\(json)\n\n"
+ }
+}
+
+// MARK: - config.json Inspection
+
+enum ModelConfigInspector {
+ /// Keys that carry the trained context length, in priority order.
+ static let contextKeys = ["max_position_embeddings", "max_sequence_length", "seq_length", "n_positions"]
+
+ /// Reads the context window from a config.json payload.
+ /// Checks the top level first, then nested `text_config` (Gemma 3/4, Qwen3.5/3.6,
+ /// Mistral 3 and other multimodal-capable configs nest the language model there).
+ static func contextWindow(fromConfig data: Data) -> Int? {
+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ return nil
+ }
+ if let value = firstPositiveInt(in: json) { return value }
+ for nestedKey in ["text_config", "language_config", "llm_config"] {
+ if let nested = json[nestedKey] as? [String: Any], let value = firstPositiveInt(in: nested) {
+ return value
+ }
+ }
+ return nil
+ }
+
+ /// Convenience: reads `/config.json`.
+ static func contextWindow(inModelDirectory directory: URL) -> Int? {
+ guard let data = try? Data(contentsOf: directory.appendingPathComponent("config.json")) else {
+ return nil
+ }
+ return contextWindow(fromConfig: data)
+ }
+
+ private static func firstPositiveInt(in dict: [String: Any]) -> Int? {
+ for key in contextKeys {
+ if let value = dict[key] as? Int, value > 0 { return value }
+ }
+ return nil
+ }
+}
diff --git a/MLX Code/Services/LLMBalancer.swift b/MLX Code/Services/LLMBalancer.swift
index 19ba03a..8238524 100644
--- a/MLX Code/Services/LLMBalancer.swift
+++ b/MLX Code/Services/LLMBalancer.swift
@@ -18,6 +18,7 @@
//
import Foundation
+import MLXLMCommon
// MARK: - Backend type
@@ -260,6 +261,7 @@ actor LLMBalancer {
func chatCompletionBalanced(
messages: [Message],
parameters: ModelParameters?,
+ tools: [ToolSpec]? = nil,
streamHandler: ((String) -> Void)? = nil
) async throws -> String? {
let s = await snapshot()
@@ -277,12 +279,15 @@ actor LLMBalancer {
model: choice,
messages: messages,
parameters: parameters,
+ tools: tools,
streamHandler: streamHandler
)
balancer.checkIn(choice.id)
return result
} catch {
balancer.checkIn(choice.id)
+ // Stop pressed: don't fail over to the next backend.
+ if error is CancellationError || Task.isCancelled { throw CancellationError() }
lastError = error
remaining.removeAll { $0.id == choice.id }
continue
@@ -298,6 +303,7 @@ actor LLMBalancer {
model: DiscoveredModel,
messages: [Message],
parameters: ModelParameters?,
+ tools: [ToolSpec]?,
streamHandler: ((String) -> Void)?
) async throws -> String {
switch model.backend {
@@ -306,6 +312,7 @@ actor LLMBalancer {
return try await MLXService.shared.chatCompletion(
messages: messages,
parameters: parameters,
+ tools: tools,
streamHandler: streamHandler
)
case .ollama:
diff --git a/MLX Code/Services/MLXService.swift b/MLX Code/Services/MLXService.swift
index 66546d7..dd74ef1 100644
--- a/MLX Code/Services/MLXService.swift
+++ b/MLX Code/Services/MLXService.swift
@@ -5,13 +5,17 @@
// Created on 2025-11-18.
// Updated 2026-03-04 — Replaced Python daemon with native MLX Swift
// Updated 2026-03-04 — Native model downloads via Hub API (no Python)
+// Updated 2026-11-06 — mlx-swift-lm 3.x (HubClient + Tokenizers via MLXHuggingFace),
+// real cancellation, native tool calling, KV-cache settings
// Copyright © 2025. All rights reserved.
//
import Foundation
-import Hub
+import HuggingFace
+import MLXHuggingFace
import MLXLLM
import MLXLMCommon
+import Tokenizers
// Wraps a non-Sendable stream callback so it can cross actor/task boundaries safely.
private final class StreamHandlerBox: @unchecked Sendable {
@@ -25,6 +29,12 @@ actor MLXService {
/// Shared singleton instance
static let shared = MLXService()
+ /// File patterns fetched when downloading a model snapshot from Hugging Face.
+ /// Besides weights/configs this must include chat templates (`chat_template.jinja`),
+ /// BPE merges (`merges.txt`), and SentencePiece models (`tokenizer.model`), or
+ /// tokenizers silently fall back to wrong templates / fail to load.
+ static let downloadPatterns = ["*.safetensors", "*.json", "*.jinja", "*.txt", "*.model"]
+
/// Currently loaded model metadata
private var loadedModel: MLXModel?
@@ -34,8 +44,11 @@ actor MLXService {
/// Whether inference is currently running
private var isInferenceRunning = false
- /// Native MLX model container (owns model weights + tokenizer)
- private var modelContainer: ModelContainer?
+ /// Generator for the loaded model (wraps the mlx-swift-lm ModelContainer in production)
+ private var generator: (any InferenceGenerator)?
+
+ /// Provides the current KV-cache settings (reads AppSettings in production)
+ private let kvCacheSettingsProvider: @Sendable () async -> KVCacheSettings
/// Context window size read from the model's config.json
private(set) var loadedModelContextWindow: Int?
@@ -43,7 +56,24 @@ actor MLXService {
/// Whether the loaded model's tokenizer supports chat templates
private(set) var hasChatTemplateSupport: Bool = false
- private init() {}
+ private init() {
+ self.kvCacheSettingsProvider = { await MainActor.run { AppSettings.shared.kvCacheSettings } }
+ }
+
+ /// Test/DI initializer: injects a generator and a "loaded" model without touching disk or GPU.
+ init(
+ generator: any InferenceGenerator,
+ model: MLXModel,
+ contextWindow: Int? = nil,
+ kvCacheSettings: KVCacheSettings = .default
+ ) {
+ self.generator = generator
+ self.loadedModel = model
+ self.isModelLoaded = true
+ self.loadedModelContextWindow = contextWindow
+ self.hasChatTemplateSupport = true
+ self.kvCacheSettingsProvider = { kvCacheSettings }
+ }
// MARK: - Model Management
@@ -83,22 +113,18 @@ actor MLXService {
throw MLXServiceError.unsafeModelFormat(expandedPath)
}
- let configuration = ModelConfiguration(directory: directory)
-
- modelContainer = try await LLMModelFactory.shared.loadContainer(
- hub: defaultHubApi,
- configuration: configuration
+ // mlx-swift-lm 3.x: local directory + swift-transformers tokenizer loader
+ let container = try await LLMModelFactory.shared.loadContainer(
+ from: directory,
+ using: #huggingFaceTokenizerLoader()
)
+ generator = MLXContainerGenerator(container: container)
loadedModel = model
isModelLoaded = true
- // Read context window from config.json
- if let configData = try? Data(contentsOf: URL(fileURLWithPath: configPath)),
- let json = try? JSONSerialization.jsonObject(with: configData) as? [String: Any],
- let ctxLen = json["max_position_embeddings"] as? Int {
- loadedModelContextWindow = ctxLen
- }
+ // Read context window from config.json (top level or nested text_config)
+ loadedModelContextWindow = ModelConfigInspector.contextWindow(inModelDirectory: directory)
// mlx-swift-lm handles chat templates natively via the tokenizer
hasChatTemplateSupport = true
@@ -112,7 +138,7 @@ actor MLXService {
/// Unloads the current model and releases GPU memory.
func unloadModel() async {
guard isModelLoaded else { return }
- modelContainer = nil
+ generator = nil
loadedModel = nil
isModelLoaded = false
loadedModelContextWindow = nil
@@ -130,139 +156,118 @@ actor MLXService {
return isModelLoaded
}
+ /// Returns true while a generation is in flight.
+ func isGenerating() -> Bool {
+ return isInferenceRunning
+ }
+
// MARK: - Inference
/// Generates text from a raw prompt.
+ /// Cancelling the calling task stops generation and throws `CancellationError`.
func generate(
prompt: String,
parameters: ModelParameters? = nil,
streamHandler: ((String) -> Void)? = nil
) async throws -> String {
- guard isModelLoaded, let model = loadedModel, let container = modelContainer else {
- throw MLXServiceError.noModelLoaded
- }
- guard !isInferenceRunning else {
- throw MLXServiceError.inferenceInProgress
- }
-
- isInferenceRunning = true
- defer { isInferenceRunning = false }
-
let sanitizedPrompt = SecurityUtils.sanitizeUserInput(prompt)
- let genParams = parameters ?? model.parameters
- guard genParams.isValid() else { throw MLXServiceError.invalidParameters }
-
- let params = GenerateParameters(
- maxTokens: genParams.maxTokens,
- temperature: Float(genParams.temperature),
- topP: Float(genParams.topP),
- repetitionPenalty: Float(genParams.repetitionPenalty)
+ return try await run(
+ prompt: .text(sanitizedPrompt),
+ fallbackPrompt: nil,
+ tools: nil,
+ parameters: parameters,
+ streamHandler: streamHandler
)
-
- let userInput = UserInput(prompt: .text(sanitizedPrompt))
- let lmInput = try await container.prepare(input: userInput)
- let stream = try await container.generate(input: lmInput, parameters: params)
-
- var fullResponse = ""
- if let handler = streamHandler {
- let box = StreamHandlerBox(handler)
- for await generation in stream {
- if let chunk = generation.chunk {
- fullResponse += chunk
- await MainActor.run { box.handler(chunk) }
- }
- }
- } else {
- for await generation in stream {
- if let chunk = generation.chunk {
- fullResponse += chunk
- }
- }
- }
-
- return fullResponse
}
/// Generates a response from structured chat messages using the tokenizer's chat template.
+ ///
+ /// - Parameter tools: Native tool specs (see `ToolSpecBuilder`). Native tool calls are
+ /// rendered as `{...}` text in the returned response so the existing
+ /// tool-approval flow handles them; the plain-text `` protocol still works
+ /// as a fallback for models without native tool-call support.
+ /// Cancelling the calling task stops generation and throws `CancellationError`.
func chatCompletion(
messages: [Message],
parameters: ModelParameters? = nil,
+ tools: [ToolSpec]? = nil,
streamHandler: ((String) -> Void)? = nil
) async throws -> String {
- guard isModelLoaded, let model = loadedModel, let container = modelContainer else {
+ let messageDicts: [[String: String]] = messages.map { msg in
+ [
+ "role": msg.role.rawValue,
+ "content": SecurityUtils.sanitizeUserInput(msg.content)
+ ]
+ }
+ return try await run(
+ prompt: .messages(messageDicts),
+ fallbackPrompt: formatMessagesAsPrompt(messages),
+ tools: (tools?.isEmpty ?? true) ? nil : tools,
+ parameters: parameters,
+ streamHandler: streamHandler
+ )
+ }
+
+ /// Shared generation loop: busy flag, parameter mapping, cancellation, tool-call mapping.
+ private func run(
+ prompt: InferencePrompt,
+ fallbackPrompt: String?,
+ tools: [ToolSpec]?,
+ parameters: ModelParameters?,
+ streamHandler: ((String) -> Void)?
+ ) async throws -> String {
+ guard isModelLoaded, let model = loadedModel, let generator else {
throw MLXServiceError.noModelLoaded
}
guard !isInferenceRunning else {
throw MLXServiceError.inferenceInProgress
}
+ // Always cleared, including on cancellation and errors.
isInferenceRunning = true
defer { isInferenceRunning = false }
+ try Task.checkCancellation()
+
let genParams = parameters ?? model.parameters
guard genParams.isValid() else { throw MLXServiceError.invalidParameters }
- let params = GenerateParameters(
- maxTokens: genParams.maxTokens,
- temperature: Float(genParams.temperature),
- topP: Float(genParams.topP),
- repetitionPenalty: Float(genParams.repetitionPenalty)
+ let kvCache = await kvCacheSettingsProvider()
+ let request = InferenceRequest(
+ prompt: prompt,
+ fallbackPrompt: fallbackPrompt,
+ tools: tools,
+ parameters: GenerationParameterMapper.map(genParams, kvCache: kvCache)
)
- // Convert app Message to [[String: any Sendable]] for MLXLMCommon
- // Note: MLXLMCommon.Message is typealias [String: any Sendable] — avoids naming conflict
- let messageDicts: [[String: any Sendable]] = messages.map { msg in
- [
- "role": msg.role.rawValue,
- "content": SecurityUtils.sanitizeUserInput(msg.content)
- ]
- }
-
- // Try the model's native chat template first. Some models (e.g. Mistral 7B) use
- // Jinja features not yet supported by swift-jinja — fall back to flat prompt format.
- let lmInput: LMInput
- do {
- let userInput = UserInput(prompt: .messages(messageDicts))
- lmInput = try await container.prepare(input: userInput)
- } catch {
- await SecureLogger.shared.warning(
- "Chat template failed (\(error.localizedDescription)), falling back to flat prompt",
- category: "MLXService"
- )
- let flatPrompt = formatMessagesAsPrompt(messages)
- let fallbackInput = UserInput(prompt: .text(flatPrompt))
- lmInput = try await container.prepare(input: fallbackInput)
- }
-
- let stream = try await container.generate(input: lmInput, parameters: params)
+ let stream = try await generator.generate(request)
+ let box = streamHandler.map(StreamHandlerBox.init)
var fullResponse = ""
- if let handler = streamHandler {
- let box = StreamHandlerBox(handler)
- for await generation in stream {
- if let chunk = generation.chunk {
- fullResponse += chunk
- await MainActor.run { box.handler(chunk) }
- // Break as soon as a complete tool call is in the response.
- // This lets chatCompletion() return immediately rather than
- // running to maxTokens, which prevents inferenceInProgress
- // errors on the follow-up generation after tool execution.
- if fullResponse.contains("") || fullResponse.contains("") {
- break
- }
- }
- }
- } else {
- for await generation in stream {
- if let chunk = generation.chunk {
- fullResponse += chunk
- if fullResponse.contains("") || fullResponse.contains("") {
- break
- }
+ var textOnly = ""
+ streamLoop: for await event in stream {
+ if Task.isCancelled { break }
+ switch event {
+ case .chunk(let chunk):
+ fullResponse += chunk
+ textOnly += chunk
+ if let box { await MainActor.run { box.handler(chunk) } }
+ // Text-protocol fallback: stop as soon as a complete text tool call is
+ // present so the follow-up generation can start immediately.
+ if textOnly.contains("") || textOnly.contains("") {
+ break streamLoop
}
+ case .toolCall(let call):
+ // Native tool call: keep consuming so several calls in one turn are captured.
+ let rendered = NativeToolCallFormatter.render(call)
+ fullResponse += rendered
+ if let box { await MainActor.run { box.handler(rendered) } }
}
}
+ // Leaving the loop early (break / cancellation) terminates the stream, which
+ // cancels the underlying mlx-swift-lm generation task.
+ try Task.checkCancellation()
return fullResponse
}
@@ -384,7 +389,8 @@ actor MLXService {
path: url.path,
parameters: ModelParameters(),
isDownloaded: true,
- sizeInBytes: totalSize
+ sizeInBytes: totalSize,
+ contextWindowSize: ModelConfigInspector.contextWindow(inModelDirectory: url)
)
}
@@ -438,10 +444,10 @@ extension MLXService {
To fix:
1. Go to Settings → Models
- 2. Select a model from the list (Llama 3.2, Qwen 2.5, Mistral, or Phi-3.5)
+ 2. Select a model from the list (Qwen3.5, Qwen3.6, Qwen3-Coder, Gemma 4 or Devstral)
3. Or add a HuggingFace ID to your custom model
- Recommended: Use 'Llama 3.2 3B' (fast, 4-bit quantized)
+ Recommended: 'Qwen3.5 9B' (fast, 4-bit quantized)
""")
}
@@ -451,21 +457,48 @@ extension MLXService {
let modelsDirectory = URL(fileURLWithPath: (settingsModelsPath as NSString).expandingTildeInPath)
try? FileManager.default.createDirectory(at: modelsDirectory, withIntermediateDirectories: true)
- let hub = HubApi(downloadBase: modelsDirectory)
- let repo = Hub.Repo(id: huggingFaceId)
-
- let modelDirectory = try await hub.snapshot(
- from: repo,
- matching: ["*.safetensors", "*.json"]
- ) { progress in
- progressHandler?(progress.fractionCompleted)
+ guard let repoID = Repo.ID(rawValue: huggingFaceId) else {
+ throw MLXServiceError.generationFailed("Invalid HuggingFace ID '\(huggingFaceId)'. Expected 'namespace/name'.")
}
+ // Same on-disk layout as the 2.x HubApi(downloadBase:) so existing downloads are reused:
+ // /models//. Caching is disabled so weights are written
+ // once, straight into the user's models folder (not ~/.cache/huggingface).
+ let destination = Self.downloadDestination(for: huggingFaceId, in: modelsDirectory)
+ try? FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
+
+ let hub = HubClient(cache: nil)
+ let progressBox = progressHandler.map { ProgressHandlerBox($0) }
+ let modelDirectory = try await hub.downloadSnapshot(
+ of: repoID,
+ to: destination,
+ matching: Self.downloadPatterns,
+ progressHandler: { progress in
+ progressBox?.handler(progress.fractionCompleted)
+ }
+ )
+
await SecureLogger.shared.info("Download complete: \(model.name) at \(modelDirectory.path)", category: "MLXService")
var updatedModel = model
updatedModel.path = modelDirectory.path
updatedModel.isDownloaded = true
+ if let contextWindow = ModelConfigInspector.contextWindow(inModelDirectory: modelDirectory) {
+ updatedModel.contextWindowSize = contextWindow
+ }
return updatedModel
}
+
+ /// `/models//` — matches the 2.x Hub layout.
+ static func downloadDestination(for huggingFaceId: String, in modelsDirectory: URL) -> URL {
+ modelsDirectory
+ .appendingPathComponent("models", isDirectory: true)
+ .appendingPathComponent(huggingFaceId, isDirectory: true)
+ }
+}
+
+/// Wraps a non-Sendable progress callback for use from the main actor.
+private final class ProgressHandlerBox: @unchecked Sendable {
+ let handler: (Double) -> Void
+ init(_ handler: @escaping (Double) -> Void) { self.handler = handler }
}
diff --git a/MLX Code/ViewModels/ChatViewModel+Tools.swift b/MLX Code/ViewModels/ChatViewModel+Tools.swift
index 1c5ab79..ff56f63 100644
--- a/MLX Code/ViewModels/ChatViewModel+Tools.swift
+++ b/MLX Code/ViewModels/ChatViewModel+Tools.swift
@@ -226,6 +226,7 @@ extension ChatViewModel {
approved[i].approved = true
}
pendingToolCalls = []
+ stopRequested = false
await executePendingToolCalls(approved)
}
diff --git a/MLX Code/ViewModels/ChatViewModel.swift b/MLX Code/ViewModels/ChatViewModel.swift
index 9594f9b..5da8f17 100644
--- a/MLX Code/ViewModels/ChatViewModel.swift
+++ b/MLX Code/ViewModels/ChatViewModel.swift
@@ -73,7 +73,17 @@ class ChatViewModel: ObservableObject {
// MARK: - Private Properties
private var cancellables = Set()
- private let conversationsDirectory: URL
+ /// Where conversations are persisted. `nil` disables persistence (tests).
+ private let conversationsDirectory: URL?
+ /// Inference backend (MLXService.shared in the app; injectable for tests)
+ let inference: MLXService
+ /// The in-flight generation. Cancelling it stops token generation in MLXService.
+ private(set) var generationTask: Task?
+ /// Set by `stopGeneration()`; blocks the agentic tool loop from continuing until
+ /// the user starts a new request.
+ var stopRequested = false
+ /// Whether the multi-model load balancer may be used (tests pin generation to `inference`).
+ var allowLoadBalancing = true
private var streamingMessageId: UUID?
private var generationStartTime: Date?
private var tokenCount: Int = 0
@@ -83,15 +93,28 @@ class ChatViewModel: ObservableObject {
// MARK: - Initialization
- init() {
- // Setup conversations directory
+ /// Default on-disk location for saved conversations.
+ nonisolated static var defaultConversationsDirectory: URL {
guard let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {
fatalError("Application Support directory unavailable")
}
- conversationsDirectory = appSupport.appendingPathComponent("MLX Code/Conversations", isDirectory: true)
+ return appSupport.appendingPathComponent("MLX Code/Conversations", isDirectory: true)
+ }
+
+ /// - Parameters:
+ /// - conversationsDirectory: Persistence location; `nil` disables saving/loading.
+ /// - inference: Inference backend.
+ init(
+ conversationsDirectory: URL? = ChatViewModel.defaultConversationsDirectory,
+ inference: MLXService = .shared
+ ) {
+ self.conversationsDirectory = conversationsDirectory
+ self.inference = inference
// Create directory if needed
- try? FileManager.default.createDirectory(at: conversationsDirectory, withIntermediateDirectories: true)
+ if let conversationsDirectory {
+ try? FileManager.default.createDirectory(at: conversationsDirectory, withIntermediateDirectories: true)
+ }
// Load conversations
loadConversations()
@@ -183,6 +206,7 @@ class ChatViewModel: ObservableObject {
}
userInput = ""
+ stopRequested = false
await generateResponse()
}
@@ -207,8 +231,10 @@ class ChatViewModel: ObservableObject {
func deleteConversation(_ conversation: Conversation) {
conversations.removeAll { $0.id == conversation.id }
- let fileURL = conversationsDirectory.appendingPathComponent("\(conversation.id.uuidString).json")
- try? FileManager.default.removeItem(at: fileURL)
+ if let conversationsDirectory {
+ let fileURL = conversationsDirectory.appendingPathComponent("\(conversation.id.uuidString).json")
+ try? FileManager.default.removeItem(at: fileURL)
+ }
if currentConversation?.id == conversation.id {
currentConversation = nil
}
@@ -221,7 +247,7 @@ class ChatViewModel: ObservableObject {
errorMessage = nil
do {
- try await MLXService.shared.loadModel(model)
+ try await inference.loadModel(model)
isModelLoaded = true
statusMessage = "Model loaded: \(model.name)"
@@ -237,7 +263,7 @@ class ChatViewModel: ObservableObject {
/// Unloads the current model
func unloadModel() async {
- await MLXService.shared.unloadModel()
+ await inference.unloadModel()
isModelLoaded = false
statusMessage = "Model unloaded"
@@ -249,12 +275,19 @@ class ChatViewModel: ObservableObject {
var nudge = Message.system("[Continue the response — do not repeat what was already written above]")
nudge.metadata = ["collapsible": "true", "collapsed": "true"]
currentConversation?.addMessage(nudge)
+ stopRequested = false
Task { await generateResponse() }
}
- /// Stops the current generation
+ /// Stops the current generation.
+ ///
+ /// Cancels the in-flight generation task, which stops token generation inside
+ /// MLXService (and mlx-swift-lm) and frees it for the next request. The partial
+ /// response is kept, and the agentic tool loop does not continue.
func stopGeneration() {
- guard isGenerating else { return }
+ guard isGenerating || generationTask != nil else { return }
+ stopRequested = true
+ generationTask?.cancel()
isGenerating = false
isWaitingForFirstToken = false
statusMessage = "Generation stopped"
@@ -277,6 +310,7 @@ class ChatViewModel: ObservableObject {
currentConversation?.messages.remove(at: lastAssistantIndex)
// Regenerate response
+ stopRequested = false
await generateResponse()
LogManager.shared.info("Regenerated last response", category: "Chat")
}
@@ -307,15 +341,32 @@ class ChatViewModel: ObservableObject {
// MARK: - Private Methods
+ /// Why an in-flight generation was cut short
+ private enum EarlyStop {
+ /// User pressed Stop
+ case user
+ /// Repetition / length guard tripped — keep the truncated response
+ case limit
+ }
+
/// Generates a response from the model
func generateResponse() async {
guard let conversation = currentConversation else { return }
+ // The user pressed Stop: don't let the agentic loop start another turn.
+ guard !stopRequested else { return }
+
guard isModelLoaded else {
errorMessage = "No model is loaded. Please load a model first."
return
}
+ // Make sure any previous generation has fully wound down so MLXService is free.
+ if let previous = generationTask {
+ previous.cancel()
+ _ = try? await previous.value
+ }
+
isGenerating = true
isWaitingForFirstToken = true
statusMessage = "Preparing response..."
@@ -342,11 +393,12 @@ class ChatViewModel: ObservableObject {
var accumulatedResponse = ""
var shouldStopGeneration = false
+ var earlyStop: EarlyStop?
do {
// Build context budget from loaded model
let selectedModel = AppSettings.shared.selectedModel
- let daemonContextWindow = await MLXService.shared.loadedModelContextWindow
+ let daemonContextWindow = await inference.loadedModelContextWindow
let budget = ContextBudget.forModel(selectedModel, daemonContextWindow: daemonContextWindow)
// Assemble optimized context within budget
@@ -358,6 +410,9 @@ class ChatViewModel: ObservableObject {
budget: budget
)
+ // Native tool calling: advertise the registry's tools to the chat template.
+ let toolSpecs = toolModeEnabled ? ToolSpecBuilder.specs(for: toolRegistry.getAllTools()) : nil
+
// Shared streaming token handler. Used by both the single-model MLX
// path and the multi-model load-balanced path so behavior is identical.
let streamHandler: (String) -> Void = { [weak self] token in
@@ -365,10 +420,7 @@ class ChatViewModel: ObservableObject {
guard let self = self else { return }
// Check if we should stop generation
- guard !shouldStopGeneration else {
- logWarning("⚠️ Stopping generation due to repetition/length limit", category: "ChatViewModel")
- return
- }
+ guard !shouldStopGeneration, earlyStop == nil else { return }
// First token received - update status
if self.isWaitingForFirstToken {
@@ -390,9 +442,6 @@ class ChatViewModel: ObservableObject {
}
}
- // Tool call detection is handled in MLXService — it breaks the stream
- // loop as soon as appears, so we just update UI here.
-
// Check for repetition
if let detector = self.repetitionDetector {
let hasRepetition = detector.addToken(token)
@@ -422,6 +471,13 @@ class ChatViewModel: ObservableObject {
accumulatedResponse += "\n\n[Response truncated: maximum tokens reached]"
}
+ // A guard tripped: actually stop the model instead of discarding tokens.
+ if shouldStopGeneration {
+ logWarning("⚠️ Stopping generation due to repetition/length limit", category: "ChatViewModel")
+ earlyStop = .limit
+ self.generationTask?.cancel()
+ }
+
// Update the message content
if let messageId = self.streamingMessageId,
let index = self.currentConversation?.messages.firstIndex(where: { $0.id == messageId }) {
@@ -434,21 +490,43 @@ class ChatViewModel: ObservableObject {
// the healthy enabled pool (all local models + frontier + Nova); the
// balancer returns nil when its pool is empty so we fall back cleanly to
// the single pinned MLX model — preserving existing behavior when off.
- let response: String
- if await LLMBalancer.shared.isBalancingEnabled(),
- let balanced = try await LLMBalancer.shared.chatCompletionBalanced(
- messages: optimizedMessages,
- parameters: selectedModel?.parameters,
- streamHandler: streamHandler
- ) {
- response = balanced
- } else {
- response = try await MLXService.shared.chatCompletion(
+ //
+ // Runs in a stored Task so Stop can cancel it (cancellation propagates into
+ // MLXService, which ends the mlx-swift-lm token stream).
+ let inference = self.inference
+ let allowLoadBalancing = self.allowLoadBalancing
+ let task = Task {
+ if allowLoadBalancing, await LLMBalancer.shared.isBalancingEnabled(),
+ let balanced = try await LLMBalancer.shared.chatCompletionBalanced(
+ messages: optimizedMessages,
+ parameters: selectedModel?.parameters,
+ tools: toolSpecs,
+ streamHandler: streamHandler
+ ) {
+ return balanced
+ }
+ return try await inference.chatCompletion(
messages: optimizedMessages,
parameters: selectedModel?.parameters,
+ tools: toolSpecs,
streamHandler: streamHandler
)
}
+ generationTask = task
+
+ let response: String
+ do {
+ response = try await task.value
+ } catch is CancellationError {
+ if stopRequested { earlyStop = .user }
+ guard earlyStop == .limit else { throw CancellationError() }
+ // Repetition/length guard: keep the truncated text as the final answer.
+ response = accumulatedResponse
+ }
+ generationTask = nil
+
+ // A Stop that raced with normal completion still counts as a stop.
+ if stopRequested { throw CancellationError() }
// Update final message
if let messageId = streamingMessageId,
@@ -485,17 +563,39 @@ class ChatViewModel: ObservableObject {
logInfo("🔧 Tool calls detected in response", category: "ChatViewModel")
await handleToolCallsInResponse(response)
}
+ } catch is CancellationError {
+ // User pressed Stop: keep whatever was streamed so far.
+ generationTask = nil
+ isGenerating = false
+ isWaitingForFirstToken = false
+ statusMessage = "Generation stopped"
+
+ if let messageId = streamingMessageId,
+ let index = currentConversation?.messages.firstIndex(where: { $0.id == messageId }) {
+ if accumulatedResponse.isEmpty {
+ currentConversation?.messages.remove(at: index)
+ } else {
+ currentConversation?.messages[index].content = accumulatedResponse
+ }
+ }
+ streamingMessageId = nil
+
+ if let conversation = currentConversation {
+ saveConversation(conversation)
+ }
+ logInfo("Generation stopped by user", category: "ChatViewModel")
} catch {
+ generationTask = nil
errorMessage = "Failed to generate response: \(error.localizedDescription)"
isGenerating = false
isWaitingForFirstToken = false
statusMessage = "Generation failed"
- streamingMessageId = nil
// Remove placeholder message
if let messageId = streamingMessageId {
currentConversation?.removeMessage(withId: messageId)
}
+ streamingMessageId = nil
logError("Failed to generate response: \(error.localizedDescription)", category: "ChatViewModel")
}
@@ -503,16 +603,16 @@ class ChatViewModel: ObservableObject {
/// Updates the model loaded status and syncs the context window size
private func updateModelStatus() async {
- isModelLoaded = await MLXService.shared.isLoaded()
+ isModelLoaded = await inference.isLoaded()
- if let model = await MLXService.shared.getCurrentModel() {
+ if let model = await inference.getCurrentModel() {
statusMessage = "Model loaded: \(model.name)"
} else {
statusMessage = "No model loaded"
}
// Sync actual context window from the loaded model
- if let contextWindow = await MLXService.shared.loadedModelContextWindow {
+ if let contextWindow = await inference.loadedModelContextWindow {
maxTokens = contextWindow
}
}
@@ -521,7 +621,8 @@ class ChatViewModel: ObservableObject {
private func loadConversations() {
let fileManager = FileManager.default
- guard let files = try? fileManager.contentsOfDirectory(at: conversationsDirectory, includingPropertiesForKeys: nil) else {
+ guard let conversationsDirectory,
+ let files = try? fileManager.contentsOfDirectory(at: conversationsDirectory, includingPropertiesForKeys: nil) else {
return
}
@@ -546,10 +647,11 @@ class ChatViewModel: ObservableObject {
return
}
- let fileURL = conversationsDirectory.appendingPathComponent("\(conversation.id.uuidString).json")
-
if let data = conversation.toJSONData() {
- try? data.write(to: fileURL)
+ if let conversationsDirectory {
+ let fileURL = conversationsDirectory.appendingPathComponent("\(conversation.id.uuidString).json")
+ try? data.write(to: fileURL)
+ }
// Update in conversations list
if let index = conversations.firstIndex(where: { $0.id == conversation.id }) {
diff --git a/MLX Code/Views/SettingsView.swift b/MLX Code/Views/SettingsView.swift
index 8b71567..778da05 100644
--- a/MLX Code/Views/SettingsView.swift
+++ b/MLX Code/Views/SettingsView.swift
@@ -358,6 +358,56 @@ struct SettingsView: View {
Divider()
+ // KV Cache Section (mapped into mlx-swift-lm GenerateParameters)
+ VStack(alignment: .leading, spacing: 16) {
+ Text("KV Cache")
+ .font(.headline)
+ .foregroundColor(.primary)
+
+ HStack {
+ Text("Quantization")
+ .frame(width: 120, alignment: .leading)
+ Picker("", selection: $settings.kvCacheBits) {
+ Text("None (full precision)").tag(0)
+ Text("8-bit").tag(8)
+ Text("4-bit").tag(4)
+ }
+ .labelsHidden()
+ .frame(maxWidth: 220)
+ }
+ Text("Quantizing the KV cache cuts memory for long conversations; 8-bit is near-lossless.")
+ .font(.caption)
+ .foregroundColor(.secondary)
+
+ HStack {
+ Text("Max KV Size")
+ .frame(width: 120, alignment: .leading)
+ Text(settings.maxKVSize == 0 ? "Unlimited" : "\(settings.maxKVSize)")
+ .foregroundColor(.secondary)
+ .frame(width: 80, alignment: .trailing)
+ Stepper("", value: $settings.maxKVSize, in: 0...1_048_576, step: 4096)
+ .labelsHidden()
+ }
+ Text("Caps cache memory with a rotating window (oldest tokens are dropped). 0 = unlimited.")
+ .font(.caption)
+ .foregroundColor(.secondary)
+
+ HStack {
+ Text("Prefill Step")
+ .frame(width: 120, alignment: .leading)
+ Text(settings.prefillStepSize == 0 ? "Auto" : "\(settings.prefillStepSize)")
+ .foregroundColor(.secondary)
+ .frame(width: 80, alignment: .trailing)
+ Stepper("", value: $settings.prefillStepSize, in: 0...8192, step: 256)
+ .labelsHidden()
+ }
+ Text("Tokens processed per prompt-prefill pass. Larger is faster but uses more peak memory.")
+ .font(.caption)
+ .foregroundColor(.secondary)
+ }
+
+ Divider()
+
// Available Models Section
VStack(alignment: .leading, spacing: 12) {
HStack {
diff --git a/Python/=0.0.10 b/Python/=0.0.10
deleted file mode 100644
index 7e810e6..0000000
--- a/Python/=0.0.10
+++ /dev/null
@@ -1,82 +0,0 @@
-Collecting mlx
- Downloading mlx-0.29.3-cp39-cp39-macosx_15_0_arm64.whl.metadata (5.7 kB)
-Collecting mlx-lm
- Downloading mlx_lm-0.28.3-py3-none-any.whl.metadata (10 kB)
-Collecting mlx-metal==0.29.3 (from mlx)
- Downloading mlx_metal-0.29.3-py3-none-macosx_15_0_arm64.whl.metadata (5.1 kB)
-Collecting numpy (from mlx-lm)
- Downloading numpy-2.0.2-cp39-cp39-macosx_14_0_arm64.whl.metadata (60 kB)
-Collecting transformers>=4.39.3 (from mlx-lm)
- Downloading transformers-4.57.1-py3-none-any.whl.metadata (43 kB)
-Collecting protobuf (from mlx-lm)
- Downloading protobuf-6.33.1-cp39-abi3-macosx_10_9_universal2.whl.metadata (593 bytes)
-Collecting pyyaml (from mlx-lm)
- Downloading pyyaml-6.0.3-cp39-cp39-macosx_11_0_arm64.whl.metadata (2.4 kB)
-Collecting jinja2 (from mlx-lm)
- Downloading jinja2-3.1.6-py3-none-any.whl.metadata (2.9 kB)
-Collecting filelock (from transformers>=4.39.3->mlx-lm)
- Downloading filelock-3.19.1-py3-none-any.whl.metadata (2.1 kB)
-Collecting huggingface-hub<1.0,>=0.34.0 (from transformers>=4.39.3->mlx-lm)
- Downloading huggingface_hub-0.36.0-py3-none-any.whl.metadata (14 kB)
-Collecting packaging>=20.0 (from transformers>=4.39.3->mlx-lm)
- Downloading packaging-25.0-py3-none-any.whl.metadata (3.3 kB)
-Collecting regex!=2019.12.17 (from transformers>=4.39.3->mlx-lm)
- Downloading regex-2025.11.3-cp39-cp39-macosx_11_0_arm64.whl.metadata (40 kB)
-Collecting requests (from transformers>=4.39.3->mlx-lm)
- Downloading requests-2.32.5-py3-none-any.whl.metadata (4.9 kB)
-Collecting tokenizers<=0.23.0,>=0.22.0 (from transformers>=4.39.3->mlx-lm)
- Downloading tokenizers-0.22.1-cp39-abi3-macosx_11_0_arm64.whl.metadata (6.8 kB)
-Collecting safetensors>=0.4.3 (from transformers>=4.39.3->mlx-lm)
- Downloading safetensors-0.6.2-cp38-abi3-macosx_11_0_arm64.whl.metadata (4.1 kB)
-Collecting tqdm>=4.27 (from transformers>=4.39.3->mlx-lm)
- Downloading tqdm-4.67.1-py3-none-any.whl.metadata (57 kB)
-Collecting fsspec>=2023.5.0 (from huggingface-hub<1.0,>=0.34.0->transformers>=4.39.3->mlx-lm)
- Downloading fsspec-2025.10.0-py3-none-any.whl.metadata (10 kB)
-Collecting typing-extensions>=3.7.4.3 (from huggingface-hub<1.0,>=0.34.0->transformers>=4.39.3->mlx-lm)
- Downloading typing_extensions-4.15.0-py3-none-any.whl.metadata (3.3 kB)
-Collecting hf-xet<2.0.0,>=1.1.3 (from huggingface-hub<1.0,>=0.34.0->transformers>=4.39.3->mlx-lm)
- Downloading hf_xet-1.2.0-cp37-abi3-macosx_11_0_arm64.whl.metadata (4.9 kB)
-Collecting MarkupSafe>=2.0 (from jinja2->mlx-lm)
- Downloading markupsafe-3.0.3-cp39-cp39-macosx_11_0_arm64.whl.metadata (2.7 kB)
-Collecting charset_normalizer<4,>=2 (from requests->transformers>=4.39.3->mlx-lm)
- Downloading charset_normalizer-3.4.4-cp39-cp39-macosx_10_9_universal2.whl.metadata (37 kB)
-Collecting idna<4,>=2.5 (from requests->transformers>=4.39.3->mlx-lm)
- Downloading idna-3.11-py3-none-any.whl.metadata (8.4 kB)
-Collecting urllib3<3,>=1.21.1 (from requests->transformers>=4.39.3->mlx-lm)
- Downloading urllib3-2.5.0-py3-none-any.whl.metadata (6.5 kB)
-Collecting certifi>=2017.4.17 (from requests->transformers>=4.39.3->mlx-lm)
- Downloading certifi-2025.11.12-py3-none-any.whl.metadata (2.5 kB)
-Downloading mlx-0.29.3-cp39-cp39-macosx_15_0_arm64.whl (549 kB)
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 549.3/549.3 kB 10.3 MB/s 0:00:00
-Downloading mlx_metal-0.29.3-py3-none-macosx_15_0_arm64.whl (36.5 MB)
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 36.5/36.5 MB 47.0 MB/s 0:00:00
-Downloading mlx_lm-0.28.3-py3-none-any.whl (294 kB)
-Downloading transformers-4.57.1-py3-none-any.whl (12.0 MB)
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 12.0/12.0 MB 48.6 MB/s 0:00:00
-Downloading huggingface_hub-0.36.0-py3-none-any.whl (566 kB)
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 566.1/566.1 kB 19.9 MB/s 0:00:00
-Downloading hf_xet-1.2.0-cp37-abi3-macosx_11_0_arm64.whl (2.7 MB)
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.7/2.7 MB 42.8 MB/s 0:00:00
-Downloading tokenizers-0.22.1-cp39-abi3-macosx_11_0_arm64.whl (2.9 MB)
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.9/2.9 MB 43.2 MB/s 0:00:00
-Downloading fsspec-2025.10.0-py3-none-any.whl (200 kB)
-Downloading numpy-2.0.2-cp39-cp39-macosx_14_0_arm64.whl (5.3 MB)
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 5.3/5.3 MB 45.7 MB/s 0:00:00
-Downloading packaging-25.0-py3-none-any.whl (66 kB)
-Downloading pyyaml-6.0.3-cp39-cp39-macosx_11_0_arm64.whl (174 kB)
-Downloading regex-2025.11.3-cp39-cp39-macosx_11_0_arm64.whl (288 kB)
-Downloading safetensors-0.6.2-cp38-abi3-macosx_11_0_arm64.whl (432 kB)
-Downloading tqdm-4.67.1-py3-none-any.whl (78 kB)
-Downloading typing_extensions-4.15.0-py3-none-any.whl (44 kB)
-Downloading filelock-3.19.1-py3-none-any.whl (15 kB)
-Downloading jinja2-3.1.6-py3-none-any.whl (134 kB)
-Downloading markupsafe-3.0.3-cp39-cp39-macosx_11_0_arm64.whl (12 kB)
-Downloading protobuf-6.33.1-cp39-abi3-macosx_10_9_universal2.whl (427 kB)
-Downloading requests-2.32.5-py3-none-any.whl (64 kB)
-Downloading charset_normalizer-3.4.4-cp39-cp39-macosx_10_9_universal2.whl (209 kB)
-Downloading idna-3.11-py3-none-any.whl (71 kB)
-Downloading urllib3-2.5.0-py3-none-any.whl (129 kB)
-Downloading certifi-2025.11.12-py3-none-any.whl (159 kB)
-Installing collected packages: urllib3, typing-extensions, tqdm, safetensors, regex, pyyaml, protobuf, packaging, numpy, mlx-metal, MarkupSafe, idna, hf-xet, fsspec, filelock, charset_normalizer, certifi, requests, mlx, jinja2, huggingface-hub, tokenizers, transformers, mlx-lm
-
-Successfully installed MarkupSafe-3.0.3 certifi-2025.11.12 charset_normalizer-3.4.4 filelock-3.19.1 fsspec-2025.10.0 hf-xet-1.2.0 huggingface-hub-0.36.0 idna-3.11 jinja2-3.1.6 mlx-0.29.3 mlx-lm-0.28.3 mlx-metal-0.29.3 numpy-2.0.2 packaging-25.0 protobuf-6.33.1 pyyaml-6.0.3 regex-2025.11.3 requests-2.32.5 safetensors-0.6.2 tokenizers-0.22.1 tqdm-4.67.1 transformers-4.57.1 typing-extensions-4.15.0 urllib3-2.5.0
diff --git a/Python/=0.19.0 b/Python/=0.19.0
deleted file mode 100644
index e69de29..0000000
diff --git a/Python/=1.24.0 b/Python/=1.24.0
deleted file mode 100644
index e69de29..0000000
diff --git a/Python/=2.2.0 b/Python/=2.2.0
deleted file mode 100644
index e69de29..0000000
diff --git a/Python/=4.35.0 b/Python/=4.35.0
deleted file mode 100644
index 92451f8..0000000
--- a/Python/=4.35.0
+++ /dev/null
@@ -1,18 +0,0 @@
-Requirement already satisfied: huggingface-hub in /Users/kochj/Library/Python/3.9/lib/python/site-packages (0.36.0)
-Requirement already satisfied: transformers in /Users/kochj/Library/Python/3.9/lib/python/site-packages (4.57.1)
-Requirement already satisfied: filelock in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from huggingface-hub) (3.19.1)
-Requirement already satisfied: fsspec>=2023.5.0 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from huggingface-hub) (2025.10.0)
-Requirement already satisfied: packaging>=20.9 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from huggingface-hub) (25.0)
-Requirement already satisfied: pyyaml>=5.1 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from huggingface-hub) (6.0.3)
-Requirement already satisfied: requests in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from huggingface-hub) (2.32.5)
-Requirement already satisfied: tqdm>=4.42.1 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from huggingface-hub) (4.67.1)
-Requirement already satisfied: typing-extensions>=3.7.4.3 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from huggingface-hub) (4.15.0)
-Requirement already satisfied: hf-xet<2.0.0,>=1.1.3 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from huggingface-hub) (1.2.0)
-Requirement already satisfied: numpy>=1.17 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from transformers) (2.0.2)
-Requirement already satisfied: regex!=2019.12.17 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from transformers) (2025.11.3)
-Requirement already satisfied: tokenizers<=0.23.0,>=0.22.0 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from transformers) (0.22.1)
-Requirement already satisfied: safetensors>=0.4.3 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from transformers) (0.6.2)
-Requirement already satisfied: charset_normalizer<4,>=2 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from requests->huggingface-hub) (3.4.4)
-Requirement already satisfied: idna<4,>=2.5 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from requests->huggingface-hub) (3.11)
-Requirement already satisfied: urllib3<3,>=1.21.1 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from requests->huggingface-hub) (2.5.0)
-Requirement already satisfied: certifi>=2017.4.17 in /Users/kochj/Library/Python/3.9/lib/python/site-packages (from requests->huggingface-hub) (2025.11.12)
diff --git a/Python/=4.65.0 b/Python/=4.65.0
deleted file mode 100644
index 35a3f41..0000000
--- a/Python/=4.65.0
+++ /dev/null
@@ -1,2 +0,0 @@
-Requirement already satisfied: numpy in /Users/kochj/Library/Python/3.9/lib/python/site-packages (2.0.2)
-Requirement already satisfied: tqdm in /Users/kochj/Library/Python/3.9/lib/python/site-packages (4.67.1)
diff --git a/Python/huggingface_downloader.py b/Python/huggingface_downloader.py
deleted file mode 100644
index ab063cc..0000000
--- a/Python/huggingface_downloader.py
+++ /dev/null
@@ -1,288 +0,0 @@
-#!/usr/bin/env python3
-"""
-HuggingFace Model Downloader
-Downloads and converts models from HuggingFace to MLX format.
-"""
-
-import sys
-import json
-import argparse
-from pathlib import Path
-from typing import Dict, Any, Optional
-import shutil
-
-try:
- from huggingface_hub import snapshot_download, list_repo_files, hf_hub_download
- from huggingface_hub.utils import HfHubHTTPError
- HF_AVAILABLE = True
-except ImportError:
- HF_AVAILABLE = False
- print(json.dumps({
- "error": "huggingface_hub not installed. Install with: pip install huggingface-hub",
- "type": "import_error"
- }), flush=True)
- sys.exit(1)
-
-# Note: mlx_lm.convert is NOT imported here to avoid xcrun calls in App Sandbox
-# It will be imported lazily only if conversion is actually needed
-MLX_CONVERT_AVAILABLE = False # Disabled to prevent sandbox issues
-
-
-class HuggingFaceDownloader:
- """Handles downloading models from HuggingFace."""
-
- def __init__(self, cache_dir: Optional[str] = None):
- """
- Initialize downloader.
-
- Args:
- cache_dir: Directory to cache downloads (default: ~/.cache/huggingface)
- """
- self.cache_dir = Path(cache_dir).expanduser() if cache_dir else None
-
- def download_model(
- self,
- repo_id: str,
- output_dir: str,
- convert_to_mlx: bool = True,
- quantize: Optional[str] = None
- ) -> Dict[str, Any]:
- """
- Download model from HuggingFace.
-
- Args:
- repo_id: HuggingFace repo ID (e.g., "mlx-community/Llama-3.2-3B-Instruct-4bit")
- output_dir: Directory to save model
- convert_to_mlx: Whether to convert to MLX format
- quantize: Quantization level (None, "4bit", "8bit")
-
- Returns:
- Status dict with download info
- """
- try:
- output_path = Path(output_dir).expanduser()
- output_path.mkdir(parents=True, exist_ok=True)
-
- # Check if model already exists
- if (output_path / "config.json").exists():
- return {
- "success": True,
- "path": str(output_path),
- "message": "Model already exists",
- "skipped": True
- }
-
- # Download model
- print(json.dumps({
- "type": "progress",
- "stage": "downloading",
- "message": f"Downloading {repo_id}..."
- }), flush=True)
-
- # Download with progress
- downloaded_path = snapshot_download(
- repo_id=repo_id,
- cache_dir=self.cache_dir,
- local_dir=output_path,
- local_dir_use_symlinks=False
- )
-
- # Convert to MLX if requested
- # Note: Conversion is disabled to prevent xcrun calls in App Sandbox
- # All models should be from mlx-community (already in MLX format)
- if convert_to_mlx:
- print(json.dumps({
- "type": "warning",
- "message": "Conversion skipped - use mlx-community models (already in MLX format)"
- }), flush=True)
-
- # Get model size
- model_size = sum(f.stat().st_size for f in output_path.rglob('*') if f.is_file())
- model_size_gb = model_size / (1024 ** 3)
-
- return {
- "success": True,
- "path": str(output_path),
- "repo_id": repo_id,
- "size_bytes": model_size,
- "size_gb": round(model_size_gb, 2),
- "quantization": quantize,
- "converted_to_mlx": convert_to_mlx and MLX_CONVERT_AVAILABLE
- }
-
- except HfHubHTTPError as e:
- if e.response.status_code == 404:
- return {
- "success": False,
- "error": f"Model not found: {repo_id}",
- "type": "not_found_error"
- }
- else:
- return {
- "success": False,
- "error": str(e),
- "type": "http_error"
- }
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "download_error"
- }
-
- def list_files(self, repo_id: str) -> Dict[str, Any]:
- """
- List files in a HuggingFace repository.
-
- Args:
- repo_id: HuggingFace repo ID
-
- Returns:
- Dict with file list
- """
- try:
- files = list_repo_files(repo_id=repo_id)
-
- return {
- "success": True,
- "repo_id": repo_id,
- "files": files,
- "count": len(files)
- }
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "list_error"
- }
-
- def get_model_info(self, repo_id: str) -> Dict[str, Any]:
- """
- Get information about a model.
-
- Args:
- repo_id: HuggingFace repo ID
-
- Returns:
- Dict with model info
- """
- try:
- from huggingface_hub import model_info
-
- info = model_info(repo_id=repo_id)
-
- return {
- "success": True,
- "repo_id": repo_id,
- "author": info.author,
- "model_id": info.modelId,
- "downloads": info.downloads,
- "likes": info.likes,
- "tags": info.tags,
- "pipeline_tag": info.pipeline_tag,
- "library_name": info.library_name
- }
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "info_error"
- }
-
- def delete_model(self, model_path: str) -> Dict[str, Any]:
- """
- Delete a downloaded model.
-
- Args:
- model_path: Path to model directory
-
- Returns:
- Status dict
- """
- try:
- model_path = Path(model_path).expanduser()
-
- if not model_path.exists():
- return {
- "success": False,
- "error": f"Model path does not exist: {model_path}",
- "type": "path_error"
- }
-
- # Delete directory
- shutil.rmtree(model_path)
-
- return {
- "success": True,
- "message": f"Deleted model at {model_path}"
- }
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "delete_error"
- }
-
-
-def main():
- """Main entry point for CLI usage."""
- parser = argparse.ArgumentParser(description="HuggingFace Model Downloader")
-
- subparsers = parser.add_subparsers(dest="command", help="Command to execute")
-
- # Download command
- download_parser = subparsers.add_parser("download", help="Download a model")
- download_parser.add_argument("repo_id", type=str, help="HuggingFace repo ID")
- download_parser.add_argument("--output", type=str, required=True, help="Output directory")
- download_parser.add_argument("--no-convert", action="store_true", help="Don't convert to MLX")
- download_parser.add_argument("--quantize", choices=["4bit", "8bit"], help="Quantization level")
- download_parser.add_argument("--cache-dir", type=str, help="Cache directory")
-
- # List command
- list_parser = subparsers.add_parser("list", help="List files in a model repo")
- list_parser.add_argument("repo_id", type=str, help="HuggingFace repo ID")
-
- # Info command
- info_parser = subparsers.add_parser("info", help="Get model information")
- info_parser.add_argument("repo_id", type=str, help="HuggingFace repo ID")
-
- # Delete command
- delete_parser = subparsers.add_parser("delete", help="Delete a downloaded model")
- delete_parser.add_argument("model_path", type=str, help="Path to model directory")
-
- args = parser.parse_args()
-
- downloader = HuggingFaceDownloader(cache_dir=getattr(args, 'cache_dir', None))
-
- if args.command == "download":
- result = downloader.download_model(
- repo_id=args.repo_id,
- output_dir=args.output,
- convert_to_mlx=not args.no_convert,
- quantize=args.quantize
- )
- print(json.dumps(result, indent=2), flush=True)
-
- elif args.command == "list":
- result = downloader.list_files(repo_id=args.repo_id)
- print(json.dumps(result, indent=2), flush=True)
-
- elif args.command == "info":
- result = downloader.get_model_info(repo_id=args.repo_id)
- print(json.dumps(result, indent=2), flush=True)
-
- elif args.command == "delete":
- result = downloader.delete_model(model_path=args.model_path)
- print(json.dumps(result, indent=2), flush=True)
-
- else:
- parser.print_help()
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/Python/mlx_daemon.py b/Python/mlx_daemon.py
deleted file mode 100755
index e6d8f84..0000000
--- a/Python/mlx_daemon.py
+++ /dev/null
@@ -1,360 +0,0 @@
-#!/usr/bin/env python3
-"""
-MLX Persistent Daemon
-Keeps model loaded in memory for instant inference.
-"""
-
-import sys
-import json
-import signal
-from pathlib import Path
-from typing import Optional
-
-try:
- import mlx.core as mx
- from mlx_lm import load, generate
- MLX_AVAILABLE = True
-except ImportError as e:
- MLX_AVAILABLE = False
- print(json.dumps({
- "error": f"MLX not installed: {str(e)}",
- "type": "import_error"
- }), flush=True)
- sys.exit(1)
-
-
-class MLXDaemon:
- """Persistent MLX inference daemon."""
-
- def __init__(self):
- self.model = None
- self.tokenizer = None
- self.model_path = None
- self.running = True
-
- # Setup signal handlers for graceful shutdown
- signal.signal(signal.SIGINT, self._handle_shutdown)
- signal.signal(signal.SIGTERM, self._handle_shutdown)
-
- def _handle_shutdown(self, signum, frame):
- """Handle shutdown signals gracefully."""
- self.running = False
- print(json.dumps({
- "type": "shutdown",
- "message": "Daemon shutting down"
- }), flush=True)
- sys.exit(0)
-
- def _read_context_window(self, model_path: Path) -> int:
- """Read context window size from model config.json."""
- config_path = model_path / "config.json"
- context_window = 8192 # conservative default
- if config_path.exists():
- try:
- import json as json_mod
- with open(config_path) as f:
- config = json_mod.load(f)
- context_window = config.get("max_position_embeddings",
- config.get("max_seq_len",
- config.get("seq_length",
- config.get("sliding_window", 8192))))
- if isinstance(context_window, str):
- context_window = int(context_window)
- except Exception:
- pass
- return context_window
-
- def load_model(self, model_path: str) -> dict:
- """Load model into memory (with caching)."""
- try:
- print(json.dumps({
- "type": "debug",
- "message": f"load_model() called with: {model_path}"
- }), flush=True)
-
- model_path = Path(model_path).expanduser()
-
- print(json.dumps({
- "type": "debug",
- "message": f"Expanded to: {model_path}"
- }), flush=True)
-
- print(json.dumps({
- "type": "debug",
- "message": f"Path exists: {model_path.exists()}"
- }), flush=True)
-
- if not model_path.exists():
- return {
- "success": False,
- "error": f"Model path does not exist: {model_path}",
- "type": "path_error"
- }
-
- # Read context window from config
- context_window = self._read_context_window(model_path)
-
- # Check if already loaded (CACHE)
- if self.model is not None and self.model_path == model_path:
- return {
- "success": True,
- "path": str(model_path),
- "name": model_path.name,
- "cached": True,
- "context_window": context_window,
- "message": "Model already loaded in daemon"
- }
-
- # Load model
- print(json.dumps({
- "type": "debug",
- "message": f"Calling mlx_lm.load() with: {str(model_path)}"
- }), flush=True)
-
- self.model, self.tokenizer = load(str(model_path))
- self.model_path = model_path
-
- print(json.dumps({
- "type": "debug",
- "message": "mlx_lm.load() completed successfully"
- }), flush=True)
-
- # Check if tokenizer supports chat templates
- has_chat_template = hasattr(self.tokenizer, 'apply_chat_template')
- print(json.dumps({
- "type": "debug",
- "message": f"Chat template support: {has_chat_template}, context_window: {context_window}"
- }), flush=True)
-
- return {
- "success": True,
- "path": str(model_path),
- "name": model_path.name,
- "cached": False,
- "context_window": context_window,
- "has_chat_template": has_chat_template,
- "message": "Model loaded successfully"
- }
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "load_error"
- }
-
- def _format_chatml(self, messages: list) -> str:
- """Fallback ChatML formatting for models without chat templates."""
- prompt = ""
- for msg in messages:
- role = msg.get("role", "user")
- content = msg.get("content", "")
- prompt += f"<|im_start|>{role}\n{content}<|im_end|>\n"
- prompt += "<|im_start|>assistant\n"
- return prompt
-
- def chat_generate(
- self,
- messages: list,
- max_tokens: int = 2048,
- temperature: float = 0.7,
- top_p: float = 0.9,
- repetition_penalty: float = 1.0
- ):
- """Generate from structured messages using tokenizer's chat template."""
- if self.model is None or self.tokenizer is None:
- yield {
- "type": "error",
- "error": "No model loaded"
- }
- return
-
- try:
- # Use tokenizer's built-in chat template if available
- if hasattr(self.tokenizer, 'apply_chat_template'):
- try:
- prompt = self.tokenizer.apply_chat_template(
- messages,
- tokenize=False,
- add_generation_prompt=True
- )
- print(json.dumps({
- "type": "debug",
- "message": f"Applied tokenizer chat template, prompt length: {len(prompt)}"
- }), flush=True)
- except Exception as e:
- print(json.dumps({
- "type": "debug",
- "message": f"Chat template failed ({e}), falling back to ChatML"
- }), flush=True)
- prompt = self._format_chatml(messages)
- else:
- prompt = self._format_chatml(messages)
- print(json.dumps({
- "type": "debug",
- "message": f"No chat template, using ChatML fallback, prompt length: {len(prompt)}"
- }), flush=True)
-
- # Generate with same streaming approach as generate()
- response = generate(
- self.model,
- self.tokenizer,
- prompt=prompt,
- max_tokens=max_tokens,
- verbose=False
- )
-
- # Stream tokens
- for token in response:
- if not self.running:
- break
- yield {
- "type": "token",
- "token": token
- }
-
- yield {
- "type": "complete",
- "message": "Generation finished"
- }
-
- except Exception as e:
- yield {
- "type": "error",
- "error": str(e)
- }
-
- def generate(
- self,
- prompt: str,
- max_tokens: int = 2048,
- temperature: float = 0.7,
- top_p: float = 0.9,
- repetition_penalty: float = 1.0
- ):
- """Generate text from prompt (streaming)."""
- if self.model is None:
- yield {
- "type": "error",
- "error": "No model loaded"
- }
- return
-
- try:
- # Generate with mlx_lm.generate() which returns a generator
- # Note: generate() only accepts model, tokenizer, prompt, max_tokens, verbose
- response = generate(
- self.model,
- self.tokenizer,
- prompt=prompt,
- max_tokens=max_tokens,
- verbose=False
- )
-
- # Stream tokens from generator
- for token in response:
- if not self.running:
- break
-
- yield {
- "type": "token",
- "token": token
- }
-
- # Generation complete
- yield {
- "type": "complete",
- "message": "Generation finished"
- }
-
- except Exception as e:
- yield {
- "type": "error",
- "error": str(e)
- }
-
- def run(self):
- """Main daemon loop - process commands from stdin."""
- # Send ready message
- print(json.dumps({
- "type": "ready",
- "message": "Daemon started and ready"
- }), flush=True)
-
- while self.running:
- try:
- # Read command from stdin
- line = sys.stdin.readline()
-
- if not line:
- # EOF reached
- break
-
- command = json.loads(line.strip())
- command_type = command.get("type")
-
- if command_type == "load_model":
- result = self.load_model(command["model_path"])
- print(json.dumps(result), flush=True)
-
- elif command_type == "chat_generate":
- # Structured message generation with chat template
- for response in self.chat_generate(
- messages=command["messages"],
- max_tokens=command.get("max_tokens", 2048),
- temperature=command.get("temperature", 0.7),
- top_p=command.get("top_p", 0.9),
- repetition_penalty=command.get("repetition_penalty", 1.0)
- ):
- print(json.dumps(response), flush=True)
-
- elif command_type == "generate":
- # Stream tokens (legacy raw prompt mode)
- for response in self.generate(
- prompt=command["prompt"],
- max_tokens=command.get("max_tokens", 2048),
- temperature=command.get("temperature", 0.7),
- top_p=command.get("top_p", 0.9),
- repetition_penalty=command.get("repetition_penalty", 1.0)
- ):
- print(json.dumps(response), flush=True)
-
- elif command_type == "status":
- # Health check
- print(json.dumps({
- "type": "status",
- "running": True,
- "model_loaded": self.model is not None,
- "model_path": str(self.model_path) if self.model_path else None
- }), flush=True)
-
- elif command_type == "shutdown":
- self.running = False
- print(json.dumps({
- "type": "shutdown",
- "message": "Daemon shutting down"
- }), flush=True)
- break
-
- else:
- print(json.dumps({
- "type": "error",
- "error": f"Unknown command type: {command_type}"
- }), flush=True)
-
- except json.JSONDecodeError as e:
- print(json.dumps({
- "type": "error",
- "error": f"Invalid JSON: {str(e)}"
- }), flush=True)
-
- except Exception as e:
- print(json.dumps({
- "type": "error",
- "error": f"Unexpected error: {str(e)}"
- }), flush=True)
-
-
-if __name__ == "__main__":
- daemon = MLXDaemon()
- daemon.run()
diff --git a/Python/mlx_inference.py b/Python/mlx_inference.py
deleted file mode 100644
index f66fb45..0000000
--- a/Python/mlx_inference.py
+++ /dev/null
@@ -1,278 +0,0 @@
-#!/usr/bin/env python3
-"""
-MLX Inference Bridge
-Handles real MLX model loading and inference for MLX Code app.
-"""
-
-import sys
-import json
-import argparse
-from pathlib import Path
-from typing import Dict, Any, Optional, Iterator
-import threading
-import queue
-
-try:
- import mlx.core as mx
- import mlx.nn as nn
- from mlx_lm import load, generate, stream_generate
- MLX_AVAILABLE = True
-except ImportError as e:
- MLX_AVAILABLE = False
- print(json.dumps({
- "error": f"MLX not installed: {str(e)}. Install with: pip install mlx mlx-lm",
- "type": "import_error"
- }), flush=True)
- sys.exit(1)
-
-
-class MLXInferenceEngine:
- """Handles MLX model loading and inference with caching."""
-
- def __init__(self):
- self.model = None
- self.tokenizer = None
- self.model_path = None
- self.config = {}
-
- def load_model(self, model_path: str) -> Dict[str, Any]:
- """
- Load MLX model from path with caching.
-
- Args:
- model_path: Path to model directory
-
- Returns:
- Status dict with success/error info
- """
- try:
- model_path = Path(model_path).expanduser()
-
- if not model_path.exists():
- return {
- "success": False,
- "error": f"Model path does not exist: {model_path}",
- "type": "path_error"
- }
-
- # Check if model is already loaded (CACHE CHECK)
- if self.model is not None and self.model_path == model_path:
- return {
- "success": True,
- "path": str(model_path),
- "name": model_path.name,
- "type": "mlx",
- "cached": True,
- "message": "Model already loaded (cached)"
- }
-
- # Load model and tokenizer
- self.model, self.tokenizer = load(str(model_path))
- self.model_path = model_path
-
- # Get model info
- model_info = {
- "success": True,
- "path": str(model_path),
- "name": model_path.name,
- "type": "mlx",
- "cached": False,
- "message": "Model loaded from disk"
- }
-
- return model_info
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "load_error"
- }
-
- def generate(
- self,
- prompt: str,
- max_tokens: int = 2048,
- temperature: float = 0.7,
- top_p: float = 0.9,
- repetition_penalty: float = 1.0,
- stream: bool = True
- ) -> Iterator[Dict[str, Any]]:
- """
- Generate text from prompt using loaded model.
-
- Args:
- prompt: Input prompt
- max_tokens: Maximum tokens to generate
- temperature: Sampling temperature (0.0-2.0)
- top_p: Nucleus sampling parameter
- repetition_penalty: Penalty for repeating tokens
- stream: Whether to stream tokens
-
- Yields:
- Dicts with generated tokens or completion status
- """
- if self.model is None or self.tokenizer is None:
- yield {
- "error": "No model loaded. Call load_model first.",
- "type": "model_error"
- }
- return
-
- try:
- # Generate with streaming
- # Note: mlx_lm.generate() returns a generator that yields strings
- response = generate(
- self.model,
- self.tokenizer,
- prompt=prompt,
- max_tokens=max_tokens,
- verbose=False
- )
-
- if stream:
- # Stream token by token
- for token in response:
- yield {
- "token": token,
- "type": "token"
- }
- else:
- # Return complete response
- full_response = "".join(response)
- yield {
- "text": full_response,
- "type": "complete"
- }
-
- # Send completion signal
- yield {
- "type": "done",
- "success": True
- }
-
- except Exception as e:
- yield {
- "error": str(e),
- "type": "generation_error"
- }
-
- def unload_model(self) -> Dict[str, Any]:
- """Unload current model from memory."""
- try:
- self.model = None
- self.tokenizer = None
- self.model_path = None
-
- # Force garbage collection
- import gc
- gc.collect()
-
- return {
- "success": True,
- "message": "Model unloaded successfully"
- }
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "unload_error"
- }
-
-
-def main():
- """Main entry point for CLI usage."""
- parser = argparse.ArgumentParser(description="MLX Inference Bridge")
- parser.add_argument("--mode", choices=["interactive", "single"], default="interactive",
- help="Interaction mode")
- parser.add_argument("--model", type=str, help="Model path to load")
- parser.add_argument("--prompt", type=str, help="Prompt for single mode")
- parser.add_argument("--max-tokens", type=int, default=2048, help="Max tokens to generate")
- parser.add_argument("--temperature", type=float, default=0.7, help="Sampling temperature")
- parser.add_argument("--top-p", type=float, default=0.9, help="Nucleus sampling parameter")
- parser.add_argument("--stream", action="store_true", default=True, help="Stream tokens")
-
- args = parser.parse_args()
-
- engine = MLXInferenceEngine()
-
- if args.mode == "single":
- # Single inference mode
- if not args.model or not args.prompt:
- print(json.dumps({
- "error": "Both --model and --prompt required for single mode",
- "type": "argument_error"
- }), flush=True)
- sys.exit(1)
-
- # Load model
- result = engine.load_model(args.model)
- print(json.dumps(result), flush=True)
-
- if not result.get("success"):
- sys.exit(1)
-
- # Generate
- for output in engine.generate(
- prompt=args.prompt,
- max_tokens=args.max_tokens,
- temperature=args.temperature,
- top_p=args.top_p,
- stream=args.stream
- ):
- print(json.dumps(output), flush=True)
-
- else:
- # Interactive mode - read commands from stdin
- print(json.dumps({"type": "ready", "message": "MLX Inference Engine ready"}), flush=True)
-
- for line in sys.stdin:
- try:
- command = json.loads(line.strip())
- cmd_type = command.get("type")
-
- if cmd_type == "load_model":
- result = engine.load_model(command["model_path"])
- print(json.dumps(result), flush=True)
-
- elif cmd_type == "generate":
- for output in engine.generate(
- prompt=command["prompt"],
- max_tokens=command.get("max_tokens", 2048),
- temperature=command.get("temperature", 0.7),
- top_p=command.get("top_p", 0.9),
- repetition_penalty=command.get("repetition_penalty", 1.0),
- stream=command.get("stream", True)
- ):
- print(json.dumps(output), flush=True)
-
- elif cmd_type == "unload_model":
- result = engine.unload_model()
- print(json.dumps(result), flush=True)
-
- elif cmd_type == "exit":
- print(json.dumps({"type": "exit", "message": "Shutting down"}), flush=True)
- break
-
- else:
- print(json.dumps({
- "error": f"Unknown command type: {cmd_type}",
- "type": "command_error"
- }), flush=True)
-
- except json.JSONDecodeError as e:
- print(json.dumps({
- "error": f"Invalid JSON: {e}",
- "type": "json_error"
- }), flush=True)
-
- except Exception as e:
- print(json.dumps({
- "error": str(e),
- "type": "error"
- }), flush=True)
-
-
-if __name__ == "__main__":
- main()
diff --git a/Python/rag_system.py b/Python/rag_system.py
deleted file mode 100644
index 4e59f06..0000000
--- a/Python/rag_system.py
+++ /dev/null
@@ -1,513 +0,0 @@
-#!/usr/bin/env python3
-"""
-RAG (Retrieval-Augmented Generation) System
-Handles codebase indexing, embeddings, and semantic search.
-"""
-
-import sys
-import json
-import argparse
-from pathlib import Path
-from typing import Dict, Any, List, Optional
-import hashlib
-
-try:
- from sentence_transformers import SentenceTransformer
- import chromadb
- from chromadb.config import Settings
- import numpy as np
- DEPENDENCIES_AVAILABLE = True
-except ImportError:
- DEPENDENCIES_AVAILABLE = False
- print(json.dumps({
- "error": "RAG dependencies not installed. Install with: pip install sentence-transformers chromadb",
- "type": "import_error"
- }), flush=True)
- sys.exit(1)
-
-
-class RAGSystem:
- """Manages codebase indexing and semantic search."""
-
- def __init__(self, db_path: str = "~/.mlx/chroma_db", model_name: str = "all-MiniLM-L6-v2"):
- """
- Initialize RAG system.
-
- Args:
- db_path: Path to ChromaDB database
- model_name: Sentence transformer model name
- """
- self.db_path = Path(db_path).expanduser()
- self.db_path.mkdir(parents=True, exist_ok=True)
-
- # Initialize embedding model
- self.embedding_model = SentenceTransformer(model_name)
-
- # Initialize ChromaDB
- self.client = chromadb.PersistentClient(
- path=str(self.db_path),
- settings=Settings(anonymized_telemetry=False)
- )
-
- # Get or create collection
- self.collection = self.client.get_or_create_collection(
- name="codebase",
- metadata={"description": "Code files and documentation"}
- )
-
- def index_directory(
- self,
- directory_path: str,
- extensions: Optional[List[str]] = None,
- exclude_patterns: Optional[List[str]] = None
- ) -> Dict[str, Any]:
- """
- Index all code files in a directory.
-
- Args:
- directory_path: Path to directory to index
- extensions: File extensions to include (e.g., [".swift", ".py"])
- exclude_patterns: Patterns to exclude (e.g., ["test", "build"])
-
- Returns:
- Dict with indexing statistics
- """
- try:
- directory = Path(directory_path).expanduser()
-
- if not directory.exists():
- return {
- "success": False,
- "error": f"Directory does not exist: {directory}",
- "type": "path_error"
- }
-
- # Default extensions if none provided
- if extensions is None:
- extensions = [".swift", ".m", ".h", ".py", ".js", ".ts", ".json", ".md"]
-
- # Default exclude patterns
- if exclude_patterns is None:
- exclude_patterns = [
- "build", "Build", "DerivedData", ".build",
- "node_modules", ".git", "__pycache__",
- "test", "Test", "tests", "Tests"
- ]
-
- indexed_count = 0
- skipped_count = 0
- error_count = 0
-
- # Find all files
- for file_path in directory.rglob("*"):
- # Skip directories
- if not file_path.is_file():
- continue
-
- # Check extension
- if file_path.suffix not in extensions:
- skipped_count += 1
- continue
-
- # Check exclude patterns
- if any(pattern in str(file_path) for pattern in exclude_patterns):
- skipped_count += 1
- continue
-
- # Index file
- try:
- self.index_file(str(file_path))
- indexed_count += 1
-
- # Progress update every 10 files
- if indexed_count % 10 == 0:
- print(json.dumps({
- "type": "progress",
- "indexed": indexed_count,
- "current_file": str(file_path.name)
- }), flush=True)
-
- except Exception as e:
- error_count += 1
- print(json.dumps({
- "type": "warning",
- "message": f"Failed to index {file_path}: {e}"
- }), flush=True)
-
- return {
- "success": True,
- "indexed": indexed_count,
- "skipped": skipped_count,
- "errors": error_count,
- "directory": str(directory)
- }
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "indexing_error"
- }
-
- def index_file(self, file_path: str) -> Dict[str, Any]:
- """
- Index a single file.
-
- Args:
- file_path: Path to file
-
- Returns:
- Dict with indexing result
- """
- try:
- file_path = Path(file_path).expanduser()
-
- if not file_path.exists():
- return {
- "success": False,
- "error": f"File does not exist: {file_path}",
- "type": "path_error"
- }
-
- # Read file content
- try:
- with open(file_path, 'r', encoding='utf-8') as f:
- content = f.read()
- except UnicodeDecodeError:
- # Skip binary files
- return {
- "success": False,
- "error": "Binary file, skipped",
- "type": "encoding_error"
- }
-
- # Skip empty files
- if not content.strip():
- return {
- "success": False,
- "error": "Empty file, skipped",
- "type": "empty_file"
- }
-
- # Generate file ID from path hash
- file_id = hashlib.md5(str(file_path).encode()).hexdigest()
-
- # Split into chunks for large files
- chunks = self._split_into_chunks(content, max_chunk_size=1000)
-
- # Generate embeddings
- embeddings = self.embedding_model.encode(chunks, show_progress_bar=False)
-
- # Store in ChromaDB
- for i, (chunk, embedding) in enumerate(zip(chunks, embeddings)):
- chunk_id = f"{file_id}_{i}"
-
- self.collection.add(
- ids=[chunk_id],
- embeddings=[embedding.tolist()],
- documents=[chunk],
- metadatas=[{
- "file_path": str(file_path),
- "file_name": file_path.name,
- "file_extension": file_path.suffix,
- "chunk_index": i,
- "total_chunks": len(chunks)
- }]
- )
-
- return {
- "success": True,
- "file_path": str(file_path),
- "chunks": len(chunks)
- }
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "indexing_error"
- }
-
- def search(
- self,
- query: str,
- n_results: int = 5,
- file_extensions: Optional[List[str]] = None
- ) -> Dict[str, Any]:
- """
- Search for relevant code snippets.
-
- Args:
- query: Search query
- n_results: Number of results to return
- file_extensions: Filter by file extensions
-
- Returns:
- Dict with search results
- """
- try:
- # Generate query embedding
- query_embedding = self.embedding_model.encode([query], show_progress_bar=False)[0]
-
- # Build where filter
- where_filter = None
- if file_extensions:
- where_filter = {
- "file_extension": {"$in": file_extensions}
- }
-
- # Search ChromaDB
- results = self.collection.query(
- query_embeddings=[query_embedding.tolist()],
- n_results=n_results,
- where=where_filter
- )
-
- # Format results
- formatted_results = []
- for i in range(len(results['ids'][0])):
- formatted_results.append({
- "id": results['ids'][0][i],
- "document": results['documents'][0][i],
- "metadata": results['metadatas'][0][i],
- "distance": results['distances'][0][i] if 'distances' in results else None
- })
-
- return {
- "success": True,
- "query": query,
- "results": formatted_results,
- "count": len(formatted_results)
- }
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "search_error"
- }
-
- def get_context_for_query(
- self,
- query: str,
- n_results: int = 3,
- max_context_length: int = 4000
- ) -> str:
- """
- Get relevant context for a query to inject into prompts.
-
- Args:
- query: User query
- n_results: Number of code snippets to retrieve
- max_context_length: Maximum context length in characters
-
- Returns:
- Formatted context string
- """
- search_result = self.search(query, n_results=n_results)
-
- if not search_result["success"]:
- return ""
-
- context_parts = []
- current_length = 0
-
- for result in search_result["results"]:
- metadata = result["metadata"]
- document = result["document"]
-
- # Format context entry
- entry = f"\n# From {metadata['file_name']} ({metadata['file_extension']})\n```\n{document}\n```\n"
-
- # Check if adding this would exceed max length
- if current_length + len(entry) > max_context_length:
- break
-
- context_parts.append(entry)
- current_length += len(entry)
-
- return "\n".join(context_parts)
-
- def clear_collection(self) -> Dict[str, Any]:
- """Clear all indexed data."""
- try:
- self.client.delete_collection("codebase")
- self.collection = self.client.get_or_create_collection(
- name="codebase",
- metadata={"description": "Code files and documentation"}
- )
-
- return {
- "success": True,
- "message": "Collection cleared successfully"
- }
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "clear_error"
- }
-
- def get_stats(self) -> Dict[str, Any]:
- """Get statistics about indexed data."""
- try:
- count = self.collection.count()
-
- # Get unique files
- all_metadata = self.collection.get()
- unique_files = set()
- if all_metadata and all_metadata['metadatas']:
- unique_files = {m['file_path'] for m in all_metadata['metadatas']}
-
- return {
- "success": True,
- "total_chunks": count,
- "unique_files": len(unique_files),
- "db_path": str(self.db_path)
- }
-
- except Exception as e:
- return {
- "success": False,
- "error": str(e),
- "type": "stats_error"
- }
-
- def _split_into_chunks(self, text: str, max_chunk_size: int = 1000) -> List[str]:
- """
- Split text into chunks for embedding.
-
- Args:
- text: Text to split
- max_chunk_size: Maximum chunk size in characters
-
- Returns:
- List of text chunks
- """
- # Split by lines first
- lines = text.split('\n')
-
- chunks = []
- current_chunk = []
- current_size = 0
-
- for line in lines:
- line_size = len(line)
-
- # If single line exceeds max size, split it
- if line_size > max_chunk_size:
- # Save current chunk if any
- if current_chunk:
- chunks.append('\n'.join(current_chunk))
- current_chunk = []
- current_size = 0
-
- # Split long line by words
- words = line.split()
- word_chunk = []
- word_size = 0
-
- for word in words:
- if word_size + len(word) + 1 > max_chunk_size:
- chunks.append(' '.join(word_chunk))
- word_chunk = [word]
- word_size = len(word)
- else:
- word_chunk.append(word)
- word_size += len(word) + 1
-
- if word_chunk:
- chunks.append(' '.join(word_chunk))
-
- # Normal line processing
- elif current_size + line_size + 1 > max_chunk_size:
- # Save current chunk
- chunks.append('\n'.join(current_chunk))
- current_chunk = [line]
- current_size = line_size
- else:
- current_chunk.append(line)
- current_size += line_size + 1
-
- # Add remaining chunk
- if current_chunk:
- chunks.append('\n'.join(current_chunk))
-
- return chunks
-
-
-def main():
- """Main entry point for CLI usage."""
- parser = argparse.ArgumentParser(description="RAG System for Code")
-
- subparsers = parser.add_subparsers(dest="command", help="Command to execute")
-
- # Index command
- index_parser = subparsers.add_parser("index", help="Index a directory")
- index_parser.add_argument("directory", type=str, help="Directory to index")
- index_parser.add_argument("--extensions", type=str, nargs="+", help="File extensions to include")
- index_parser.add_argument("--exclude", type=str, nargs="+", help="Patterns to exclude")
-
- # Search command
- search_parser = subparsers.add_parser("search", help="Search indexed code")
- search_parser.add_argument("query", type=str, help="Search query")
- search_parser.add_argument("--n-results", type=int, default=5, help="Number of results")
- search_parser.add_argument("--extensions", type=str, nargs="+", help="Filter by extensions")
-
- # Context command
- context_parser = subparsers.add_parser("context", help="Get context for query")
- context_parser.add_argument("query", type=str, help="Query")
- context_parser.add_argument("--n-results", type=int, default=3, help="Number of results")
- context_parser.add_argument("--max-length", type=int, default=4000, help="Max context length")
-
- # Stats command
- stats_parser = subparsers.add_parser("stats", help="Get statistics")
-
- # Clear command
- clear_parser = subparsers.add_parser("clear", help="Clear all indexed data")
-
- args = parser.parse_args()
-
- # Initialize RAG system
- rag = RAGSystem()
-
- if args.command == "index":
- result = rag.index_directory(
- directory_path=args.directory,
- extensions=args.extensions,
- exclude_patterns=args.exclude
- )
- print(json.dumps(result, indent=2), flush=True)
-
- elif args.command == "search":
- result = rag.search(
- query=args.query,
- n_results=args.n_results,
- file_extensions=args.extensions
- )
- print(json.dumps(result, indent=2), flush=True)
-
- elif args.command == "context":
- context = rag.get_context_for_query(
- query=args.query,
- n_results=args.n_results,
- max_context_length=args.max_length
- )
- print(context, flush=True)
-
- elif args.command == "stats":
- result = rag.get_stats()
- print(json.dumps(result, indent=2), flush=True)
-
- elif args.command == "clear":
- result = rag.clear_collection()
- print(json.dumps(result, indent=2), flush=True)
-
- else:
- parser.print_help()
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/Python/setup.sh b/Python/setup.sh
index 17d81d8..f1df683 100755
--- a/Python/setup.sh
+++ b/Python/setup.sh
@@ -25,6 +25,9 @@ echo " pip is available ✓"
echo ""
# Install dependencies
+# NOTE: version specifiers MUST be quoted. Unquoted `pkg>=1.0` is parsed by the shell
+# as `pkg` plus an output redirect into a file named `=1.0` (which is how the stray
+# Python/=0.0.10 etc. files were created).
echo "📦 Installing Python dependencies..."
echo " This may take a few minutes..."
echo ""
@@ -32,16 +35,16 @@ echo ""
/usr/bin/python3 -m pip install --user --upgrade pip
echo " Installing MLX framework..."
-/usr/bin/python3 -m pip install --user mlx>=0.0.10 mlx-lm>=0.0.10
+/usr/bin/python3 -m pip install --user "mlx>=0.0.10" "mlx-lm>=0.0.10"
echo " Installing HuggingFace tools..."
-/usr/bin/python3 -m pip install --user huggingface-hub>=0.19.0 transformers>=4.35.0
+/usr/bin/python3 -m pip install --user "huggingface-hub>=0.19.0" "transformers>=4.35.0"
echo " Installing RAG dependencies..."
-/usr/bin/python3 -m pip install --user sentence-transformers>=2.2.0 chromadb>=0.4.0
+/usr/bin/python3 -m pip install --user "sentence-transformers>=2.2.0" "chromadb>=0.4.0"
echo " Installing utilities..."
-/usr/bin/python3 -m pip install --user numpy>=1.24.0 tqdm>=4.65.0
+/usr/bin/python3 -m pip install --user "numpy>=1.24.0" "tqdm>=4.65.0"
echo ""
echo "✅ Installation complete!"
diff --git a/README.md b/README.md
index 8fa2f31..9f439b9 100644
--- a/README.md
+++ b/README.md
@@ -5,11 +5,11 @@



-
+
A local AI coding assistant for macOS, powered by Apple MLX. No cloud. No subscriptions. No data leaving your machine.
-MLX Code runs language models directly on Apple Silicon using the [mlx-swift](https://github.com/ml-explore/mlx-swift) framework. It provides a chat interface with 14 built-in tools that can read files, search code, run shell commands, build Xcode projects, manage Git repos, and interact with GitHub -- all driven by a local model running on your GPU.
+MLX Code runs language models directly on Apple Silicon using [mlx-swift](https://github.com/ml-explore/mlx-swift) and [mlx-swift-lm](https://github.com/ml-explore/mlx-swift-lm) 3.x. It provides a chat interface with 14 built-in tools that can read files, search code, run shell commands, build Xcode projects, manage Git repos, and interact with GitHub -- all driven by a local model running on your GPU.
Written by Jordan Koch.
@@ -59,6 +59,8 @@ graph TB
subgraph Engine["Inference Engine"]
MLXService["MLXService (actor)"]
+ Generator["InferenceGenerator (protocol)"]
+ MLXLM["mlx-swift-lm 3.x ModelContainer"]
ContextManager["ContextManager (actor)"]
ContextBudget["70% messages / 20% project / 10% summary"]
UserMemories["UserMemories (actor)"]
@@ -81,6 +83,7 @@ graph TB
Views --> ViewModels
ViewModels --> Tools
Tools --> Engine
+ MLXService --> Generator --> MLXLM
Engine --> Security
Views -.-> External
```
@@ -100,19 +103,67 @@ sequenceDiagram
ChatView->>ChatViewModel: Send message
ChatViewModel->>ContextManager: Assemble context (budget-aware)
ContextManager-->>ChatViewModel: System prompt + history + project context
- ChatViewModel->>MLXService: Generate (AsyncStream)
- MLXService-->>ChatViewModel: Stream tokens
- ChatViewModel->>ChatViewModel: Detect tool call in output
- ChatViewModel->>ToolRegistry: Execute tool
- ToolRegistry-->>ChatViewModel: Tool result
- ChatViewModel->>MLXService: Continue generation with result
+ ChatViewModel->>ToolRegistry: Build native ToolSpecs
+ ChatViewModel->>MLXService: chatCompletion(messages, tools) in a cancellable Task
+ MLXService-->>ChatViewModel: Stream chunks + native tool calls (rendered as blocks)
+ ChatViewModel->>ChatViewModel: Extract tool calls (native or text fallback)
+ ChatViewModel->>ToolRegistry: Execute approved tools
+ ToolRegistry-->>ChatViewModel: Tool results
+ ChatViewModel->>MLXService: Continue generation with results
MLXService-->>ChatView: Final response
+ User-->>ChatViewModel: Stop (cancels the Task; MLXService ends the token stream)
+```
+
+### Inference Path (mlx-swift-lm 3.x)
+
+```mermaid
+flowchart LR
+ subgraph App["MLX Code"]
+ VM["ChatViewModel
generationTask"]
+ Settings["AppSettings
KV cache: bits / max size / prefill step"]
+ Params["ModelParameters
temp, topP, topK, minP,
repetition penalty + context"]
+ Svc["MLXService (actor)
busy flag, cancellation,
tool-call mapping"]
+ Mapper["GenerationParameterMapper"]
+ Specs["ToolSpecBuilder
ToolRegistry → [ToolSpec]"]
+ Fmt["NativeToolCallFormatter
toolCall → <tool>{json}</tool>"]
+ end
+ subgraph LM["mlx-swift-lm 3.32"]
+ Loader["LLMModelFactory.loadContainer(from: URL,
using: #huggingFaceTokenizerLoader())"]
+ Container["ModelContainer.prepare / generate"]
+ Stream["AsyncStream<Generation>
.chunk / .toolCall / .info"]
+ end
+ subgraph HF["Hugging Face"]
+ Hub["HubClient.downloadSnapshot
*.safetensors *.json *.jinja *.txt *.model"]
+ Tok["swift-transformers Tokenizers
(chat template)"]
+ end
+
+ Hub --> Loader
+ Tok --> Loader
+ VM --> Svc
+ Specs --> Svc
+ Params --> Mapper
+ Settings --> Mapper
+ Mapper -->|GenerateParameters| Container
+ Svc --> Container --> Stream
+ Stream -->|chunks| Svc
+ Stream -->|tool calls| Fmt --> Svc
+ Svc -->|stream to UI| VM
+ VM -. "Stop: Task.cancel()" .-> Svc
```
---
## Features
+### Native On-Device Inference (mlx-swift-lm 3.x)
+
+- **Real Stop** -- Stop cancels the generation task; token generation ends inside mlx-swift-lm and the next request starts immediately. The partial answer is kept.
+- **Native tool calling** -- the tool registry is sent to the model's chat template as `ToolSpec`s, and `Generation.toolCall` events (Qwen, Llama, Mistral, Gemma, Harmony and more formats parsed by mlx-swift-lm) feed the existing approval flow -- several calls per turn are supported. The `…` text protocol remains as a fallback.
+- **KV-cache controls** -- Settings → Model: KV quantization (none / 8-bit / 4-bit), max KV size (rotating cache) and prefill step size.
+- **Full sampling controls** -- temperature, top-p, top-k, min-p, repetition penalty (default 1.1) and repetition context size are all passed to the sampler.
+- **Complete downloads** -- chat templates (`*.jinja`), BPE merges (`*.txt`) and SentencePiece models (`*.model`) are fetched along with weights and configs.
+- **Context detection** -- the context window is read from `config.json`, including nested `text_config` (Qwen3.5/3.6, Gemma 4, Devstral 2).
+
### 14 Built-in Tools
| Tool | Purpose | Tier |
@@ -189,12 +240,18 @@ Uses [mlx-community](https://huggingface.co/mlx-community) models from Hugging F
| Model | Size | Context | Best for |
|---|---|---|---|
-| **Qwen 2.5 7B** (default) | ~4 GB | 32K | General coding, tool calling |
-| Mistral 7B v0.3 | ~4 GB | 32K | Versatile, instructions |
-| DeepSeek Coder 6.7B | ~4 GB | 16K | Code-specific tasks |
-| Qwen 2.5 14B | ~8 GB | 32K | Best quality (16GB+ RAM) |
+| **Qwen3.5 9B** (default) | ~5 GB | 256K | General coding, native tool calling (16 GB+ RAM) |
+| Qwen3-Coder 30B-A3B (MoE) | ~17 GB | 256K | Agentic coding (32 GB+ RAM) |
+| Devstral Small 2 24B | ~14 GB | 384K | Software-engineering agent tasks (32 GB+ RAM) |
+| Qwen3.6 35B-A3B (MoE) | ~20 GB | 256K | High quality at MoE speed (32 GB+ RAM) |
+| Qwen3.6 27B | ~16 GB | 256K | Best quality, slower (32 GB+ RAM) |
+| Gemma 4 E4B | ~4 GB | 128K | Efficient general model |
+| Qwen3.5 2B | ~1.5 GB | 256K | Fast edits on 8 GB Macs |
+| Qwen 2.5 7B (legacy) | ~4 GB | 32K | Kept for existing installs |
+
+All entries are `mlx-community` 4-bit repos whose architectures are supported by mlx-swift-lm 3.32. Long contexts need a lot of memory -- use the KV-cache settings to cap or quantize it.
-Models download automatically via native Hub Swift API. Custom models from any mlx-community repository are supported. All models must be **SafeTensors** format -- PyTorch pickle files are rejected.
+Models download automatically via the native Swift Hugging Face client (`HubClient`). Custom models from any mlx-community repository are supported. All models must be **SafeTensors** format -- PyTorch pickle files are rejected.
---
@@ -274,7 +331,7 @@ Local HTTP API on port **37422** (loopback only).
- **Apple Silicon** (M1, M2, M3, M4)
- **8 GB RAM** minimum (16 GB recommended)
- **No Python required** -- inference and downloads are pure Swift
-- **Xcode 15+** -- only needed for the Source Editor Extension
+- **Xcode 26+** -- only needed to build from source (mlx-swift-lm 3.x uses swift-tools 6.2 and Swift macros)
## Installation
@@ -294,7 +351,7 @@ Local HTTP API on port **37422** (loopback only).
### From Source
-Requires **Xcode 15 or later**. Because the app bundles **MLX** for on-device LLM inference, the build
+Requires **Xcode 26 or later**. Because the app bundles **MLX** for on-device LLM inference, the build
compiles Metal GPU shaders, which needs Apple's **Metal Toolchain** — a component recent Xcode versions
no longer ship by default. Install it once:
@@ -308,10 +365,13 @@ Then build:
```bash
git clone git@github.com:kochj23/MLXCode.git
cd MLXCode
-open "MLX Code.xcodeproj" # Xcode resolves Swift packages on first open (mlx-swift, mlx-swift-examples, …)
-# Build & run: Cmd+R (Xcode 15+, macOS 14.0+ target)
+open "MLX Code.xcodeproj" # Xcode resolves Swift packages on first open (mlx-swift, mlx-swift-lm, swift-huggingface, swift-transformers)
+# Build & run: Cmd+R (Xcode 26+, macOS 14.0+ target). Approve the MLXHuggingFace macros when Xcode asks.
```
+Command-line builds must pass `-skipMacroValidation` (mlx-swift-lm's `#huggingFaceTokenizerLoader()` is a Swift macro).
+Pinned dependency versions are committed in `MLX Code.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved`.
+
> Skipping the Metal Toolchain step produces a wall of `CompileMetalFile … cannot execute tool 'metal'
> due to missing Metal Toolchain` errors from the `mlx-swift` dependency. That's the missing component,
> not a problem with the project.
@@ -349,15 +409,38 @@ open "MLX Code.xcodeproj" # Xcode resolves Swift packages on first open (mlx-s
## Test Suite
-618 tests across 27 test files covering models, services, security, context budgeting, build parsing, Keychain, tool registry, JSON repair, prompt templates, and source-level security scanning.
+574 tests across 28 test files covering models, services, security, context budgeting, build parsing, Keychain, tool registry, JSON repair, prompt templates, source-level security scanning, and the inference engine (parameter mapping, Stop/cancellation, native tool calls, download patterns, catalog, context parsing) via a mock generator -- no model download needed.
```bash
xcodebuild -project "MLX Code.xcodeproj" -scheme "MLX Code" \
- -destination "platform=macOS" test
+ -destination "platform=macOS" -skipMacroValidation test
+```
+
+Optional real-model integration test (skipped by default):
+
+```bash
+TEST_RUNNER_MLXCODE_INTEGRATION=1 TEST_RUNNER_MLXCODE_MODEL_PATH=/path/to/mlx-model \
+ xcodebuild -project "MLX Code.xcodeproj" -scheme "MLX Code" -destination "platform=macOS" \
+ -skipMacroValidation -only-testing:"MLX Code Tests/MLXServiceTests/testIntegrationLoadAndStreamRealModel" test
```
---
+## Version History
+
+| Version | Date | Highlights |
+|---|---|---|
+| 6.4.0 | 2026-11 (unreleased) | mlx-swift-lm 3.32 / mlx-swift 0.32.3, real Stop, native tool calling, KV-cache settings, min-p, model catalog refresh (Qwen3.5/3.6, Qwen3-Coder, Gemma 4, Devstral 2), complete tokenizer downloads, dead Python scripts removed; multi-model load balancer (local + frontier + optional Nova) |
+| 6.3.0 | 2026-03-04 | Native model downloads, tool-call reliability, Xcode Source Editor Extension |
+| 6.1.0 | 2026-02-26 | Security hardening and code-quality audit |
+| 5.0.0 | 2026-02-19 | Focused rewrite: removed media generation, RAG and auxiliary panels |
+| 4.0.0 | 2026-02-19 | Native mlx-swift inference |
+| 1.0.0 | 2025-11-18 | Initial release |
+
+See [CHANGELOG.md](CHANGELOG.md) for details.
+
+---
+
## License
MIT License -- Copyright 2025-2026 Jordan Koch
diff --git a/add_python_scripts.rb b/add_python_scripts.rb
deleted file mode 100755
index 2a1c10e..0000000
--- a/add_python_scripts.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-#!/usr/bin/env ruby
-require 'xcodeproj'
-
-project_path = 'MLX Code.xcodeproj'
-project = Xcodeproj::Project.open(project_path)
-
-# Get the main target
-target = project.targets.first
-
-# Get or create Python group
-python_group = project.main_group.find_subpath('Python', true)
-python_group.set_source_tree('SOURCE_ROOT')
-
-# Python scripts to add (relative to project directory)
-scripts = [
- 'Python/huggingface_downloader.py',
- 'Python/mlx_inference.py',
- 'Python/rag_system.py'
-]
-
-scripts.each do |script_path|
- # Add file reference
- file_ref = python_group.new_reference(script_path)
- file_ref.last_known_file_type = 'text.script.python'
-
- # Add to Copy Bundle Resources phase
- target.add_resources([file_ref])
-
- puts "Added #{script_path} to project"
-end
-
-project.save
-
-puts "\n✅ Python scripts added to Xcode project"
-puts "They will now be bundled in the app's Resources folder"