Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ jobs:
matrix:
os: [ubuntu-latest]
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14"]
include:
- os: macos-latest
python-version: "3.12"
- os: windows-latest
python-version: "3.12"

steps:
- name: Check out repository
Expand Down Expand Up @@ -46,6 +51,15 @@ jobs:
pip install -e .[server] httpx numpy
pytest tests/test_server.py

- name: Official SDK interoperability
if: matrix.python-version == '3.12' && matrix.os == 'ubuntu-latest'
env:
LOCAL_LLM_KIT_OPENAI_INTEROP: '1'
LOCAL_LLM_KIT_MCP_INTEROP: '1'
run: |
pip install openai 'mcp>=2.0,<3'
pytest tests/test_responses_sdk.py tests/test_mcp_interop.py

- name: Import smoke test (light core, no heavy deps)
run: >
python -c
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ build/
dist/
.venv/
docs/_build/
*.egg-info/
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
- Native Apple Foundation Models adapter and apfel profile, including native schemas, fresh sessions, inline image attachments, exact token counting, cooperative timeouts and streaming stop handling.
- Server discovery, native capability metadata, `doctor` CLI and a locality guard that rejects unknown or remote routes.
- Shared transient HTTP retry policy with finite delays and cleanup, plus the Transformers server preset.
- MCP tools client over stdio and Streamable HTTP, namespaced registration, deadlines and official SDK interoperability tests.
- Bounded agent loop with request-scoped tools, strict argument parsing and shared tool execution; structured chat with optional full JSON Schema validation and Pydantic validation.
- BM25, dense/lexical reciprocal rank fusion, MMR diversity, metadata filters, deletion and a small RAG pipeline.
- Opt-in atomic SQLite conversation logging and lossless tool/message export, plain-text/JSON/YAML templates, and logging CLI commands.
- Measured hardware memory inspection and approximate model/KV memory planning; no guaranteed fit claims.
- Stateless Responses API subset with text/image inputs, function calls/results, schema-format forwarding and SDK-compatible text/tool streaming events.

### Fixed
- Competing tool loops could bypass the new agent's controls; the agent now disables nested execution.
- SSE MCP responses waited for EOF after a result, and notifications restarted deadlines. Results now return promptly within an absolute deadline.
- Structured-output validation accepted invalid field types, and repair changed quoted literals. Schemas now enforce constraints and repair preserves strings.
- Unverified HTTP endpoints could pass the locality check. Unknown routing now fails closed; loopback alone is insufficient.
- Reasoning metadata could be dropped from native chat responses and streams.
- Conversation logs lost original tool IDs, usage and finish reasons, used separate in-memory stores per thread, and could commit partial interactions.
- Windows concurrent model-file publication could fail on transient file locks. Atomic replacement now retries bounded Windows locking errors and preserves the prior model on persistent failure.
- Template loading depended on YAML for plain text, and directory loading hid parse failures.
- Hardware advice fabricated missing measurements and combined separate GPUs into an unrealistic memory budget.

### Validation scope
- Core requirements remain Python 3.9+ with no new mandatory dependencies; Apple SDK and official SDK interoperability have separate version requirements.
- These are unreleased changes. Protocol/SDK tests do not establish performance superiority or certify every runtime/hardware combination.

## [0.2.0] - 2026-10-17

### Added
Expand Down
457 changes: 218 additions & 239 deletions README.md

Large diffs are not rendered by default.

110 changes: 110 additions & 0 deletions docs/source/advanced_features.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
Agents, retrieval and local history
==================================

These features are unreleased additions. See the repository README for runnable
examples and :doc:`community_pr_review` for their provenance and review fixes.

Agents and structured output
-----------------------------

``Agent(llm, tools=[callable], mcp_clients=[connected_server], max_steps=5)``
runs a bounded tool loop. It disables LLM's nested tool execution and uses a
request-local tool registry. Decorated tool names are respected. MCP tools use
``server__tool`` names; the caller manages MCP connection lifetime. Invalid JSON
arguments become error feedback and never pass through JSON repair. Python tool
timeouts limit waiting rather than terminating the worker or undoing side effects.
``AgentResult.tool_calls_executed`` counts attempts, including failed calls.

``llm.chat_structured(messages, schema=..., max_retries=2)`` validates returned
JSON. Dictionary schemas require ``pip install 'local-llm-kit[structured]'``;
Pydantic v1/v2 model classes use their own validator. Native JSON Schema is
forwarded where supported. The helper performs bounded correction turns and
returns validated JSON data, not a Pydantic instance. Remote schema retrieval
is disabled. This does not make prompted JSON a constrained-decoding guarantee.

