maclocal-api

scouzi1966MIT活跃维护

把 Mac 上运行的 Apple Foundation Models、MLX 模型等本地 AI 能力聚合成一个兼容 OpenAI 的 API 端点,支持服务模式和单次命令推理,还能通过管道调用。

'afm' command cli: macOS server and single prompt mode that exposes Apple's Foundation and MLX Models and other APIs running on your Mac through a single aggregated OpenAI-compatible API endpoint. Supports Apple Vision and single command (non-server) inference with piping as well . Now with Web Browser and local AI API aggregator

nightly-20261025-54a1548发布于 2026-10-25 22:51 UTC352star +2 / 7 天17fork同步于 2026-11-10 12:01 UTC

怎么上手

由 README 提炼,执行前请确认
brew install scouzi1966/afm/afm
afm mlx -m Qwen3-0.6B-4bit -w
硬件要求按 README 说明

需 Apple Silicon Mac,完整功能需 macOS 26 或更新;显存即统一内存,按所选模型准备,0.6B–4B 量化模型最易验证,30B 级需大得多的统一内存。

支持 Apple Silicon
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

把 Apple Silicon Mac 变成私有 OpenAI 兼容 AI 服务器,跑 MLX 与 Apple 端侧模型

把 Mac 上运行的 Apple Foundation Models、MLX 模型等本地 AI 能力聚合成一个兼容 OpenAI 的 API 端点,支持服务模式和单次命令推理,还能通过管道调用。

核心能力

  • 聚合 Apple Foundation 与 MLX 模型到单一 OpenAI 兼容端点
  • 原生 Swift 可执行文件,服务端无需 Python 运行时
  • 支持流式、工具调用、结构化输出、推理与 logprobs
  • 内置 WebUI,并提供 Vision OCR、语音、嵌入接口
  • 含前缀缓存、并发解码、投机解码与指标观测

容易踩的坑

