A private, local-first AI assistant for macOS and iOS. Built with Swift, SwiftUI and MLX. Language models run entirely on your device, and you can fine-tune them there too, on a Mac or on an iPhone.
- No cloud APIs, no accounts, no telemetry. The only network traffic is searching and downloading models from Hugging Face.
- Works fully offline once a model is downloaded.
- On-device LoRA / QLoRA fine-tuning with the MLX Swift training loop, from dataset file to a usable adapter in a few taps.
- Optional local memory that recalls relevant facts from earlier chats, with no embedding model and no network.
- Optional terminal access on macOS: the model can ask to run shell commands, and you approve each one.
- Interface in English, Russian, Ukrainian and Polish.
- Features
- Requirements
- Build and run
- Quick start
- Fine-tuning in depth
- Memory budget and runtime settings
- Local memory
- Terminal access (macOS)
- Where your data lives
- Architecture
- Testing
- Troubleshooting
- Limitations and known issues
- Roadmap
- License
- Credits
- Streaming chat with MLX models on Apple Silicon. Tokens appear as they are generated, and the Stop button cancels generation immediately.
- Multi-byte characters (Cyrillic, emoji) that get split across tokens are buffered until complete, so you never see broken replacement glyphs in a streamed reply.
- A live token counter shows how much of the model's context window the conversation uses. It is an estimate (about 4 characters per token, never below the word count), not the model's real tokenizer, so it stays instant and works with every backend.
- Only the most recent messages are sent to the model: the last 24 on macOS and the last 8 on iOS, to keep memory use predictable.
- Reply length: 512 tokens by default on macOS (384 on iOS). The "continue response" option raises this to 4096 on macOS (2048 on iOS).
- The system prompt is editable in Settings. If a loaded adapter was trained with its own system prompt, that prompt is used automatically so the adapter behaves the way it was trained.
- Search Hugging Face from inside the app. MLX searches put
mlx-communityrepositories first. - A curated quick-pick list of models that are comfortable on an 8 GB device (Llama 3.2 3B, Qwen2.5 3B and 7B, Phi-3.5 mini, Gemma 2 2B, all 4-bit).
- Downloads show byte-level progress. MLX models are downloaded file by file (config, tokenizer, weights). On iOS the screen is kept awake while a download runs.
- Keep several models installed, switch between them, and delete models or adapters with a confirmation.
- Trained adapters are listed next to the models, with the base model they belong to.
- Trains adapter weights only. The base model is never modified.
- QLoRA is automatic when the base model is quantized (for example
mlx-community/...-4bit). On a full-precision base it is plain LoRA. The app reads the quantization from the model'sconfig.jsonand tells you which one it is running. - Uses the MLX Swift training loop with a validation set and the Adam optimizer. Learning rate, LoRA layers, batch size and iterations are configurable.
- Datasets: one
.json,.jsonlor.txtfile, in any of six schemas (text,prompt/completion,instruction/input/output,question/answer,input/output,messages). The file is shuffled and split into training and validation parts automatically. - Examples are rendered as ChatML (Qwen style) with an end-of-turn token so the model learns where to stop.
- Live progress: step, loss, speed and estimated time remaining. Stopping a run still saves the adapter trained so far. Weights are also checkpointed periodically during training.
- The chat model is unloaded before training starts to free memory.
- An optional extra copy of the finished adapter can be exported to a folder you choose.
- Tested with Qwen2.5-3B-Instruct (4-bit) on an 8 GB MacBook Air and on an iPhone 16 Pro Max.
Details and tuning advice are in Fine-tuning in depth.
- Remembers finished question and answer pairs on the device (up to 200) and adds the most relevant ones to new requests.
- Retrieval is lexical: cosine similarity over word and character-trigram features. No embedding model is needed, so memory works in any UI language and even before a model is loaded.
- Can be switched off or cleared in Settings.
See Local memory for how it works and where it falls short.
- Off by default and off again on every launch. The setting is deliberately never saved.
- The model asks for a command by writing
<terminal>command</terminal>. LocAI shows it, you approve or deny it, LocAI runs it with/bin/zsh, and the output goes back to the model. - Each command has a timeout, no keyboard input and capped output. Process trees are terminated on timeout or when you press Stop.
See Terminal access (macOS) for the protocol and the safety model.
- Native SwiftUI with the Observation framework, on macOS and iOS from one codebase.
- Four tabs: Chat, Models, Settings and Tuning.
- UI languages: English, Russian (Русский), Ukrainian (Українська) and Polish (Polski). The default follows the device: Russian on a Russian-language system, English otherwise. Missing translations fall back to English.
- Models, adapters, chat history and memory stay on the device.
- The app's only network access is the Hugging Face API and file downloads (
huggingface.co). There are no analytics and no accounts.
- An Apple Silicon Mac, or an iPhone / iPad with an Apple Silicon chip.
- Xcode with the macOS 26 / iOS 26 SDKs. Current deployment targets are macOS 26.0 and iOS 26.5 (both adjustable in the project settings).
- MLX needs a Metal GPU, so the iOS Simulator is not supported. Use a Mac or a real device.
- On iOS the app uses the Increased Memory Limit capability (see
LocAI/LocAI.entitlements), which matters for loading 3B-class models. - Free disk space: roughly 2 GB per 3B 4-bit model, about 4 GB or more for 7B.
Rough memory guide:
| Device RAM | Comfortable choice |
|---|---|
| 8 GB (MacBook Air, iPhone Pro) | 1.5B to 3B models in 4-bit, batch size 1 for training |
| 16 GB | Up to 7B in 4-bit |
| 24 GB and more | Larger models and longer contexts |
git clone https://github.com/tarsonov-cdv/LocAI.git
cd LocAI
open LocAI.xcodeproj- Wait for Xcode to resolve the Swift packages (
mlx-swift-examplesand its dependencies). The first resolve can take a while. - Select the
LocAItarget, open Signing & Capabilities, and choose your own development team. - Choose My Mac or a connected iPhone / iPad as the run destination.
- Press Run.
Notes:
- The macOS build is configured to run without the App Sandbox so that terminal commands can see your files. If you do not need the terminal tool you can enable the sandbox again. The app detects it and keeps working, but shell commands then only see the app container.
- If an earlier sandboxed build already downloaded models, an unsandboxed build keeps using that existing folder instead of silently losing them.
- If you see the message "The MLX backend package is not linked", the MLX products are missing from the target. Make sure
MLXLLM,MLXLMCommon,MLXOptimizersandTokenizersare linked.
- Open the Models tab, pick a model from the quick-pick list (Qwen2.5-3B-Instruct 4-bit is a good start on 8 GB devices) and download it.
- Select the downloaded model and load it. The header shows the model, the backend, and any adapter applied.
- Open Chat and write a message. The token counter shows context use.
- Optional: open Settings to change the memory budget, the system prompt, the language, memory and terminal options.
- Optional: open Tuning, choose a dataset file, a base model and a system prompt, set the parameters and start training. When it finishes, pick the new adapter in the Models tab or press Use in chat.
Suggested first fine-tune on an 8 GB device: a 1.5B to 3B model in 4-bit, batch size 1, 4 to 8 LoRA layers, 100 iterations, learning rate 1e-5.
| Model | Approx. size | Notes |
|---|---|---|
| Llama 3.2 3B Instruct 4-bit | ~2 GB | Fast general assistant |
| Qwen2.5 3B Instruct 4-bit | ~2 GB | Multilingual; used for fine-tuning tests |
| Phi-3.5 Mini Instruct 4-bit | ~2 GB | Lightweight reasoning |
| Gemma 2 2B IT 4-bit | ~1.5 GB | Small and quick |
| Qwen2.5 7B Instruct 4-bit | ~4 GB+ | Higher quality; needs more memory |
All of these are MLX repositories on Hugging Face (mlx-community/...).
- The dataset file, model folder and hyperparameters are validated. Errors are reported in plain language (missing file, folder without
config.json, non-positive values). - The dataset is parsed into examples, shuffled, and split into a training part and a validation part.
- The chat model is unloaded and the base model is loaded for training.
- LoRA layers are added to the attention layers of the last N transformer blocks (N is "LoRA layers").
- The MLX Swift training loop runs with the Adam optimizer and a fixed learning rate (no schedule). It reports progress, validates periodically and checkpoints the adapter weights.
- The adapter and its metadata are written to disk. If you stopped the run early, the adapter trained so far is saved and the metadata records the real number of completed iterations.
One file, one of three extensions. In .jsonl every line is its own JSON value, and malformed lines are skipped. In .json the file can be an array of examples, or an object whose data or examples key holds the array.
| Schema | Example | Becomes |
|---|---|---|
text |
{"text": "Any text"} |
The text as is |
prompt + completion |
{"prompt": "Hi", "completion": "Hello"} |
One user turn and one assistant turn |
instruction (+ input) + output |
{"instruction": "Translate", "input": "cat", "output": "кіт"} |
User turn is instruction and input joined by a newline |
question + answer |
{"question": "2+2?", "answer": "4"} |
One user turn and one assistant turn |
input + output |
{"input": "Hi", "output": "Hello"} |
One user turn and one assistant turn |
messages |
{"messages": [{"role": "user", "content": "Hi"}, {"role": "assistant", "content": "Hello"}]} |
A whole multi-turn conversation as one example |
| plain strings | ["one example", "another"] |
Each non-empty string as is |
Other details:
.txtfiles use one example per non-empty line, used as is.- In
messages, only the rolessystem,userandassistantare kept, and messages with empty content are dropped. A conversation with nothing left is skipped. - The system prompt from the Tuning tab is prepended to chat-style examples. If a
messagesconversation already has its ownsystemmessage, that one wins and the Tuning prompt is not added. - Plain
textexamples and.txtlines are not wrapped in ChatML.
Chat-style examples become ChatML, and every turn ends with <|im_end|>:
<|im_start|>system
Answer briefly and informally.<|im_end|>
<|im_start|>user
Hi<|im_end|>
<|im_start|>assistant
Hello<|im_end|>
This format matches Qwen-style models. See Limitations for what that means for other model families.
- The examples are shuffled first, so the validation part is a random sample and not simply the tail of your file.
- Validation size is
max(batch size, 10% of examples). Training gets the rest. - Both parts must hold at least one full batch (the MLX batch iterator cannot work with fewer examples than the batch size). If the dataset is too small the app tells you how many examples it found and how many it needs.
| Setting | Default | Notes |
|---|---|---|
| LoRA layers | 4 | Applied to the last N blocks. More layers means more capacity and more memory. Try 4 to 8 on 8 GB devices |
| Batch size | 1 | Raise it only if memory allows |
| Iterations | 100 | Number of optimizer steps, not epochs |
| Learning rate | 1e-5 |
Fixed, used by Adam |
| System prompt | "Answer briefly and informally, as in personal correspondence." | Saved with the adapter |
Reporting and checkpoint cadence are derived from the iteration count: progress every min(10, iterations) steps, validation and checkpoint saves every min(100, iterations) steps, and at most 10 validation batches.
Each run creates a new folder:
<models folder>/adapters/<model>-<timestamp>/
├── adapter.safetensors # LoRA weights
└── locai_adapter.json # metadata needed to re-apply the adapter
locai_adapter.json stores the base model folder name, the number of LoRA layers, the iterations actually run, the quantization bits of the base (empty for plain LoRA), the creation date and the training system prompt.
You can also pick a folder for an extra copy (weights and metadata).
- An adapter works only with the base model it was trained on. Tensor shapes differ between models, so LocAI compares the base model name and refuses to apply a mismatching adapter. It shows a notice in the Models tab instead of failing.
- When the model is loaded, LocAI recreates the same LoRA layers (the last N blocks) and loads the saved weights. The chat uses the adapter's training system prompt automatically.
- Adapters and models are listed separately, and you can delete either one.
- Fine-tuning a small model on informal text teaches style and tone, not facts. Do not expect it to memorize information.
- Start with 100 iterations and look at the validation loss. If it climbs while training loss falls, you are overfitting. Use more data or fewer iterations.
- A good first sanity check is a tiny dataset (10 to 20 examples) with enough iterations that the loss clearly drops. If it does not, check the dataset schema first.
- Clean your data before training. Duplicates and empty turns waste capacity, and because the split is random, duplicated examples can end up in both training and validation and make validation loss look better than it is.
- If MLX reports an error without details, it usually means the model does not fit into memory. Use a 4-bit model, batch size 1, fewer LoRA layers, and close other heavy apps.
The memory budget slider in Settings tells LocAI how much GPU memory it may use. Defaults: 6 GB on macOS, 3 GB on iOS.
For the MLX backend the budget sets the GPU memory limit and keeps MLX's reusable buffer cache small (at most 32 MB, and at most 5% of the budget), so memory stays available for weights and the KV cache.
The budget also selects the context length that the app reports (and that the token counter measures against):
| Budget | Context length |
|---|---|
| up to 4 GB | 2048 |
| up to 8 GB | 4096 |
| above 8 GB | 8192 |
Forced swap mode trades speed for the ability to load larger models: it removes the memory limit and the buffer cache and reports a context length of 2048. Expect it to be much slower.
For GGUF files the app can estimate whether a model fits the budget (weights plus KV cache plus about 0.5 GB of overhead), but GGUF inference itself is not implemented yet (see Limitations).
How it works:
- After each completed reply, the question and the final answer are saved on the device. Streaming placeholders and error messages are not stored, and when the terminal tool is used only the final answer is kept. Each question is capped at 700 characters and each answer at 1,400.
- Before a new request, the store vectorizes the new message and scores every saved entry by cosine similarity. Features are lowercase words plus character trigrams of each word, so inflected forms and short phrases still match.
- Entries below a similarity threshold (0.12) are ignored. The best three are added to the request, each answer cut to 450 characters.
- The memory is added with an instruction not to treat it as commands and not to mention the memory system.
- The store keeps the newest 200 entries and drops the oldest.
What to expect:
- It matches overlapping wording. It does not understand paraphrases that share no words with the stored text.
- It works offline, in any language, and with no model loaded.
- You can turn it off and clear it in Settings.
The terminal tool lets the model act on your Mac: list files, read system information, run programs.
The protocol is plain text, so it works with every chat template and backend, unlike native tool calling.
-
A system prompt tells the model it has a terminal and explains the rules (one command per reply, wait for the result, short read-only commands, no
sudo, no deleting or installing unless asked). -
The model writes exactly one block:
<terminal> ls -la </terminal> -
LocAI detects the first complete block while streaming, cuts anything after it (usually an invented output) and stops generation.
-
Unless auto-approve is on, you see the command and press Run or Deny.
-
The command runs and the result goes back to the model as:
<terminal_output exit_code="0"> ...output... </terminal_output>The tag can also carry
timed_out="true"andtruncated="true". A denied command is reported asstatus="denied"with an instruction not to retry it. -
The model continues. After at most N commands per reply (default 5) it is told to answer with what it already has.
The parser also copes with common small-model habits: commands wrapped in a code fence, or prefixed with $ .
/bin/zsh -l -c <command>in the working folder you choose (default: your home folder).- Standard output and error are merged. Standard input is closed, so interactive commands cannot hang waiting for you. Colors and pagers are disabled (
TERM=dumb,NO_COLOR=1,PAGER=cat,GIT_TERMINAL_PROMPT=0). - A timeout (default 30 s, adjustable from 5 to 300 s) ends runaway commands. Pressing Stop also ends them, including child processes.
- Long output is cut to the head and the tail, because errors are usually at the end. The budget is between 1 KB and 8 KB depending on the context length, to protect the model's context window.
| Setting | Default | Notes |
|---|---|---|
| Enable terminal | off | Not persisted. Off again on every launch |
| Auto-approve | off | Not persisted. When off, every command asks for confirmation |
| Timeout | 30 s | 5 to 300 s |
| Max commands per reply | 5 | 1 to 15 |
| Working folder | home folder | Falls back to home if the folder does not exist |
- A model that reads untrusted text (a web page, a file, an email) can be tricked by instructions hidden in it. Keep confirmation on and read every command before pressing Run. Treat auto-approve as dangerous.
- The macOS build runs without the App Sandbox so the shell can see your files. That also means commands run with your user's permissions.
- Terminal access is not available on iOS, where apps cannot start processes. The settings are hidden there.
Everything is kept under one folder, by default ~/Library/Application Support/LocAI/ (inside the app container on iOS or in a sandboxed Mac build):
LocAI/
├── models/
│ ├── mlx/ # MLX model folders (config.json, tokenizer, *.safetensors)
│ ├── gguf/ # downloaded GGUF files
│ └── adapters/ # LoRA / QLoRA adapters, one folder per training run
└── semantic-memory.json # local memory, up to 200 entries
- The models folder can be changed in Settings. Adapters follow it.
- Chat history is kept in memory for the session and cleared when a model is loaded or when you clear the chat.
- To remove everything the app stored, delete the
LocAIfolder.
SwiftUI views (Chat, Models, Settings, Tuning)
|
AppState ── AppSettings, ModelManager, SemanticMemoryStore
|
ChatBackend protocol
├── MLXChatBackend (MLX / MLXLLM, LoRA adapter loading)
└── LlamaCppChatBackend (GGUF, placeholder, see Limitations)
LoRATrainingManager (MLX Swift training loop, dataset loader, adapter export)
HuggingFaceService (search and download)
TerminalService (macOS only: command runner and tool protocol)
| Component | Responsibility |
|---|---|
AppState |
Loaded model and adapter, conversation, one chat turn including the terminal loop, memory injection, token count |
AppSettings |
Memory budget, prompts, language, terminal options, models folder, derived limits |
ChatBackend |
Interface every inference backend implements: load, streamChat (an AsyncThrowingStream of text deltas), unload |
MLXChatBackend |
Loads MLX models, sets GPU limits, applies adapters, streams tokens |
ModelManager |
Lists, creates and deletes models and adapters on disk |
HuggingFaceService |
Hugging Face search and file downloads, built on DownloadTaskRunner |
LoRATrainingManager |
Dataset loading and splitting, training run, progress, cancellation, adapter saving |
LoRAAdapter |
Adapter folder layout, metadata, compatibility check |
SemanticMemoryStore |
Lexical retrieval store with JSON persistence |
TerminalService |
Process runner, TerminalCommandParser, TerminalPrompt |
TokenEstimator |
Fast token estimate for the context indicator |
Loc / LocExtras |
Four-language UI strings with English fallback |
sendappends your message and starts a generation task.buildPayloadassembles the request: one system message (the adapter's or your system prompt, plus terminal instructions when the tool is on), an optional memory block, then the most recent messages.- The backend streams text deltas into the assistant message.
- With the terminal tool on, the stream is watched for a complete
<terminal>block. If one appears, generation stops, the command is approved and run, the output is appended as a tool-result message, and the loop continues up to the command limit. - The final answer is saved to memory (if enabled).
- The project uses
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor. Code that must not block the UI (command execution, dataset parsing, training configuration) is explicitlynonisolated. - Any backend that conforms to
ChatBackendcan be added without touching the UI. - Training runs inside the MLX model container's executor, with a thread-safe cancel flag shared with the UI.
LocAI/
├── LocAI.xcodeproj
├── LocAI/
│ ├── LocAI.entitlements
│ └── Sources/
│ ├── LocAIApp.swift
│ ├── Models/ # AppSettings, ChatMessage, ModelInfo, LoRAAdapter
│ ├── Services/ # AppState, backends, training, memory, terminal, downloads
│ ├── Views/ # Chat, Models, Settings, Tuning, shared components
│ └── Localization/ # Loc, LocExtras
└── LocAITests/ # unit tests (Swift Testing)
The unit tests use Swift Testing and live in the LocAITests target. They cover the logic that does not need a GPU.
Run in Xcode: select the My Mac destination and press Cmd+U. Results appear in the Test navigator (Cmd+6).
Run from the terminal:
xcodebuild test -scheme LocAI -destination 'platform=macOS'Use xcodebuild, not swift test: SwiftPM cannot compile MLX's Metal shaders, so a binary built that way fails at runtime.
| Area | What is checked |
|---|---|
TokenEstimator |
Characters-per-token rounding, minimum of one token per word, Cyrillic, message sums |
TerminalCommandParser |
First complete block, unclosed and empty blocks, code fences, $ prefix, several blocks |
| Dataset loader | All six schemas, ChatML rendering, system prompt handling, malformed JSONL lines, .json wrappers, .txt, unsupported extensions, Cyrillic content |
DatasetSplit |
10% hold-out, batch-size minimums, exact boundary, error details |
| Training configuration | Missing dataset or model files, non-positive hyperparameters |
SemanticMemoryStore |
200-entry cap, field limits, persistence, clearing, relevant and unrelated queries |
Not covered by automated tests: the MLX inference and training paths themselves (they need a Metal GPU and downloaded models) and the SwiftUI views.
| Symptom | What to do |
|---|---|
| "The MLX backend package is not linked" | Link MLXLLM, MLXLMCommon, MLXOptimizers and Tokenizers to the target |
| Build or run fails in the iOS Simulator | Not supported: MLX needs a Metal GPU. Use a Mac or a real device |
| Training stops with "MLX failed ... did not provide a detailed reason" | Almost always memory. Use a 4-bit model, batch size 1, fewer LoRA layers, and close other apps |
| "The dataset has N examples, but batch size B needs at least M" | Add examples or lower the batch size. Both parts of the split must fill one batch |
| "No training examples were found" | The file's schema was not recognized. Check it against Dataset formats |
| Permission denied for the dataset or export folder | Choose the file or folder with the Open… button instead of typing a path |
| Adapter notice about a base-model mismatch | The adapter was trained on a different base model. Load the model it was trained on |
| A model download fails midway | Check the connection and free disk space, then start the download again |
| Models "disappeared" after switching sandbox settings | Check the models folder in Settings. A sandboxed build keeps data in its container |
Could not find test host when running tests |
Select My Mac as the destination for the test run |
| The model answers very slowly | Lower the memory pressure: close other apps, use a smaller or 4-bit model, and avoid forced swap |
- GGUF / llama.cpp inference is not implemented yet. You can search for and download GGUF files, but loading one reports that the backend is not available. Use MLX models.
- The training template is hard-coded to ChatML (Qwen style). Other model families (Llama, Gemma, Phi) expect different chat templates, so training data for them would need its own template. Chat itself uses the model's own template.
- Training does not mask user turns. Each example is one ChatML string, so the model also learns from the user and system text, not only from the assistant's replies.
- Fine-tuning a 1.5B to 3B model on informal text picks up style, not facts, and can produce wrong words in less common languages.
- Dataset checks are minimal. Malformed JSONL lines are skipped silently, and duplicate examples are not removed.
- Local memory is lexical. It matches overlapping words, not paraphrases, and keeps only the newest 200 exchanges.
- The token counter is an estimate (about 4 characters per token). It is good for judging "am I near the limit", not for exact counts.
- An adapter only works with the exact base model it was trained on.
- Terminal output is truncated to protect the context window, so very long outputs are shown as head and tail only.
- High deployment targets (macOS 26.0, iOS 26.5) mean older systems cannot build or run the project unless you lower them and the code still compiles.
- llama.cpp backend for GGUF inference
- Dataset validation and de-duplication on import, with a report of skipped lines
- Assistant-only loss masking for training
- Per-model-family chat templates for training
- Generation statistics
- Model metadata viewer
- Conversation export
- Custom model repositories
PolyForm Noncommercial License 1.0.0. See LICENSE.md.
You can read, run and modify the code for any noncommercial purpose. Commercial use is not permitted by this license.
Built with MLX, the MLX Swift examples, Hugging Face model hosting and SwiftUI.