``repair_json``/``extract_json`` repair presentation errors, preserving quoted
literals, but reject unfinished strings/values. They can close containers and
are intended for opt-in output handling rather than executable actions.

Retrieval
----------

``SimpleVectorStore.search`` retains dense/TF-IDF ranking by default. Explicit
``mode='lexical'`` uses BM25; ``mode='hybrid'`` fuses BM25/dense ranks with RRF.
An embedding function and stored embeddings are required for hybrid search.
``search_hybrid(alpha=...)`` sets the dense rank weight. ``lambda_mult`` enables
MMR diversity when dense vectors exist. Metadata filters accept an exact mapping
or a predicate. ``delete(ids)`` removes the corresponding text, metadata and
vector together; JSON save/load preserves the remaining index.

``RAGPipeline`` connects chunking, storage, retrieval and a citation prompt.
Without an embedder its default works lexically. It returns source records so
the caller can inspect grounding; citations are requested, not validated. The
store is in memory and suited to small collections. Hash embeddings in offline
examples are deterministic fixtures rather than semantic retrieval models.

Conversation storage and templates
-----------------------------------

``ConversationLog(path)`` is opt-in. One locked SQLite connection supports
threads and ``:memory:`` databases. A completed interaction commits atomically.
Messages retain their complete payload, original tool IDs, response usage and
finish reason. ``export_conversation(id, 'openai')`` returns replayable message
payloads. ``log_interaction(..., conversation_id=id)`` accepts new messages or a
full history with a previously stored prefix; the stored prefix is deduplicated.
The original prototype schema is upgraded additively without deleting rows.
Close the store or use a context manager when finished.

``LLM(..., conversation_log=log)`` saves completed chat calls and streams.
Each request creates a conversation snapshot; it does not infer a shared user
session. Interrupted streams are not saved as completed answers. Stored prompts,
images and tool outputs are ordinary local SQLite data.

.. code-block:: bash

local-llm-kit chat --backend echo -m echo --message Hello --conversation-log ./chat.db
local-llm-kit logs list --db ./chat.db
local-llm-kit logs show CONVERSATION_ID --db ./chat.db
local-llm-kit logs export CONVERSATION_ID --db ./chat.db --format openai

``PromptTemplate`` supports ``{{name}}`` and ``{{name|default}}`` text replacement.
It does not evaluate expressions or escape values for JSON. JSON and plain-text
files work with the standard library; YAML needs the optional ``[yaml]`` extra.
Directory loading reports invalid JSON/YAML instead of silently skipping it.

Hardware planning
------------------

``get_system_memory`` reports measured RAM and NVIDIA GPU memory when available,
or zero/notes for unknown values. macOS reclaimable pages approximate available
RAM. Apple unified memory is shared RAM; separate GPU capacities are not summed.

``estimate_model_vram`` estimates GiB for weights, KV cache and overhead for one
sequence. Supply ``num_layers``, ``num_kv_heads`` and ``head_dim`` together to
replace the default Llama-like architecture assumption. Weight quantization,
runtime overhead, backend allocation and batch size still affect peak usage.
``recommend_quantization`` uses 85% of available memory as a planning budget.
It does not guarantee fit or prevent an out-of-memory error.

.. code-block:: bash

local-llm-kit hardware --params-b 8 --context-length 8192
local-llm-kit hardware --params-b 8 --memory-gb 12

Stateless Responses API
------------------------

The development server supports ``POST /v1/responses`` for text/image message
input, instructions, flat function tool definitions, function-call/output
round trips, ``max_output_tokens`` and ``text.format``. Streaming emits the
created/item/content/delta/done/completed lifecycle for text and tool arguments,
with stable IDs and sequence numbers. Usage maps to input/output token names.
An unserved requested model returns an error. Nonstream inference runs outside
the ASGI event loop. Responses returns tool calls for the caller to execute.

Stateful responses, hosted tools, background jobs and reasoning controls are
unsupported and rejected. Native schema enforcement remains model-dependent;
use structured chat for separate returned-data validation. This is a documented
subset, not full OpenAI API parity. The official Python SDK stream manager is
exercised by ``LOCAL_LLM_KIT_OPENAI_INTEROP=1 pytest tests/test_responses_sdk.py``.
The server is a development adapter, not an authenticated multi-user gateway.
35 changes: 35 additions & 0 deletions docs/source/api_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,41 @@ Set ``stream=True`` on chat or completion to receive an iterator. Chat chunks
carry ``choices[0].delta``; text-completion chunks carry ``choices[0].text``.
AirLLM streaming is buffered into one completed backend chunk.

