Files
ai_studio/README.md
2026-11-19 09:18:49 +00:00

207 lines
16 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# AI Studio
Native SwiftUI chat for Apple silicon Macs running macOS 14 or later. Open `AIStudio.xcodeproj` in Xcode with Swift 6.3 or later and run the shared **AIStudio** scheme on **My Mac**. Xcode resolves the pinned Swift packages on the first build.
## 1. Set up a model
- **GGUF** models run locally. In **Settings → Model Library → On This Mac**, drop a GGUF chat model from Finder or use **Import…**. Choose **Use** to set the default for chat. The library shows architecture, predominant tensor format, file size, selection, and the recommended Metal working set. Bundled llama.cpp runs GGUF chat on Metal without an Ollama service. Models need a supported embedded chat template.
- To download a **GGUF** model, open **Hugging Face · GGUF**, choose **Browse**, search by model name, or enter a public `owner/model` ID. Open a result’s files and choose a standalone download. AI Studio pins the repository revision, shows byte progress and cancellation, validates the available size and checksum, then registers the model. Private or gated repositories and sharded GGUF downloads are outside this workflow.
- **Core ML** chat requires macOS 15 or later. In **Settings → Model Library → On This Mac → Core ML**, download the Apple Mistral model or import a compatible stateful Core ML model with its matching `tokenizer.json` and `tokenizer_config.json` beside it. Choose **Use** or pick the **Core ML** entry in chat. Search lists public Hugging Face model cards. The import currently targets the stateful text-generation contract used by [Apple’s Mistral export](https://huggingface.co/apple/mistral-coreml).
- **Ollama:** In **Settings → Models**, refresh the installed list and select a tag. The default server is `http://127.0.0.1:11434`. Use the same pane to pull, inspect, and delete models. Enter a remote HTTP or HTTPS base URL to use another server. The optional bearer token stays in memory and requires HTTPS for remote servers.
- **OpenAI-compatible:** In **Settings → Models**, choose the compatible backend, enter the API base URL (for example `http://127.0.0.1:1234/v1` for LM Studio), then refresh models and select the exact model ID. Remote URLs require HTTPS. An optional bearer token stays in memory and is cleared when the endpoint changes. The server manages model loading. Chat Completions streams the reply and any separately reported reasoning.
- **MLX:** In **Settings → Model Library**, drop an MLX folder or browse and search Hugging Face for public MLX Community text-generation checkpoints. Switch to **Ollama** for models installed on your server and the public Ollama catalog. Download a checkpoint and choose **Load Model** to load it for on-device inference. **Settings → Models** also accepts a local model folder with configuration, tokenizer files, and safetensors weights. **Prefer Ollama** can fall back to the configured MLX folder when Ollama fails before emitting output.
- **Thinking:** The composer sends Boolean or named effort settings to Ollama. The composer keeps Thinking visible. Supported MLX and GGUF templates expose Default, Off, and On. Backends that manage thinking themselves show Default. The model button shows the selected backend beside the model name. Reported reasoning appears in an expandable section. If an Ollama request is interrupted after emitting text, reasoning, or a tool call, the router keeps that backend. **Stop** cancels generation and retains any partial output.
**Import LM Studio Library** in **On This Mac** scans `~/.lmstudio/models` for GGUF chat models and MLX folders and registers them in place. Use **Import MLX Models…** to select an individual checkpoint or scan a folder of checkpoints.
Model Library shows red warnings when the model files alone exceed the applicable memory budget or the configured MLX weight limit. Generation also needs memory for its context.
Use **Settings → Agents** to enable or create reusable roles, then turn on **Agents** in the composer. The [Agents guide](Docs/Agents.md) covers setup, model routing, supervised MCP calls, and run limits.
Use the model button in the chat composer to choose an installed GGUF, MLX, Core ML, or Ollama model, or a model from your compatible API. AI Studio remembers the
choice for that conversation. **Use Default** returns to the model in Settings.
Use **Resources** beside the model button to select a Knowledge Stack, Skill,
Context, Web Clip, or Prompt Template for the current chat. **Insert Saved Prompt**
copies a saved prompt into the composer for editing. Use **Open Workspace** to
manage these resources.
See [Local Model Roadmap](Docs/LOCAL-MODELS.md) for supported families, verification, and the next phase.
Open **Training & Images** from the main window toolbar. **Training** contains the MLX conversion and LoRA workflow with live run output. **Images** opens Apple Image Playground on supported Macs and can preview an existing image or export a PNG preview. [MLX fine-tuning guide](Docs/TRAINING.md) · [Apple Image Playground](https://developer.apple.com/documentation/imageplayground)
Open **Performance** from the chat toolbar to compare latency and throughput in a separate window. **Run Benchmark** uses the selected model, a fixed prompt, and a 128-token output cap. Completed replies keep their timing beneath the message, and the dashboard retains the latest 50 chat and benchmark runs.
**Settings → Model Library → LM Studio** offers local file scanning and an API model list. Use **Use Locally** for an imported file or **Use Server Model** for a running LM Studio server. The **Hugging Face · Core ML** section shows the Apple checkpoint as **Installed** when its files are already present. Hugging Face catalog rows share the same layout across MLX, GGUF, and Core ML, with previews, model cards, favorites, and actions on a separate line.
The Images workspace adjusts exposure using [Core Image with a Metal renderer](https://developer.apple.com/documentation/coreimage/cicontext). Export Preview saves the adjusted PNG.
## 2. Chat with documents
Use **Documents** in the conversation toolbar to import PDF, UTF-8 text,
Markdown, or CSV. PDFs require extractable text. AI Studio splits documents
into overlapping passages and indexes them in SQLite FTS5. When macOS has a
sentence embedding for the detected language, AI Studio computes and stores
vectors on the Mac. Retrieval combines the FTS5 and cosine similarity rankings
with reciprocal rank fusion. Keyword search remains available without embeddings.
AI Studio retrieves up to four passages from the conversation and four from a
selected local Knowledge Stack. When chat-document retrieval finds no match,
it uses opening excerpts from recent chat documents. The composer toggle
controls chat-document retrieval, and the paperclip attaches previewed text to
one turn. Requests label the excerpts `[D1]`, `[D2]`, and so on. The reply's
**Document sources** section shows the excerpts the final model received. The
app saves those excerpts with the reply so they remain inspectable after a
document is removed. Ollama and compatible servers receive any passages
included in their generation request. MLX generation runs on the Mac.
Chat history, older-message recall, and document indexes live in
`~/Library/Application Support/AIStudio/studio.sqlite`. Chat documents are
scoped to their conversation. Deleting a document removes its index, and
deleting a conversation removes its messages and documents. Original files
stay in place.
## 3. Run a tool
Open **Toolbox**, enter an MCP HTTP endpoint, and choose **Connect**. Select a tool, review the schema, enter its JSON arguments, and confirm the invocation. You can attach up to 8,000 characters of the result to the next message in the active conversation. The composer shows the attachment before it is sent.
For a local subprocess, select **Local stdio**, enter the full path of the
server executable, and add one argument per line. Choose **Start & Connect** to start the server and discover its tools.
Use **Disconnect** on that row to stop the subprocess. Local
stdio supports the MCP initialization handshake used by the 2024 and 2025
protocol revisions.
The HTTP client supports Streamable HTTP with current stateless discovery and legacy initialization, session headers, and JSON or server-sent event responses. Remote MCP endpoints require HTTPS. Optional bearer tokens stay in memory. Tool calls require explicit confirmation and are sent once. OAuth sign-in, modern stateless stdio, and server-requested follow-up interactions remain outside the supported MCP scope.
## 4. Customize prompts and review performance
Choose a **Global preset** in **Settings → Generation**. Default, Concise, Coding, Study,
Creative, and Custom are available across conversations. **Prompt Builder**
turns structured inputs into a prompt you can copy, put in the composer,
or save as the global system prompt. Global settings persist across launches.
Open **Workspace → Prompt Studio** to create a versioned template. Put
`{{input}}` where the chat or evaluation input belongs. A template without
the placeholder goes before the input. Add up to eight input/assistant pairs
with **Examples** to demonstrate the desired response in context. Saving
records the body, notes, tags, and examples together. **Version History** loads
an earlier version into the editor, where you can evaluate it or save it as a
new version. **Use as Template** activates the latest saved version for the
current conversation.
**Evaluate** runs the draft and its examples through the default model route
from Settings. Enter an optional expected output to check equality after
normalizing whitespace and letter case. Evaluation does not add a chat turn.
Select a version in the editor and run the same test case to compare outputs.
**Settings → Generation → Prompt context budget** limits estimated input plus
reserved output for MLX, Ollama, and compatible chat. The estimate uses UTF-8
size and message overhead, so actual model token counts can differ. The budget
preserves system instructions and the latest user input, dropping whole
example or history turns and lower-ranked document excerpts as needed. If the
required input still exceeds the budget, the request stops with an error.
An explicit Ollama context length also constrains the budget.
Search conversation titles and messages in the sidebar. Rename the selected
chat with the pencil button. Completed replies render inline Markdown and fenced
code blocks with copy controls. The **Performance** dashboard keeps the last
50 generations across launches, including latency, duration, output size,
backend, and tokens per second when the provider supplies it.
## 5. Generation and local tools
**Settings → Generation** applies system instructions to future requests
without adding a transcript message. Save parameter overrides with **Apply
Parameters**. Blank fields inherit backend defaults, including AI Studio’s
1,024-token MLX cap. Shared settings include sampling temperature, top-p,
output token limit, repetition controls, and stop sequences. Ollama also accepts
context length, top-k, min-p, seed, frequency and presence penalties, keep-alive,
and JSON response mode. The compatible backend sends temperature, top-p, max tokens, stops, frequency and presence penalties, and JSON mode. Native MLX exposes rolling KV-cache size and prefill
step size. On failover, MLX uses the supported shared and MLX settings.
**Settings → Local Tools** runs a confirmed command through the installed
Docker CLI. It captures up to 128 KiB of combined output; you can copy that
output or explicitly attach it to the active chat. The Finder section can open
or reveal a selected file or folder, copy its path, or preview up to 8,000
bytes of a selected UTF-8 file. A preview can be explicitly attached to the
active chat. Docker commands and Finder actions are initiated from Settings.
**Settings → Runtime** shows the cached MLX model and available physical
memory. Set the idle unload interval, unload the cached model on demand,
or set an optional maximum weight-file size for new model loads. The model
weight limit measures safetensors on disk. It does not estimate total runtime
memory.
## Workspace and desktop preferences
Open **Workspace** to create reusable document stacks, store instructions as
Skills, save reference Contexts, save Prompts, or capture public UTF-8 pages as
Web Clips. Select the resources you want to include in the current chat. Knowledge stacks
show the number of locally embedded passages. If a connected MCP server
provides `search_knowledge`, its results are automatically included in new
chat requests while it stays connected. This includes Local Knowledge’s
Chroma index. A connected Gitea server can list repositories when asked in
chat, for example “Can you see my Git repos?”
Toolbox shows the connected MCP server beside the composer. Read
[Programming custom MCP servers](Docs/MCP.md) for configuration, the installed
Knowledge server, and troubleshooting.
Return sends and Shift–Return inserts a newline. **Settings → Appearance**
controls workspace mode, theme, accent, typography, spell checking and
automatic correction. **Settings → Workspace Data** exports the SQLite
workspace and restores an AI Studio backup after confirmation. Backup
reminders appear in that panel. **Settings → Model Library** downloads catalog
models, registers existing local MLX folders, and scans a selected library
folder for compatible checkpoints. Settings → Models lists Ollama models
as rows with direct selection controls.
## Search and retrieve web sources
Type `Search the web for Laravel service container` or paste a page URL
into chat. AI Studio uses Bing search by default. To use SearXNG, set a
`/search` endpoint with JSON enabled in **Toolbox → Web Search**.
A search retrieves up to four result pages. A direct request retrieves
up to two URLs. Both can follow up to three relevant links on the same
sites, one level deep. AI Studio extracts text without running page
scripts and sends excerpts with source URLs to the selected model.
The chat's diagnostics menu has a **Show Debug Output** option for
retrieved page paths and lookup errors.
**Toolbox → Web Search** lists results. **Toolbox → Retrieve Page** previews a page and lets you attach it to your next message. Both are available next to the chat composer. **Built-In Web** offers separate
search and retrieval tools in the MCP Servers tab.
## Add local files to chat
**Settings → Local Tools → Chat File Access** lets you choose a folder or
allow any location readable by AI Studio under macOS permissions. Use
`/read /path/to/file.txt` or `/ls /path/to/folder` in chat. The selected
model receives the preview. Turn off access from the same settings section.
Use the paperclip beside the composer. Select a UTF-8 text or source file,
a text PDF, or a folder. Review the preview and attach it to your next
message. Folder previews list immediate visible entries. Toolbox shows
server connections on the left and the selected server's tools and results
on the right.
## Build and test
From the project root, run `Scripts/build.sh` to build and open AI Studio. It defaults to Debug. Use `./Scripts/build.sh Release` for a Release build, or add `--no-launch` after the configuration to build without opening the app. Run `Scripts/test.sh` for XCTest, including the local MCP and Ollama management fixture. It requires Python 3 for the fixture and keeps its logs and results in the temporary build directory.
For opt-in live provider checks, use installed models or select a catalog download:
```sh
TEST_RUNNER_AISTUDIO_TEST_OLLAMA_URL=http://127.0.0.1:11434 \
TEST_RUNNER_AISTUDIO_TEST_OLLAMA_MODEL=your-installed-tag \
TEST_RUNNER_AISTUDIO_TEST_MLX_PATH=/path/to/local-model \
TEST_RUNNER_AISTUDIO_TEST_MODEL_DOWNLOAD=qwen3-0.6b-4bit \
./Scripts/test.sh
```
See `Docs/RELEASE.md` for packaging, signing, and notarization.
See [phase progress](Docs/PHASES.md) for verification status and remaining work.
Hugging Face GGUF and Core ML search results fetch per-file sizes and show a range when a repository has multiple variants. Red warnings identify repositories with variants above the memory budget. Each catalog search section can be collapsed and remembers its state.