MLX 模型权重首次使用时才从 Hugging Face 下载;默认监听 127.0.0.1:9999;开发构建需 Xcode 27,稳定版建议用 v0.9.19 而非 afm-next。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本nightly-20261025-54a1548
  1. nightly-20261025-54a1548afm-next (20261025 · 54a1548)pre-release最新正式版2026-10-25 · 2026-10-25 22:51 UTC

    Nightly build from main branch.

    • Commit: 54a1548
    • Date: 20261025
    • Version: 0.9.20-next.20261025.54a1548

    This is an unstable development build. For the latest stable release, use brew install scouzi1966/afm/afm.

    Changes since last build (138ca5d)

    • Update AFMKit release candidate and vision qualification (e14aa40)
    • Update exact AFMKit release to rc.10 (ac34390)
    • Fix post-stop tool guard and reasoning SSE checks (1dc5b39)
    • Catch completed initial SSE items in live reasoning qualification (f1cc11a)
    • Reject unoffered deltas and stream empty initial response items (f208f17)
    • Reject provider tool calls without requested tools (6839b05)
    • Add no-tools provider violation regression tests (02dfe31)
    • Document reasoning regression fixes and client qualification (d6310cd)
    • Deliver Codex reasoning summaries and preserve structured reasoning (1a1a71c)
    • Test truncated structured reasoning finalization (b063e1b)
    • Preserve and deliver reasoning beside tool calls (659fa96)
    • Cover structured reasoning with answer and tool turns (67f3897)
    • Require reasoning SSE delivery in qualification tests (a4884e9)
    • Fix throwing reasoning test response callbacks (fb6be76)
    • Add reasoning and tool-turn qualification contracts (393a447)
    • Fix Responses reasoning input and generation option forwarding (b371dc4)
    • Preserve remote dependency pins in paired AFMKit builds (3e207b8)

    Install / Upgrade

    Homebrew
    brew tap scouzi1966/afm
    brew install scouzi1966/afm/afm-next    # fresh install
    brew upgrade afm-next                    # upgrade existing
    brew reinstall afm-next                  # force reinstall (same version, new build)
    
    pip
    pip install --extra-index-url https://maclocal-ai.pages.dev/afm/wheels/simple/ macafm-next
    
    Switching between stable and nightly
    # Homebrew
    brew unlink afm && brew install scouzi1966/afm/afm-next   # switch to nightly
    brew unlink afm-next && brew link afm                      # switch back to stable
    
    # pip
    pip install macafm          # stable
    pip install --extra-index-url https://maclocal-ai.pages.dev/afm/wheels/simple/ macafm-next   # nightly
    

    Qualification on this build

    This nightly consumes immutable AFMKit v0.1.18-rc.11, including the reasoning-boundary and stop-sequence fixes. The merged source passed 399 XCTest cases (2 skipped), 145 Swift Testing cases, and 118/118 full live assertions with a Qwen Next vision checkpoint launched using --vlm.

    The comprehensive model suite ran 87 configurations (91 result records): 89 passed and two tool-argument expectations failed from model-emitted argument choices. Promptfoo reported native protocol conformance 76/76; model and agent behavior 73/99; and forced-parser experiments 197/231. The latter two categories are quality and compatibility findings, not native protocol passes. No transport errors or crashes were observed. MTP was off for this qualification. See the attached test-report bundle for the HTML reports, raw data, and Codex-GLM triage.

  2. nightly-20261005-138ca5dafm-next (20261005 · 138ca5d)pre-release2026-10-05 · 2026-10-05 18:33 UTC
    查看更新说明

    AFM v0.9.20-next.20261005.138ca5d

    Nightly candidate from main commit 138ca5d8b5802fa7ba5f4031a41248a6909a6731, with immutable AFMKit 0.1.18-rc.9.

    Highlights

    • Integrates the qualified Qwen Next MTP throughput work, including the opt-in throughput-v2 profile. Users do not need optimization environment variables.
    • Supports native mlx-community Qwen Next checkpoint loading and vision, alongside the ddalcu vision-overlay layout.
    • Preserves shared-prefix reuse and concurrent request isolation with MTP on and off.
    • Corrects Responses API validation-error envelopes.
    • Honors explicit thinking-off requests through Messages and Responses, preventing hidden reasoning from consuming the answer budget on supported models.
    • Strengthens release tests: pinned executable/resource identity, checkpoint and harness provenance, complete llmprobe case coverage, and matched AI-judge comparison evidence.
    • Improves reliable build/test resource staging and validates CLI profiles before capture-file preparation.

    Qwen Next throughput profile

    afm mlx -m mlx-community/Qwen3.8-Flash-Next-4bit-mtp \
      --vlm --mtp --mtp-depth 3 --qwen-mtp-profile throughput-v2 -w
    

    The profile is explicitly opt-in. For non-MTP operation, omit the three MTP/profile options. Prefix caching retains its normal enabled default. Isolated context throughput measurements disable it and use a prefill step size of 8192; those measurements are not concurrent aggregate throughput claims.

    Install

    brew update
    brew install scouzi1966/afm/afm-next
    # If already installed:
    brew upgrade afm-next
    afm --version
    

    Expected version: v0.9.20-next.20261005.138ca5d.

    pip install --upgrade --extra-index-url https://maclocal-ai.pages.dev/afm/wheels/simple/ \
      'macafm-next==0.9.20.dev20261005+138ca5d'
    

    Evidence and scope

    Final executable SHA-256: 93fe1a17a0ec3c749bfe80ff2c1cfddd0da11db0759b4cc090f880770c77aefa.

    Final checks: 156/156 vision/API/cache/concurrency assertions; all 144 context-test outputs exactly match the saved AFM control. All 32 sustained prefill/decode comparisons are within 3% of that control (largest loss 2.09%). Unit qualification: 366 XCTest cases, two skips, zero failures; 145 Swift Testing cases passed.

    Single-request decode tok/s, with six trials per context (not selected peaks):

    Checkpoint / mode0.5K1K2K4K
    ddalcu vision overlay, AFM MTP on113.11110.2099.3598.06
    Same overlay, reference MTP on104.24104.1997.54100.14
    ddalcu vision overlay, AFM MTP off69.1068.4562.0661.14
    Same overlay, reference MTP off72.0169.6863.2864.78
    Native community, AFM MTP on89.4385.9379.2685.96
    Native community, AFM MTP off35.5435.5334.2834.17

    Reference figures are preserved mlx-serve 26.10.1 measurements (three trials/context), not new runs. It cannot load the native-community layout, so no same-checkpoint reference comparison is claimed for those rows. AFM-converted checkpoint received fresh functional smoke, not a new throughput matrix. The report bundle includes complete prefill and decode comparisons: overlay MTP-on prefill is 0.01–7.45% behind the reference; MTP-off prefill is 6.86–10.69% behind. These are isolated 128-token, greedy, reasoning-off measurements with prefix cache disabled and prefill chunk 8192—not aggregate concurrency claims.

    The attached test-report bundle distinguishes final-binary checks from earlier same-provider qualification. It includes the retained first-use timing failures, fixed paired confirmations, raw outputs, reference comparisons, and known model-behavior failures. Passing protocol checks are not presented as perfect model quality. First-use timing is distinct from sustained throughput; its underlying cause is not established.

    TurboQuant, DFlash, PCC, Splash, and the separate QSA-gather experiment are not included.

  3. nightly-20260922-a1d7461afm-next (20260922 · a1d7461)pre-release2026-09-22 · 2026-09-22 23:40 UTC
    查看更新说明

    AFM v0.9.20-next.20260922.a1d7461

    Nightly build from maclocal-api a1d7461, using the qualified, exact AFMKit 0.1.18-rc.8 release. This is a prerelease, not a stable production release.

    Highlights

    • Qwen Next performance and cache reuse: retain sparse long-context prefill, fused radix selection, decode-block selection and cheaper state snapshots. Normal defaults enable the qualified paths—no tuning environment variables are required. The final same-checkpoint 1K comparison measured median decode 68.66 vs 68.94 tok/s and client prefill 1029.5 vs 1026.7 tok/s against mlx-serve 26.9.5. First-use variability remains tracked; this is not a claim that every run or configuration meets parity.
    • Correct cache accounting: exact prompt repeats can reuse saved state and logits; cached-token counts describe actual reuse. GLM composite cache state is validated before restoration, with safe cold misses where needed.
    • More reliable tool conversations: preserve assistant calls and tool results through shared text/vision processing, without duplicate envelopes.
    • Structured-output fidelity: preserve marker-shaped literals in JSON and tool arguments; repair reasoning/visible-stop boundaries during batching.
    • Consistent API errors: valid requests that fail to produce a required call return a generation error, including a terminal SSE error for streaming. Token-budget exhaustion retains its normal length finish reason. No invented calls, hidden retries, or sampling-default changes are introduced.
    • Clearer test reporting: native conformance, model behavior and forced-parser experiments remain separate. Hard assertions and AI-judge scores are reported independently.

    Validation

    The attached report archive contains four-model full-suite HTML and Codex-GLM judging, llmprobe/Context evidence, raw responses and comparisons, plus final installed-binary smoke results. Development-candidate tests are identified separately from packaged-binary tests.

    Final tagged-package source tests: 352 XCTest cases (two skipped), zero failures; 145 Swift Testing passes. Provider release gates passed, including all 16 public API baselines and all 16 downstream products. Existing Xcode-beta Foundation test exclusions are documented in the archive.

    Known quality limitations are retained in the reports, including literal-fidelity probe failures/exclusions, missing required calls, Qwen case-level regressions, and first-use prefill outliers. These are not represented as universal quality parity or 100% model-behavior passes.

    Install or upgrade

    brew update
    brew install scouzi1966/afm/afm-next
    # If already installed:
    brew upgrade afm-next
    afm --version
    

    Expected: v0.9.20-next.20260922.a1d7461.

    Python nightly:

    pip install --upgrade --extra-index-url https://maclocal-ai.pages.dev/afm/wheels/simple/ macafm-next
    

    The Python distribution version is 0.9.20.dev20260922+a1d7461; its installed command reports the same canonical nightly version as Homebrew.

  4. nightly-20260920-afd96daafm-next (20260920 · afd96da)pre-release2026-09-20 · 2026-09-20 03:55 UTC
    查看更新说明

    Nightly build from main branch.

    • Commit: afd96da
    • Date: 20260920
    • Version: v0.9.20-next.20260920.afd96da
    • AFMKit: v0.1.18-rc.7 (b1c09a3)

    This is an unstable development build. For the latest stable release, use brew install scouzi1966/afm/afm.

    Qwen Next performance and execution work

    This nightly integrates the Qwen Next optimization work from AFMKit #122, AFMKit #123, and the consumer integration in maclocal-api #306.

    • Improves Qwen Next MTP initialization and bounded prefill: shifted target/head pairs survive chunk boundaries, and incompatible replay geometry is rejected rather than reused.
    • Adds reusable shared-batch execution infrastructure for recurrent models, including mixed-position autoregressive batching, fused/compiled GDN preparation, shared attention projections and Q/K normalization, and request-owned attention banks.
    • Preserves per-request recurrent state, PLE histories, cache positions, cancellation, sampling, stops, logprobs, and stream ownership while sharing eligible GPU work.
    • Adds exact prompt replay and bounded replay-cache handling, plus extensive Qwen Next numerical, lifecycle, quality, memory, and performance qualification.
    • Keeps higher-risk batching experiments opt-in. Their environment controls and rollback guidance are documented in AFMKit's QWEN_NEXT_OPT_IN_MATRIX.md; they are not silently promoted as user defaults.

    Controlled M3 Ultra C15 measurements retained by the merged work show the latest native-arithmetic request-banked attention candidate improving aggregate output throughput:

    WorkloadControlCandidateChange
    Prefix cache enabled162.62 tok/s175.09 tok/s+7.7%
    Prefix cache disabled82.84 tok/s87.09 tok/s+5.1%
    512-token prefix diagnostic158.62 tok/s169.84 tok/s+7.1%

    These are controlled opt-in results, not universal default-speed claims. The candidate retained identical text and token counts in the principal paired screens; broader semantic quality and workload-specific behavior remain separate qualification gates.

    For Qwen Next MTP, the bounded-prefill repair improved the fixed sampled structural screen from 15/25 to 17/25 while ordinary decoding scored 18/25 and the frozen reference scored 24/25. The corresponding full timing repeat was effectively neutral (28.60 to 28.83 output tok/s including prefill), so this nightly claims an MTP correctness repair—not a general MTP speedup.

    Other changes since the previous nightly

    • Prefix caching is now enabled by default. Use --disable-prefix-caching to opt out. The old --enable-prefix-caching flag remains as a deprecated compatibility option and prints guidance.
    • Adds bounded DeepSeek DSpARK chunked prefill with exact chunk/full cache and proposal parity (AFMKit #127).
    • Fails closed on AFMKit source-fingerprint errors and fixes DS4 source fingerprinting.
    • Improves reliable SwiftPM planning and canonical MLX metallib staging without requiring user environment variables.

    Validation

    • AFMKit RC: 906 XCTest cases passed, 14 intentional skips, 0 failures; 24 Swift Testing cases passed, 0 failures.
    • Consumer nightly: release build, source-fingerprint gates, installed-binary API smoke, Promptfoo qualification, and independent reviews completed before publication.

    Install / upgrade

    Homebrew

    brew tap scouzi1966/afm
    brew install scouzi1966/afm/afm-next    # fresh install
    brew upgrade afm-next                    # upgrade existing
    brew reinstall afm-next                  # force reinstall this build
    

    pip

    pip install --extra-index-url https://maclocal-ai.pages.dev/afm/wheels/simple/ macafm-next
    

    Switching between stable and nightly

    # Homebrew
    brew unlink afm && brew inst
    
  5. nightly-20260913-8212750AFM v0.9.20-next.20260913.8212750 — Apertus parity nightlypre-release2026-09-13 · 2026-09-13 15:45 UTC
    查看更新说明

    Apertus parity nightly

    This nightly includes the Apertus quantized-checkpoint inference fix and the Apertus response-tail sanitization fix.

    • Version: 0.9.20-next.20260913.8212750
    • Commit: 8212750ec75efaad4c6fa22b18e3403bb3553e77
    • AFMKit: 0.1.18-rc.6 (d8b1c09aad1c08356f2789f30d78eaa09cf18003)
    • Issue: #298

    Apertus fix

    AFM now matches the Python mlx-lm execution path for Apertus 2509:

    • Python-reference RoPE frequency rounding;
    • a final decode-shaped prompt-token step;
    • mlx-lm-compatible deliberation defaults;
    • Swiss AI's recommended unspecified-request sampling defaults (temperature=0.8, top_p=0.9).

    Using the exact 4-bit checkpoint and the 1,255-token RAG prompt from #298, the release candidate matched the Python reference byte-for-byte at 128, 512, and 2,048 completion tokens. The 2,048-token output is 8,847 characters on both sides. After publication, the GitHub archive was downloaded again and its relocated executable reproduced the 128-token Python-exact output.

    Validation

    • Consumer release XCTest: 344 passed, 0 failed, 6 skipped.
    • Full AFM assertion harness: 74 passed, 15 failed, 7 skipped (96 raw assertions). The failures are Apertus model-quality/tool-emission issues or two test-harness false negatives; no engine crash, transport, cache, batch, or parity failure was found.
    • Comprehensive Apertus suite: 82 passed, 9 failed, 0 skipped out of 91 records. This matches the previously documented four-bit model-quality baseline. All nine are instruction-following/tool-emission model failures.
    • The deterministic AI judge was not enabled.

    The curated evidence bundle, full HTML/JSONL reports, exact-parity outputs, publication verification, and checksums are attached as afm-v0.9.20-next.20260913.8212750-test-reports.tar.gz.

    A separate Python mlx_lm 0.31.3 / MLX 0.32.2 comparison on the same checkpoint is attached as apertus-python-mlx-compare-20260913.tar.gz. A separate end-user verification bundle is attached as afm-nightly-ux-verification-20260913.tar.gz: it covers a clean Homebrew reinstall, headless API/SSE checks, real headed Chrome WebUI interaction with screenshots, and native TUI chat/status/exit checks. Under the same generic no-system policy, eight of nine representative limitation probes failed in both Python and AFM. All tool probes returned ordinary text with no OpenAI tool call and no native <|tools_prefix|> envelope. The official recommended sampling subset also had four failures in both engines and zero engine-only failures.

    Install / upgrade

    Homebrew
    brew tap scouzi1966/afm
    brew install scouzi1966/afm/afm-next    # fresh install
    brew upgrade afm-next                    # upgrade existing
    brew reinstall afm-next                  # force reinstall
    
    pip
    pip install --extra-index-url https://maclocal-ai.pages.dev/afm/wheels/simple/ macafm-next
    
    Switching with stable
    brew unlink afm && brew install scouzi1966/afm/afm-next
    brew unlink afm-next && brew install scouzi1966/afm/afm
    

    This is an unstable development build. For the latest stable release, use brew install scouzi1966/afm/afm.

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    AFM — Your Mac is the cloud

    AFM — local AI infrastructure for Apple Silicon

    Swift 6.2+ macOS 26+ OpenAI compatible MIT

    Website · Documentation · GitHub releases

    [!IMPORTANT] AFM is moving to a two-layer architecture built on AFMKit.

    AFMKit is the reusable Swift foundation for building native AI apps and agents on Apple platforms. It owns the shared model contracts and provider runtimes for Apple Foundation Models, MLX, and DwarfStar, including generation, streaming, tool calling, structured output, and multimodal services.

    maclocal-api remains the complete AFM product: the afm CLI, local OpenAI-compatible server, WebUI, packaging, and operational tooling. It now consumes one exact-versioned AFMKit dependency instead of carrying parallel provider implementations. This separation lets apps and agents embed AFMKit directly while server users continue to install and run AFM as before.

    The migration is being delivered incrementally. Existing AFM commands and API compatibility remain the product contract while provider ownership moves into AFMKit and maclocal-api becomes a focused application layer on top of it.

    What's new

    AFM v0.9.19

    AFM v0.9.19 release highlights, installation instructions, new capabilities, and recently released models

    AFM turns an Apple Silicon Mac into a private, OpenAI-compatible AI server. Run Hugging Face MLX models or Apple’s on-device Foundation Model, then connect the clients and SDKs you already use.

    • Native Swift executable—no Python runtime for serving
    • Local inference—no cloud account or API key
    • Chat, streaming, tools, structured output, reasoning, and logprobs
    • Vision OCR, speech, embeddings, and a built-in WebUI
    • Prefix caching, concurrent decode, speculative decoding, and metrics
    • Importable Swift packages for apps that need in-process inference

    AFM is for Apple Silicon Macs running current macOS/Xcode toolchains. MLX model weights download from Hugging Face the first time you use them.

    Install

    [!NOTE] Stable v0.9.19 is the recommended release. It expands model support, OpenAI Responses and Anthropic Messages compatibility, image endpoints, native checkpoint conversion, and runtime reliability. Install afm-next only to preview changes made after v0.9.19.

    Use this stable release unless a newer nightly explicitly lists a post-v0.9.19 change you need.

    Stable (v0.9.19)Nightly (afm-next)
    Homebrewbrew install scouzi1966/afm/afmbrew install scouzi1966/afm/afm-next
    pippip install macafmpip install --extra-index-url https://maclocal-ai.pages.dev/afm/wheels/simple/ macafm-next
    Release notesv0.9.19Latest nightly

    Install a previous version

    Older stable releases are kept as pinned formulae in the Homebrew tap and as version-pinned wheels on PyPI. This is useful for reproducing an issue against a specific build or rolling back without waiting for a new release.

    Homebrew (pinned stable formulae): afm@<version> — available for 0.9.0, 0.9.1, and 0.9.3–0.9.10.

    brew install scouzi1966/afm/[email protected]
    brew uninstall afm
    brew link [email protected]
    afm --version
    

    Homebrew (pinned nightly formulae): afm-next@<full-version> — for example, [email protected]. See the Homebrew tap for available pinned nightlies.

    brew install scouzi1966/afm/[email protected]
    

    pip (version-pinned wheels): install any published release by version.

    pip install macafm==0.9.10
    pip install --extra-index-url https://maclocal-ai.pages.dev/afm/wheels/simple/ \
      macafm-next==0.9.15.dev20260808
    

    Start in two minutes

    brew install scouzi1966/afm/afm
    
    # Start a small MLX model and open the WebUI
    afm mlx -m Qwen3-0.6B-4bit -w
    

    AFM is now listening at http://127.0.0.1:9999/v1.

    curl http://127.0.0.1:9999/v1/chat/completions \
      -H 'Content-Type: application/json' \
      -d '{
        "model": "Qwen3-0.6B-4bit",
        "messages": [{"role": "user", "content": "Explain unified memory in one paragraph."}],
        "stream": false
      }'
    

    Or use Apple’s on-device model:

    afm -w
    

    Native terminal chat

    Use --tui when you want a private, full-screen chat without running an HTTP server:

    # Apple Foundation Models
    afm --tui
    
    # Any supported MLX model (all normal sampling/runtime flags still apply)
    afm mlx -m Qwen3-0.6B-4bit --tui
    

    TUI changes have a model-free regression harness. make test-tui runs stable Markdown/math/code snapshots and exercises keyboard input, terminal sizing, alternate-screen cleanup, and raw-mode restoration through a real macOS pseudo-terminal. If an intentional visual change updates the expected output, run Scripts/test-tui.sh --record, inspect the snapshot diff, then rerun make test-tui normally. The same focused suite runs automatically on relevant pull requests.

    The terminal UI streams responses, separates optional reasoning, and renders both answers and visible reasoning through a native CommonMark/GFM renderer. Headings, nested/task lists, quotes, tables, links, inline formatting, fenced code, and raw HTML are presented as inert terminal output. Code uses source-compiled Tree-sitter grammars for semantic highlighting and line numbers (details); unified diffs have distinct file, hunk, addition, and deletion styling. Inline and display LaTeX are rendered as readable Unicode math, including fractions, roots, super/subscripts, operators, Greek symbols, matrices, and cases. The UI also reports token and throughput statistics.

    Reasoning is collapsed by default into a live activity row with its phase, animated cursor, elapsed time, and generated character count. Press Tab during generation to expand or collapse the reasoning panel without interrupting the model. Use /reasoning expanded, /reasoning collapsed, /reasoning off, or /reasoning last to control it explicitly.

    It supports multiline editing, prompt history, cancellation, persisted/searchable sessions under ~/.afm/sessions, transcript export, attachments, terminal-width-aware tables, themes, and safe actions for response artifacts. Use /help for the command palette.

    The navigation follows Codex CLI conventions. Normal chat output remains in Terminal scrollback. Press Ctrl+T to open the full transcript overlay, then scroll with a Mac trackpad or mouse wheel, arrows, Page Up/Down, Ctrl-U/Ctrl-D, or Home/End; press Ctrl+T again to close it. Add --no-alt-screen to keep overlays inline too. /blocks opens a session-wide code-block list: navigate with arrows or paging keys, press Enter for Copy/Save/Preview actions, and Escape to return. Numbered /save, /copy, and /open commands remain available for direct use.

    Code is never executed automatically. /save refuses overwrites unless /save! is used, and only an explicit /open previews HTML or JavaScript in the browser. iTerm2 and Kitty can display local images inline; Terminal.app uses an explicit /image Quick Look fallback.

    Choose your runtime

    RuntimeBest forStart it
    MLXOpen models, VLMs, agent controls, performance tuningafm mlx -m <model>
    Apple Foundation ModelsZero-download system model and .fmadapter LoRA adaptersafm
    DwarfStarCompatible fixed-schedule Metal checkpointsafm mlx -m <owner/repo> (auto-resolved) or afm mlx -m <checkpoint.gguf> --mlx-runtime dwarfstar
    GatewayOne model list for Ollama, LM Studio, Jan, and other local serversafm --gateway

    Model IDs without an organization default to mlx-community, so Qwen3-0.6B-4bit and mlx-community/Qwen3-0.6B-4bit both work. For stable, general-purpose MLX models, use mlx-community; experimental scouzi1966 MLX artifacts require an unreleased maclocal-api version and are described in Experimental scouzi1966 MLX models.

    Evaluate a local model

    AFM ships all 91 labeled variants from the repository's comprehensive MLX test as a deterministic, no-judge suite. The model loads once, every output and timing measurement is retained locally, and a self-contained HTML report opens when the run finishes.

    afm mlx -m mlx-community/Qwen3-0.6B-4bit --eval
    
    # Headless run, suite discovery, and custom-suite scaffolding
    afm mlx -m <model> --eval --no-open
    afm mlx --eval-list
    afm mlx --eval-init my-suite
    afm mlx --eval-validate ~/.afm/evals/my-suite.json
    afm mlx -m <model> --eval-suite comprehensive --eval-suite my-suite
    

    Run artifacts are stored in collision-safe ~/.afm/evals/<date-time>-<model>-<suite>/ directories. See Local model evaluations for the suite schema, deterministic checks, report contents, and security limits.

    Why AFM works well for agents

    AFM is built for multi-turn, tool-using clients—not only chat demos.

    CapabilityWhat it gives you
    Native tool formatsAuto-detection for JSON, Qwen XML, Gemma, GLM, Kimi, MiniMax, LFM2, and related formats
    Tool choiceauto, none, required, and named-function forcing
    Streaming tool deltasOpenAI-style tool-call chunks while ordinary content continues to stream
    Structured outputjson_object, json_schema, and token-level xgrammar enforcement when enabled
    Reasoning extraction<think> and harmony analysis channels mapped to reasoning_content
    Determinism and inspectionseed, logprobs, top_logprobs, request IDs, tracing, and raw-parser mode
    Long-running reliabilityCancellation, Retry-After, token counting, fair concurrent queues, and Prometheus metrics
    Prefix reuseRadix-tree KV caching for stable system prompts and multi-turn agent loops

    Pick a tool-calling mode

    • Native (default): AFM detects the model’s own format and uses the narrowest parser. Use this for parity checks and benchmarks.
    • Repair: add --tool-call-parser afm_adaptive_xml for JSON-in-XML fallback, type coercion, nullable-schema handling, and fuzzy tool-name matching. Add --fix-tool-args when a model renames arguments.
    • Raw: add --tool-call-parser none to return the model’s tool markup as ordinary assistant content.

    See MLX tool-calling modes for examples and benchmark guidance.

    Connect an existing client

    Most OpenAI-compatible clients need only a base URL and a placeholder API key:

    Base URL: http://127.0.0.1:9999/v1
    API key:  x
    

    Copy-ready guides:

    OpenCode · OpenClaw · Cline · Continue · Aider · Cursor · Hermes

    OpenClaw users can also generate a provider block directly:

    afm mlx -m Qwen3-Coder-Next-4bit --openclaw-config
    

    API surface

    MethodEndpointPurpose
    POST/v1/chat/completionsChat, SSE streaming, tools, reasoning, structured output, logprobs
    POST/v1/completionsCapability-gated raw-prompt completions for MLX and DwarfStar, including SSE and exact usage
    GET/v1/modelsActive model and gateway model discovery
    POST/v1/embeddingsApple NaturalLanguage embeddings for RAG and semantic search
    POST/v1/vision/ocrOCR, tables, barcodes, classification, saliency, and PDFs
    POST/v1/audio/transcriptionsOn-device speech-to-text
    POST/v1/audio/speechText-to-speech using installed Apple voices
    POST/v1/images/generationsFLUX.2 Klein text-to-image with base64 PNG output
    POST/v1/images/editsMultipart FLUX.2 Klein reference-image editing
    POST/v1/tokenizevLLM-compatible tokens and counts for the loaded MLX model
    POST/v1/count_tokensAnthropic-style input token count
    POST/v1/batch/completionsMultiplex up to 64 completions over SSE
    POST/v1/chat/completions/{id}/cancelCancel an in-flight generation
    GET/metricsPrometheus afm:* and vLLM-compatible queue, token, throughput, and timing metrics
    GET/openapi.jsonOpenAPI description
    GET/docsInteractive API reference served by AFM

    AFM also implements OpenAI-style file and batch-job endpoints under /v1/files and /v1/batches when the MLX batch service is active.

    Apple-native tools

    The CLI and HTTP server expose useful system frameworks without another service.

    # OCR text or a table from an image/PDF
    afm vision --file invoice.pdf --table
    
    # Other Vision modes: text, table, barcode, classify, saliency, auto
    afm vision --file photo.heic --mode classify --format json
    
    # Speech recognition
    afm speech transcribe --file meeting.wav --format srt
    
    # Text to speech
    afm speech synthesize "Hello from AFM" --voice nova --output hello.aac
    
    # Dedicated OpenAI-compatible embeddings server (default port 9998)
    afm embed
    

    For vision-language models, add --vlm and pass one or more files with --media.

    Performance controls

    Defaults are a good starting point. Use these when the workload calls for them:

    # Reuse prompt KV across requests
    afm mlx -m <model>                         # prefix caching is enabled by default
    afm mlx -m <model> --disable-prefix-caching # explicit opt-out
    
    # Save memory on long context
    afm mlx -m <model> --kv-bits 8
    
    # Fair-queue concurrent requests through one model
    afm mlx -m <model> --concurrent 4
    
    # Strict tool/JSON schemas with xgrammar
    afm mlx -m <model> --enable-grammar-constraints
    
    # Per-request device, memory, timing, and bandwidth estimates
    afm mlx -m <model> --gpu-profile -s "Explain Metal kernels"
    

    Supported checkpoints can also use speculative decoding:

    • --mtp for compatible Qwen models. Qwen3.8 automatically prefetches the separately published MTP head matching the base checkpoint's quantization; use --mtp-model <repo-or-path> to override it.
    • For Qwen Next, the qualified opt-in throughput recipe is --mtp --mtp-depth 3 --qwen-mtp-profile throughput-v2. The earlier throughput-v1 profile remains available. Choose draft depth separately with --mtp-depth. The CLI selection overrides AFM_QWEN_MTP_PROFILE. --qwen-mtp-profile off disables the profile defaults while preserving individual tuning overrides. Omitting the option preserves the environment/provider defaults. The profile remains opt-in. Performance depends on the checkpoint and workload; see the matched-context qualification for exact checkpoints, settings, results, and remaining gaps. No tuning environment variables are required for the qualified recipe.
    • --eagle3 <drafter-directory> for supported dense Gemma4 models
    • --dspark-support <support.gguf> for compatible DwarfStar DSpark workflows

    Read decode optimizations before choosing a checkpoint or interpreting benchmark results.

    Sampling and response controls

    The MLX backend supports temperature, top_p, top_k, min_p, repetition_penalty, presence_penalty, seed, stop, logprobs, and top_logprobs.

    Useful server defaults:

    # Apply one JSON schema when requests omit response_format
    afm mlx -m <model> \
      --guided-json '{"type":"object","properties":{"answer":{"type":"string"}},"required":["answer"]}' \
      --enable-grammar-constraints
    
    # Disable model reasoning/thinking
    afm mlx -m <model> --no-thinking
    
    # Pin chat-template keyword arguments
    afm mlx -m <model> --chat-template-kwargs '{"enable_thinking":false}'
    

    Use AFMKit and AFM as Swift packages

    The independent scouzi1966/AFMKit package defines the provider products:

    • AFMKitCore — provider contracts and core types
    • AFMOpenAICompat — OpenAI-compatible request/response types
    • AFMKitMLX — MLX model loading and inference
    • AFMKitApple — Apple Foundation Models backend
    • AFMKitFoundationModelsMLX — macOS 27 MLX executor bridge
    • AFMKitDwarfStar — DwarfStar runtime integration

    This maclocal-api consumer package separately defines its application adapters:

    • AFMKitFoundationModels — compatibility re-export of AFMKitApple
    • AFMKitFoundationModels27 — macOS 27 application adapters
    • AFMKitFoundationModels27DwarfStar — opt-in DwarfStar macOS 27 adapter
    • AFMKitServices — vision, speech, and embedding services
    • AFMKit — high-level headless inference facade
    • AFMServer — Vapor HTTP layer
    • afm — CLI executable

    AFMKit is pinned to one exact public SwiftPM release so provider source, runtime resources, and the consumer contract advance together. See AFMKit URL consumption for the dependency and publication policy. Release tooling fails closed unless the manifest, lock, public tag, and anonymously fetchable revision all agree.

    AFMKitFoundationModels27DwarfStar remains as a source-compatible re-export; the implementation and runtime lifetime management now live in AFMKit's AFMKitFoundationModelsDwarfStar product. This keeps AFM and independent AFMKit consumers on the same bridge while preserving a one-commit rollback.

    Start with the AFMKit public API guide and the independent AFMKitCore consumer.

    Build from source

    git clone https://github.com/scouzi1966/maclocal-api.git
    cd maclocal-api
    ./build.sh
    

    The build resolves only the revisions in the tracked Package.resolved, initializes pinned submodules, builds the locked WebUI, and packages AFMKit-owned runtime resources without mutating dependency sources. AFMKit is public, so the normal build needs no repository token. Add --install to install under INSTALL_PREFIX (default /usr/local).

    Requirements

    • Apple Silicon Mac
    • macOS 26 or newer for the complete feature set
    • Xcode 27 for development builds
    • Disk and unified memory appropriate for the model you choose

    Small 0.6B–4B quantized models are the easiest way to confirm a setup. Large 30B-class models need substantially more unified memory.

    Documentation map

    Contributing

    Issues, reproducible test cases, documentation improvements, and model-compatibility reports are welcome. Read AGENTS.md and CLAUDE.md before changing build, test, or vendored integration code.

    If AFM is useful to you, star the repository. You may also like Vesta AI Explorer, a full-featured native macOS AI app.

    License

    MIT