``LLM(..., require_local=True)`` refuses a model the backend reports as routed
off this machine, and raises if the backend could report routing but the lookup
failed. ``llm.detect_backend_capabilities()`` returns the backend's own report
(context length, capabilities, routing) where it supports one; see
:doc:`discovery`.

Server discovery
----------------

.. code-block:: python

from local_llm_kit import discover, find_local_server, probe_endpoint

report = discover() # DiscoveryReport
report.live # live ServerReport objects
report.on_device() # live servers with a local model
report.first_live(require_local=True) # ServerReport or None
report.to_dict() # JSON-ready

server = find_local_server() # first on-device server, or None
single = probe_endpoint("localhost:1234")

``discover`` takes ``extra_urls``, ``include_known``, ``timeout``, ``enrich`` and
``max_workers``. ``probe_endpoint`` takes a base URL in any of the forms
:func:`local_llm_kit.discovery.normalize_base_url` accepts. ``ServerReport``
exposes ``provider``, ``live``, ``latency_ms``, ``error``, ``models``,
``context_window``, ``vision``, ``notes``, ``local_models``, ``remote_models``,
``has_local_models`` and ``all_local``; ``ModelRecord`` exposes ``id``,
``capabilities``, ``context_length``, ``remote``, ``remote_host`` and the
``supports_tools``/``supports_vision``/``supports_embeddings``/
``supports_thinking`` predicates.

Probes are unauthenticated ``GET`` requests to model-listing and metadata
endpoints only: no downloads, no inference, no credentials.

High-level helpers
------------------

Expand Down
99 changes: 90 additions & 9 deletions docs/source/backends.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ not install, launch or reconfigure it.
Runtime coverage and feature limits
-----------------------------------

These 12 runtimes cover desktop apps, local files, Apple Silicon, GPU servers
and offloaded inference. This is a compatibility selection, not a top-ten
ranking: no comparable active-user measurement has been established.
llama.cpp's library and server integrations count as one runtime.
The integrations cover desktop apps, local files, Apple Silicon, GPU servers
and offloaded inference. This is a compatibility selection; no comparable
active-user ranking or cross-engine performance claim is established.

.. list-table:: Capability matrix for this client
:header-rows: 1
Expand All @@ -21,6 +20,14 @@ llama.cpp's library and server integrations count as one runtime.
- Integration
- Tools and structured output
- Embeddings
* - Apple FM (native)
- In-process SDK (``apple-fm``)
- Prompted tools/JSON loop; native ``json_schema`` enforcement
- No adapter embedding method
* - Apfel bridge
- OpenAI-compatible HTTP
- Forwarded; native tools + ``json_schema`` server-side
- No endpoint in this preset
* - Ollama
- Native HTTP
- Native tools/schema forwarding; model-dependent
Expand Down Expand Up @@ -70,12 +77,52 @@ llama.cpp's library and server integrations count as one runtime.
- Forwarded; model/template-dependent
- Requires a loaded embedding model

All server presets have client routing, payload and HTTP/SSE fixture tests.
All server presets have client routing and payload and HTTP/SSE fixture tests.
This is protocol validation, not a real-engine or hardware certification.
Unsupported native tool/schema options may be rejected by the upstream server;
the client does not silently claim those features were enforced. Native vision
is forwarded only through the HTTP adapters. In-process adapters currently
format text; use an HTTP vision model for image inputs.
the client does not silently claim those features were enforced. Vision parts pass through the HTTP adapters and the native Apple attachment
adapter where its SDK/OS supports images; other in-process adapters format text.


Apple Foundation Models (native backend + apfel bridge)
-------------------------------------------------------

Apple Silicon Macs ship an on-device model via the Foundation Models
framework. Local LLM Kit reaches it two ways:

* **Native** (``backend="apple-fm"``): Apple's official
`python-apple-fm-sdk <https://github.com/apple/python-apple-fm-sdk>`_
(``pip install "local-llm-kit[apple-fm]"``). Requires macOS 26+, Xcode 26+
with the SDK agreement accepted, Python 3.10+, and Apple Intelligence
turned on (`support article <https://support.apple.com/en-us/121115>`_).
Sessions are created per request (backend instances are shared through
the client cache), tool calls use the uniform client-side loop, and
``response_format={"type": "json_schema", ...}`` is enforced natively by
the SDK. ``temperature`` (``0`` selects greedy sampling), ``seed``,
``max_tokens`` and ``stop`` are honoured; ``top_p``/``top_k``/penalties
and logprobs have no SDK equivalent and are ignored. data-URL
``image_url`` parts are materialised to temporary files and passed as
``ImageAttachment`` objects (remote URLs are rejected, never downloaded);
image understanding itself needs the macOS 27 SDK. ``count_tokens_exact``
offers exact budgeting via the SDK's async ``token_count``. There is no
on-device embedding endpoint. Everything runs on device; nothing falls
back to Private Cloud Compute or any remote endpoint.
* **Bridge** (``backend="apfel"``): no Xcode needed. Run
`apfel --serve <https://github.com/Arthur-Ficial/apfel>`_ (macOS 26+,
Apple Silicon, Apple Intelligence on), which serves OpenAI-compatible
``POST /v1/chat/completions`` on ``http://localhost:11434/v1``. The
preset strips the sampling fields apfel rejects (``top_k``/penalties),
maps prompt completion to chat (the upstream completions endpoint is absent),
and reports no embedding support.

``python examples/apple_foundation.py`` demonstrates both paths and prints
setup steps when the model or server is unavailable. Contracts are covered
by offline tests with an SDK double
(``tests/test_apple_fm.py``); the opt-in live test
(``LOCAL_LLM_KIT_APPLE_FM_LIVE=1``) needs an eligible Mac and is skipped in
CI. See also `simonw/llm-apple-foundation
<https://github.com/simonw/llm-apple-foundation>`_ for the same SDK used
through the ``llm`` CLI, which informed the sampling/schema mapping here.

Server presets
--------------
Expand All @@ -101,7 +148,8 @@ Server presets
- http://localhost:8080/v1
* - llama-server
- llama-server
- http://localhost:8080/v1 (start with --port 8080)
- http://localhost:9931/v1 (the default since October 2026; the Docker
image and older builds use 8080)
* - Jan
- jan
- http://127.0.0.1:1337/v1 (enable server and configure its API key)
Expand All @@ -114,6 +162,14 @@ Server presets
* - KoboldCpp
- koboldcpp
- http://localhost:5001/v1
* - Apfel bridge
- apfel
- http://localhost:11434/v1 (run ``apfel --serve``; shares Ollama's port)

* - Transformers serve
- transformers-serve
- http://localhost:8000/v1 (run ``transformers serve``;
shares vLLM's default port)

Use the ID of a model already loaded by the server. A preset chooses the
connection URL and protocol parameter mapping. Override the URL with
Expand All @@ -122,6 +178,14 @@ needed. The generic ``openai-compat`` backend supports other servers exposing th
same endpoints. Server and model capabilities determine tool calling, schemas,
vision and embedding availability.

Rather than guessing which port is in use, probe them all with
``local-llm-kit doctor`` — see :doc:`discovery`. It reports what is listening,
reads each server's own capability metadata (Ollama ``/api/show``, llama.cpp
``/props``, LM Studio ``/api/v1/models``, apfel ``/v1/models``), and flags models
that a server routes off the machine. The preset catalog is de-duplicated by
normalised URL and the provider is identified from the server's response, so
several providers sharing a default port is not ambiguous.

.. code-block:: python

from local_llm_kit import LLM
Expand All @@ -141,6 +205,10 @@ Upstream setup references:
* `MLX-LM project <https://github.com/ml-explore/mlx-lm>`_ and its
`server endpoints/options <https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/server.py>`_
* `KoboldCpp API and setup <https://github.com/LostRuins/koboldcpp#apis-and-integrations>`_
* `apfel OpenAI API compatibility <https://github.com/Arthur-Ficial/apfel#openai-api-compatibility>`_

* `transformers serve <https://huggingface.co/docs/transformers/main/en/serving>`_
(``pip install transformers[serving]``; default ``http://localhost:8000``)

For example, launch MLX-LM with prepared weights using
``mlx_lm.server --model /path/to/local/mlx-model --host 127.0.0.1 --port 8080``,
Expand Down Expand Up @@ -205,6 +273,19 @@ models, or ``backend="llamacpp"`` with the ``llamacpp`` extra for local GGUF fil
Tool calls and JSON output use the kit's prompt formatting unless the backend
implements a native capability. Prompted JSON is not a schema-enforcement guarantee.

The ``transformers-serve`` preset connects to a running ``transformers serve``
instance instead of loading weights in-process: same adapter, same model ID
rules as the other presets, default ``http://localhost:8000/v1``.

Transient-failure retries
-------------------------

The HTTP adapters share ``RetryPolicy``. Set ``backend_kwargs={'max_retries': 0}``
to fail fast, pass an integer for the retry count, or a RetryPolicy for finite
delay controls. Selected transient statuses and connection setup failures are
retried. Streaming retries only connection setup, never already emitted output.
See :doc:`discovery` for details.

Offline operation and validation scope
--------------------------------------

Expand Down
Loading
Loading