diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 88ffb51..d4d7112 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 @@ -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 diff --git a/.gitignore b/.gitignore index 8f9f74b..8ca4736 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ build/ dist/ .venv/ docs/_build/ +*.egg-info/ diff --git a/CHANGELOG.md b/CHANGELOG.md index cf204c4..d56938e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 63e89b0..ff48e23 100644 --- a/README.md +++ b/README.md @@ -1,323 +1,302 @@ # Local LLM Kit -[![PyPI version](https://badge.fury.io/py/local-llm-kit.svg)](https://pypi.org/project/local-llm-kit/) -[![Python 3.9+](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org/downloads/) -[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/1Utkarsh1/Local-LLM-kit/blob/v0.2.0/LICENSE) -[![CI](https://github.com/1Utkarsh1/Local-LLM-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/1Utkarsh1/Local-LLM-kit/actions) -[![Docs](https://readthedocs.org/projects/local-llm-kit-package/badge/?version=latest)](https://local-llm-kit-package.readthedocs.io/) -[![Offline ready](https://img.shields.io/badge/offline-echo%20backend-lightgrey.svg)](#offline-mode-no-model-needed) +[![PyPI](https://img.shields.io/pypi/v/local-llm-kit.svg)](https://pypi.org/project/local-llm-kit/) +[![Python](https://img.shields.io/pypi/pyversions/local-llm-kit.svg)](https://pypi.org/project/local-llm-kit/) +[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) -**One Python API for offline models and local LLM servers.** Use the same chat and completion interface with Ollama, AirLLM, SGLang, vLLM, LM Studio, LocalAI, llama.cpp or Hugging Face Transformers; tools, schemas and embeddings follow backend capabilities. Start with the offline echo backend, then connect a real model. Core install stays light (stdlib + `typing-extensions`); inference dependencies are optional. +One Python API for local language models, desktop apps, and inference servers. +Use OpenAI-shaped chat, streaming, tools and structured output while choosing +where your model runs. The core install needs only `typing-extensions`; model +engines and validation packages are optional. -Version **0.2.0** includes the local runtime presets and reliability fixes below. See the [backend compatibility guide](https://github.com/1Utkarsh1/Local-LLM-kit/blob/v0.2.0/docs/source/backends.rst) for tested contracts and runtime limitations, and [llms.txt](https://github.com/1Utkarsh1/Local-LLM-kit/blob/v0.2.0/llms.txt) for a concise project reference. +**Development status:** PyPI **0.2.0** is the current release. Native Apple FM, +MCP, discovery, Responses, agents, hybrid retrieval, logging and the hardware +advisor below are **unreleased changes on this branch**. To try this branch: -> **Scope, honestly stated:** this is a zero-heavy-dependency client + adapter + offline mock — code once against the OpenAI shape, swap backends without rewriting, and test in CI without a GPU. It is not an inference engine (use vLLM/Ollama to serve traffic) and `serve` is a development shim, not production infra. +```bash +git clone https://github.com/1Utkarsh1/Local-LLM-kit.git +cd Local-LLM-kit +git checkout feat/consolidated-community-upgrades +python -m pip install -e '.[structured,server]' +``` -**Created by Utkarsh Rajput ([1Utkarsh1](https://github.com/1Utkarsh1))** +For the released API, use the [0.2.0 documentation](https://github.com/1Utkarsh1/Local-LLM-kit/tree/v0.2.0). +No API key is needed for local inference. Prepare your engine, dependencies and +model weights before disconnecting from the internet. -## 60-second quickstart (Ollama) +## Start with a local model + +Start [Ollama](https://github.com/ollama/ollama), then download a model once: ```bash -pip install "local-llm-kit[ollama]" -ollama pull llama3.2:3b -ollama serve & # usually already running on http://localhost:11434 +ollama pull qwen2.5:0.5b +pip install local-llm-kit +local-llm-kit chat --backend ollama -m qwen2.5:0.5b --message 'Hello' ``` ```python from local_llm_kit import LLM -llm = LLM(model_path="llama3.2:3b", backend="ollama") -resp = llm.chat(messages=[{"role": "user", "content": "Say hi in one sentence."}]) -print(resp["choices"][0]["message"]["content"]) +llm = LLM('qwen2.5:0.5b', backend='ollama') +response = llm.chat([{'role': 'user', 'content': 'Explain recursion briefly.'}]) +print(response['choices'][0]['message']['content']) + +for chunk in llm.chat([{'role': 'user', 'content': 'Write a haiku.'}], stream=True): + print(chunk['choices'][0]['delta'].get('content') or '', end='') ``` -CLI equivalent: +For tests without a model or a server: -```bash -local-llm-kit chat --model llama3.2:3b --backend ollama +```python +llm = LLM('echo', backend='echo') +assert llm.chat([{'role': 'user', 'content': 'Hello'}])['choices'][0]['message']['content'].startswith('Echo:') ``` -## Offline mode (no model needed) - -Every example and the test-suite run without downloads via the `echo` backend: +## Choose your runtime -```bash -python examples/simple_chat.py --backend echo -python examples/tools_structured.py --backend echo -``` +Server presets connect to an engine you have already started; they do not install +or launch it. Always use that server's served model ID. You can override any URL +with `backend_kwargs={'base_url': 'http://127.0.0.1:PORT/v1'}`. -## Installation +| Runtime | `backend` | Connection or extra | +|---|---|---| +| Ollama | `ollama` | Native HTTP; default port 11434 | +| llama.cpp | `llamacpp` / `llama-server` | Local GGUF with `[llamacpp]`, or server port 9931 | +| LM Studio | `lmstudio` | Server port 1234 | +| vLLM | `vllm` | Server port 8000 | +| SGLang | `sglang` | Server port 30000 | +| LocalAI | `localai` | Server port 8080 | +| Jan | `jan` | Server port 1337 | +| GPT4All | `gpt4all` | Server port 4891 | +| MLX-LM | `mlx-lm` | Server port 8080 | +| KoboldCpp | `koboldcpp` | Server port 5001 | +| Hugging Face Transformers | `transformers` / `transformers-serve` | In-process `[transformers]`, or server port 8000 | +| AirLLM | `airllm` | Experimental in-process `[airllm]`; buffered streaming | +| Apple Foundation Models | `apple-fm` | Native `[apple-fm]`, eligible Mac and SDK required | +| apfel | `apfel` | Apple model bridge; server port 11434 | +| Other OpenAI-compatible servers | `openai-compat` | Explicit `base_url` | + +This is a compatibility list. Popularity and speed depend on workload and +hardware. Tools, vision, embeddings and native schema enforcement depend on the +actual engine, model, parser and configuration. GPT4All, MLX-LM and apfel presets +have no embedding endpoint in this adapter. llama-server's current binary uses +9931; older versions and its Docker image may use 8080. See the +[compatibility guide](docs/source/backends.rst) for limits and upstream references. + +## Find running servers and check locality ```bash -pip install local-llm-kit # core only (light) -pip install "local-llm-kit[transformers]" # HF Transformers -pip install "local-llm-kit[airllm]" # optional AirLLM adapter -pip install "local-llm-kit[llamacpp]" # llama.cpp (GGUF) -pip install "local-llm-kit[ollama]" # Ollama convenience client -pip install "local-llm-kit[server]" # `serve` command (FastAPI/uvicorn) -pip install "local-llm-kit[embeddings]" # sentence-transformers, numpy -pip install "local-llm-kit[rag]" # numpy, faiss-cpu, pypdf -pip install "local-llm-kit[all]" # everything +local-llm-kit doctor +local-llm-kit doctor --json --url http://127.0.0.1:9000/v1 +local-llm-kit doctor --require-local ``` -Requires Python 3.9+. The generic `openai-compat` backend (vLLM, LM Studio, llama-server) needs no extra — it speaks HTTP with the standard library. +```python +from local_llm_kit import discover, find_local_server -## Backend comparison +report = discover() +for server in report.live: + print(server.provider, server.base_url, [m.to_dict() for m in server.models]) -| Backend | `backend=` value | What it runs | Needs | Best for | Vision | Embeddings | -|---|---|---|---|---|---|---| -| Echo (mock) | `"echo"` | offline deterministic echo, no model | nothing | tests, CI, docs, offline dev | passes messages through | deterministic stub | -| Transformers | `"transformers"` | HF models via `transformers`+`torch` | `pip install "local-llm-kit[transformers]"` | HF text models on GPU/CPU | text adapter | separate embeddings client | -| AirLLM (experimental adapter) | `"airllm"` | AirLLM offloaded inference | `pip install "local-llm-kit[airllm]"`, prepared weights and suitable hardware | fitting larger models into limited accelerator memory | text only in this adapter | no | -| llama.cpp | `"llamacpp"` | `.gguf` via `llama-cpp-python` | `pip install "local-llm-kit[llamacpp]"` | quantized local text models | use HTTP server for vision | use HTTP server for embeddings | -| Ollama | `"ollama"` | models served by `ollama serve` | Ollama daemon | 5-min local setup | model-dependent | `nomic-embed-text` etc. | -| OpenAI-compatible | `"openai-compat"` | any `POST /v1/chat/completions` server (vLLM, LM Studio, Ollama, llama.cpp server) | server URL | pointing at an existing server | model-dependent | model-dependent | +server = find_local_server(require_local=True) +``` -Auto-detect: `http(s)` model path → `openai-compat`, `ollama:` prefix → `ollama`, `.gguf`/GGML path → `llamacpp`, anything else → `transformers`. Pass `backend=` explicitly for `echo`. +Discovery reads available native metadata from Ollama, llama.cpp, LM Studio and +apfel. A reachable loopback URL or a local-sounding model name alone does not +prove local inference: unknown locality stays unknown. Ollama cloud routes are +marked remote. `LLM(..., require_local=True)` accepts known in-process engines +or a loopback server with verified model metadata, and rechecks before chat and +completion requests. This trusts server metadata; it is not a network sandbox +and does not prevent a model engine from downloading weights or a tool from +using the network. -### Local server presets +HTTP adapters retry connection failures and selected transient statuses with +bounded backoff. Configure `backend_kwargs={'max_retries': 0}` to fail fast or +pass `local_llm_kit.retry.RetryPolicy` for delay controls. Streaming retries only +the connection setup, avoiding repeated tokens after output starts. -Use a model ID that the running server actually serves. These presets use the shared OpenAI-compatible adapter; `backend_kwargs={"base_url": "http://host:port/v1"}` overrides the URL. +## Use Apple's built-in model -| Server | `backend=` | Connection preset | -|---|---|---| -| SGLang | `"sglang"` | `http://localhost:30000/v1` | -| vLLM | `"vllm"` | `http://localhost:8000/v1` | -| LM Studio | `"lmstudio"` | `http://localhost:1234/v1` | -| LocalAI | `"localai"` | `http://localhost:8080/v1` | -| llama-server | `"llama-server"` | `http://localhost:8080/v1`; launch with `--port 8080` | -| Jan | `"jan"` | `http://127.0.0.1:1337/v1`; enable its local server and supply its API key | -| GPT4All | `"gpt4all"` | `http://127.0.0.1:4891/v1`; enable Local API Server in settings | -| MLX-LM | `"mlx-lm"` | `http://127.0.0.1:8080/v1`; run `mlx_lm.server` on Apple Silicon | -| KoboldCpp | `"koboldcpp"` | `http://localhost:5001/v1` | - -Together with native Ollama, Transformers and AirLLM, these cover **12 distinct local runtimes** (llama.cpp has both in-process and server paths). This is a compatibility selection, not a measured popularity ranking. GPT4All and MLX-LM presets provide text/chat; use a separate embedding backend. Native tools, schemas and vision require explicit upstream/model support. See the [capability matrix and setup references](https://github.com/1Utkarsh1/Local-LLM-kit/blob/v0.2.0/docs/source/backends.rst) before choosing a runtime. +```bash +pip install 'local-llm-kit[apple-fm]' +``` ```python -from local_llm_kit import LLM - -llm = LLM(model_path="your-served-model-id", backend="sglang") -result = llm.chat([{"role": "user", "content": "Hello!"}]) -print(result["choices"][0]["message"]["content"]) +llm = LLM('apple-foundationmodel', backend='apple-fm', + backend_kwargs={'timeout': 30}) +print(llm.chat([{'role': 'user', 'content': 'Summarise this idea.'}])) ``` -Native chat forwards messages, tools, JSON schemas, seed and stop sequences to Ollama and OpenAI-compatible servers. Tool calls returned outside the text are preserved, including fragmented streamed arguments. Tool and schema support depends on the server configuration and selected model. Ollama's native API offers automatic tool selection; named choices narrow the available tools, while `required` is not guaranteed by that API. +The native backend needs Python 3.10+, macOS 26+, Xcode 26+ with its SDK agreement +accepted, and an Apple Intelligence-capable Mac with Apple Intelligence enabled. +It creates a fresh SDK session per request, forwards native JSON Schema, supports +streaming stops across chunk boundaries and exposes `count_tokens_exact`. +Inline data-URL images use temporary files; actual vision requires an SDK/OS +version with image support. Unsupported sampling controls are documented. +Use `LLM.achat()` from async code. -Compatibility tests exercise adapter contracts and a local HTTP fixture. They do not certify every server release, model, accelerator or performance level. Setup links and feature limits are in the [backend guide](https://github.com/1Utkarsh1/Local-LLM-kit/blob/v0.2.0/docs/source/backends.rst). +Alternatively, run [apfel --serve](https://github.com/Arthur-Ficial/apfel) and +select `backend='apfel'`. This profile omits unsupported sampling fields, maps +prompt completion to chat, and reports no embedding support. It shares Ollama's +default port; configure separate ports to run both simultaneously. -### AirLLM +## Python tools, MCP and agents ```python -from local_llm_kit import LLM +from local_llm_kit import Agent, tool -llm = LLM( - model_path="/path/to/trusted/local/checkpoint", - backend="airllm", - backend_kwargs={"device": "cuda:0", "max_seq_len": 2048}, -) -response = llm.complete("Explain local inference briefly.", max_tokens=64) -print(response["choices"][0]["text"]) -``` - -The AirLLM adapter is **experimental**: its PyTorch and macOS MLX call contracts have offline tests; real model/GPU inference has not been certified here. Generation is serialized per cached model because offloaded layers are stateful. Streaming returns one completed chunk, and per-call seeds/logprobs are unsupported. The MLX path exposes temperature sampling only. AirLLM may need significant checkpoint/shard disk space and may load model-supplied code; use trusted checkpoints and follow [AirLLM's setup instructions](https://github.com/lyogavin/airllm). +@tool +def add(a: int, b: int) -> int: + """Add two numbers.""" + return a + b -For offline inference, prepare weights and dependencies first, use local checkpoint paths, and set `HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1` when using Hugging Face loaders. The kit does not install or launch external servers. A server preset connects to the endpoint you configure. +llm.add_tool(add) +reply = llm.chat([{'role': 'user', 'content': 'What is 12 + 30?'}]) -```python -from local_llm_kit import LLM - -LLM(model_path="mistralai/Mistral-7B-Instruct-v0.1", backend="transformers") -LLM(model_path="./models/mistral-7b-q4.gguf", backend="llamacpp") -LLM(model_path="llama3.2:3b", backend="ollama") -LLM(model_path="any-name", backend="openai-compat", - backend_kwargs={"base_url": "http://localhost:8080/v1"}) -LLM(model_path="echo", backend="echo") # offline +# Or let the bounded agent own the loop with tools scoped to that agent: +agent = Agent(llm, tools=[add], max_steps=5, tool_timeout=10) +result = agent.run('What is 12 + 30?') +print(result.content, result.success) ``` -## OpenAI-SDK drop-in (talk to any OpenAI client) - -Start the bundled server, then use the stock `openai` package unchanged: +Tool execution uses complete parsed arguments, names scoped to the request, +required-argument checks and a waiting timeout. Invalid or failed calls become +error feedback; truncated arguments are not repaired into executable actions. +A timed-out Python function can keep running, so tools with side effects still +need their own execution controls. A model that supports tool calling is required. +Use `execute_tools=False` to return calls for your application to handle. -```bash -local-llm-kit serve --model llama3.2:3b --backend ollama --port 8000 -# offline smoke test: local-llm-kit serve --backend echo --port 8000 -``` +Connect a trusted MCP server with the same tools interface: ```python -from openai import OpenAI +from local_llm_kit import MCPServer -client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed") -resp = client.chat.completions.create( - model="llama3.2:3b", - messages=[{"role": "user", "content": "Hello!"}], -) -print(resp.choices[0].message.content) +with LLM('qwen2.5:7b', backend='ollama') as llm: + llm.add_mcp_server('files', command='your-mcp-server', args=['/allowed/path']) + # Tools are namespaced files__. llm.close() closes the connection. + reply = llm.chat([{'role': 'user', 'content': 'List the available files.'}]) ``` -See `examples/openai_compatible.py` (falls back to direct `LLM(backend="echo")` when no server / no `openai` package is present, so it runs offline). - -Supported routes: `GET /health`, `GET /v1/models`, `POST /v1/chat/completions` (incl. `stream=true` SSE), `POST /v1/completions`, `POST /v1/embeddings`. +```bash +local-llm-kit mcp tools --command 'your-mcp-server /allowed/path' --json +local-llm-kit mcp call --url http://127.0.0.1:9000/mcp --tool read --args '{"path":"note.txt"}' +``` -> **Security note:** the server returns tool calls **without executing them** unless a request sets `"execute_tools": true`. Only enable that for callers you trust — auto-executing model-chosen functions is arbitrary-code-execution-as-a-feature if your tools are powerful. +The synchronous MCP tools client supports stdio and Streamable HTTP (JSON/SSE), +deadlines, pagination, namespacing and cleanup. Resources, prompts, OAuth and +server-initiated subscriptions are outside this subset. A local subprocess may +itself use the network; transport alone makes no offline guarantee. -## Server snippet +## Validate structured output ```bash -# GGUF file, OpenAI-compatible endpoints on :8000 -local-llm-kit serve --model ./models/mistral-7b-q4.gguf --backend llamacpp --port 8000 - -# Or backed by an upstream OpenAI-compatible server -local-llm-kit serve --backend openai-compat --port 8000 +pip install 'local-llm-kit[structured]' ``` ```python -# Programmatic (requires the `server` extra) -from local_llm_kit.server import create_app, run - -app = create_app(model_path="llama3.2:3b", backend="ollama") -run(app, port=8000) +schema = {'type': 'object', 'properties': {'age': {'type': 'integer', 'minimum': 0}}, + 'required': ['age'], 'additionalProperties': False} +data = llm.chat_structured([{'role': 'user', 'content': 'Return age 3 as JSON.'}], + schema=schema, max_retries=2) +assert data['age'] == 3 ``` -## Modern tools snippet (`@tool` + `tools`/`tool_choice`) +Dictionary schemas use `jsonschema`; Pydantic model validation is supported when +Pydantic is installed. The helper validates types and constraints and asks for +correction within its retry limit. Native constrained decoding is used where the +backend supports it. `extract_json` and `repair_json` are optional output helpers +that preserve quoted values; they are not used to repair executable tool calls. -Legacy `add_function` / `functions=` / `function_call=` still work. New code should use this: +## Retrieval with local documents ```python -from local_llm_kit import LLM, tool - -@tool(description="Get the current weather for a city") -def get_weather(location: str, unit: str = "celsius") -> dict: - """Get the weather for a location.""" - return {"temperature": 22, "unit": unit, "location": location} - -llm = LLM(model_path="echo", backend="echo") -llm.add_tool(get_weather) # legacy: llm.add_function(name, schema, impl) also works - -resp = llm.chat( - messages=[{"role": "user", "content": "Weather in Paris?"}], - tools=[get_weather.spec], - tool_choice="auto", -) -print(resp["choices"][0]["message"]) +from local_llm_kit import RAGPipeline, SimpleVectorStore + +pipeline = RAGPipeline(llm) +pipeline.add_documents(['Local installation uses prepared weights.'], + metadatas=[{'topic': 'setup'}]) +answer = pipeline.query('How does local installation work?', mode='lexical') +print(answer['answer'], answer['sources']) ``` -Full runnable version: `examples/tools_structured.py`. +`SimpleVectorStore` supports default dense/TF-IDF search, explicit BM25, metadata +filters, deletion and JSON persistence. With an `embed_fn`, `mode='hybrid'` fuses +dense/BM25 ranks; `lambda_mult` enables MMR diversity. The small in-memory store +is intended for modest document collections. Hash embeddings in examples are +deterministic fixtures, not semantic search models. Citation prompts do not +prove that an answer is grounded; returned source records let applications check. -## Structured output snippet (`response_format`, JSON Schema) +## Save conversations and reuse prompts ```python -from local_llm_kit import LLM +from local_llm_kit import ConversationLog, PromptTemplate -llm = LLM(model_path="echo", backend="echo") -schema = { - "type": "object", - "properties": {"name": {"type": "string"}, "population": {"type": "integer"}}, - "required": ["name", "population"], -} -try: - resp = llm.chat( - messages=[{"role": "user", "content": "Describe Paris."}], - response_format={"type": "json_schema", "json_schema": {"name": "city", "schema": schema}}, - ) -except TypeError: # older client fallback - resp = llm.chat( - messages=[{"role": "user", "content": "Describe Paris."}], - format="json", - ) -print(resp["choices"][0]["message"]["content"]) +prompt = PromptTemplate('Explain {{topic}} in {{style|plain language}}.').render(topic='recursion') +with ConversationLog('chat.db') as log: + llm = LLM('qwen2.5:0.5b', backend='ollama', conversation_log=log) + response = llm.chat([{'role': 'user', 'content': prompt}]) + print(log.export_conversation(response['conversation_id'], format='openai')) ``` -## Minimal RAG snippet +Logging is opt-in. SQLite writes each completed interaction atomically, including +usage, tool IDs and full message payloads; `:memory:` works across threads. +Completed streams are logged too. An interrupted stream is not saved as a complete +answer. Stored prompts, images and tool outputs are ordinary local database data. +Templates use plain text replacement, not evaluation or automatic JSON escaping; +JSON and plain-text files need no extra, while YAML files need `[yaml]`. -```python -from local_llm_kit import LLM -from local_llm_kit.rag import SimpleVectorStore, build_rag_prompt - -# Lexical mode: no embeddings needed, keyword search works offline. -# Pass embed_fn=... (EmbeddingClient, Ollama, OpenAI-compatible endpoint) -# for semantic retrieval instead. -store = SimpleVectorStore() -store.add( - ["Paris is the capital of France.", "The Eiffel Tower is in Paris."], - metadatas=[{"source": "doc-0"}, {"source": "doc-1"}], -) -hits = store.search("Where is the Eiffel Tower?", k=2) -messages = build_rag_prompt("Where is the Eiffel Tower?", hits) - -llm = LLM(model_path="echo", backend="echo") -resp = llm.chat(messages=messages) -print(resp["choices"][0]["message"]["content"]) +```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 export CONVERSATION_ID --db ./chat.db --format openai +local-llm-kit hardware --params-b 8 --context-length 8192 ``` -Full runnable version: `examples/rag_minimal.py`. +The hardware advisor reports measured or unknown memory and an approximate +single-sequence model/KV budget. It does not combine separate GPUs into a +fictional single device or guarantee a model will fit. Supply actual KV geometry +to `estimate_model_vram` when available. -## Vision snippet (graceful degradation) +## Connect an OpenAI SDK client -```python -from local_llm_kit import LLM +```bash +pip install 'local-llm-kit[server]' openai +local-llm-kit serve --backend ollama --model qwen2.5:0.5b --host 127.0.0.1 --port 8000 +``` -messages = [{ - "role": "user", - "content": [ - {"type": "text", "text": "What is in this image?"}, - {"type": "image_url", "image_url": {"url": "https://example.com/cat.jpg"}}, - ], -}] - -for backend in ("ollama", "openai-compat", "echo"): - try: - llm = LLM(model_path="llava # or model your server hosts", backend=backend) - print(llm.chat(messages=messages)["choices"][0]["message"]["content"]) - break - except Exception as e: - print(f"{backend} unavailable, falling back ({e})") +```python +from openai import OpenAI +client = OpenAI(base_url='http://127.0.0.1:8000/v1', api_key='unused') +response = client.responses.create(model='qwen2.5:0.5b', input='Hello', store=False) +print(response.output_text) ``` -Text-only backends receive the `text` parts and ignore images instead of crashing. Runnable demo: `examples/vision_chat.py`. +The development server exposes chat/completions, completions, embeddings, model +listing and a **stateless Responses subset**: text/image message input, +instructions, function calls/results, `text.format`, and text/tool SSE lifecycles. +Responses returns tools for the caller to execute. Stateful responses, built-in +hosted tools, reasoning controls and background jobs are rejected. This is not +full OpenAI API parity or a hardened multi-user inference gateway. Use a native +embedding backend for semantic embeddings; the development fallback is a fixture. -## CLI +## Development and validation ```bash -local-llm-kit chat --model llama3.2:3b --backend ollama --system "You are helpful." -local-llm-kit complete --model ./m.gguf --backend llamacpp --prompt "Once upon a time," -local-llm-kit serve --backend echo --port 8000 -local-llm-kit pull owner/repo:file.gguf --output-dir ./models -local-llm-kit pull owner/repo --filename file.gguf --revision main --force -local-llm-kit chat --backend sglang --model your-served-model-id -q "Hello" -local-llm-kit list -local-llm-kit embed --model nomic-embed-text --backend ollama --text "hello world" +pip install -e '.[dev,server]' httpx openai mcp +ruff check . +black --check . +pytest +LOCAL_LLM_KIT_OPENAI_INTEROP=1 pytest tests/test_responses_sdk.py +LOCAL_LLM_KIT_MCP_INTEROP=1 pytest tests/test_mcp_interop.py ``` -All `chat`/`complete`/`embed` commands accept `--backend echo|transformers|llamacpp|ollama|openai-compat`. Run any command with `--help` for flags. - -Server presets and `airllm` are also accepted by the CLI. `pull` reuses repository/revision-specific and URL-specific caches; `--force` refreshes a download. Failed transfers preserve existing complete files. URL cache paths now include a URL hash, so older flat URL caches may be downloaded once again. - -## Examples - -| File | Shows | Offline? | -|---|---|---| -| `examples/simple_chat.py` | streaming chat loop | `--backend echo` | -| `examples/openai_compatible.py` | stock OpenAI client vs local server | yes (falls back to `echo`) | -| `examples/tools_structured.py` | `@tool` + `response_format` | yes | -| `examples/rag_minimal.py` | chunk → store → retrieve → chat | yes | -| `examples/vision_chat.py` | `image_url` message, graceful fallback | yes | - -## Migration: 0.1.x → 0.2.0 - -Backwards compatible: `LLM` / `chat` / `complete` / `add_function` keep working. - -| 0.1.x | 0.2.0 (preferred) | Notes | -|---|---|---| -| `functions=[...]` | `tools=[...]` | `functions` still accepted, normalized internally | -| `function_call="auto"` | `tool_choice="auto"` | same | -| `format="json"` | `response_format={"type": "json_object"}` or `json_schema` | `format` still accepted as shorthand | -| backends `transformers`/`llamacpp` | + `echo`, `ollama`, `openai-compat` | `echo` needs no deps | -| no server | `local-llm-kit serve` + `local_llm_kit.server` | needs `server` extra | -| no RAG | `local_llm_kit.rag` + `local_llm_kit.embeddings` | stdlib core, numpy optional | -| images unsupported | `content: [{"type":"image_url",...}]` | text fallback on text-only models | - -Rename checklist: replace `functions=` with `tools=` (wrap each spec as `{"type":"function","function":spec}` — or just pass `@tool` functions, the helper does it), replace `format="json"` with `response_format`, pin new extras in your requirements. - -## License / Contributing +Python 3.9+ is supported by the core. Official SDK interoperability checks use +Python 3.10+ where their dependencies require it. Offline protocol fixtures verify +routing and payload contracts; they do not certify all engines or GPU hardware. +Native Apple live tests require `LOCAL_LLM_KIT_APPLE_FM_LIVE=1` on an eligible Mac. -MIT. Contributions welcome — see `CONTRIBUTING.md`. +See [examples](examples), the [API reference](docs/source/api_reference.rst), +[contribution guide](CONTRIBUTING.md), [changelog](CHANGELOG.md), and +[PR consolidation record](docs/source/community_pr_review.rst). +Report reproducible bugs through [GitHub Issues](https://github.com/1Utkarsh1/Local-LLM-kit/issues). +Local LLM Kit is licensed under [MIT](LICENSE). diff --git a/docs/source/advanced_features.rst b/docs/source/advanced_features.rst new file mode 100644 index 0000000..f8d1740 --- /dev/null +++ b/docs/source/advanced_features.rst @@ -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. diff --git a/docs/source/api_reference.rst b/docs/source/api_reference.rst index eb59094..5e2218c 100644 --- a/docs/source/api_reference.rst +++ b/docs/source/api_reference.rst @@ -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 ------------------ diff --git a/docs/source/backends.rst b/docs/source/backends.rst index f24f777..eef6fea 100644 --- a/docs/source/backends.rst +++ b/docs/source/backends.rst @@ -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 @@ -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 @@ -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 `_ + (``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 `_). + 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 `_ (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 +`_ for the same SDK used +through the ``llm`` CLI, which informed the sampling/schema mapping here. Server presets -------------- @@ -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) @@ -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 @@ -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 @@ -141,6 +205,10 @@ Upstream setup references: * `MLX-LM project `_ and its `server endpoints/options `_ * `KoboldCpp API and setup `_ +* `apfel OpenAI API compatibility `_ + +* `transformers serve `_ + (``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``, @@ -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 -------------------------------------- diff --git a/docs/source/community_pr_review.rst b/docs/source/community_pr_review.rst new file mode 100644 index 0000000..f04a401 --- /dev/null +++ b/docs/source/community_pr_review.rst @@ -0,0 +1,74 @@ +Community PR consolidation +=========================== + +This branch consolidates the useful parts of PRs 9 through 15 against main +commit ``62305685373878ffd3a6a2097c310dd7d801c20a``. Selection is based on code, +reproduced failures and tests. Research-ledger row counts and feature counts +are not performance or quality evidence. Raw ledgers remain in the original PRs. + +Feature provenance +------------------- + +.. list-table:: Reviewed selections + :header-rows: 1 + + * - Source PR + - Retained and completed + - Excluded or replaced + * - `9 `_ + - Native Apple sessions, schemas, image attachment adapter, token counting and apfel profile; added effective timeouts/cancellation and streaming stops. + - Unreachable duplicate block; ineffective waiting timeouts. + * - `10 `_ + - Reasoning metadata propagation and explicit apfel completion-to-chat mapping. + - Duplicate Apple adapter that dropped important messages/options; generic fallback based on error-message substrings. + * - `11 `_ + - Responses subset, upstream model listing, atomic tool-exchange history, MMR and hybrid retrieval; completed SDK-compatible input/output and streaming. + - Duplicate retry implementation; incomplete Responses event/usage conversion. + * - `12 `_ + - Agent loop, validated structured output, BM25/RRF/filter/delete pipeline and hardware guidance; repaired and connected public APIs/CLI. + - Blocking MCP transport, JSON repair for executable arguments, fabricated memory measurements and guaranteed-fit claims. + * - `13 `_ + - Stronger MCP transport/host/CLI; fixed kept-open SSE and deadlines, atomic registration and cleanup; completed explicit 2026 stateless revision. + - Reading an entire SSE response before returning a matched result; locality claims based only on stdio. + * - `14 `_ + - Opt-in SQLite logging, templates and history CLI; made writes atomic, preserved payloads/IDs and fixed thread sharing and file parsing. + - Guessing truncated tool arguments, automatic replacement of arbitrary requested models with Apple FM, duplicate adapters and malformed CI placement. + * - `15 `_ + - Discovery/doctor, native capability metadata, shared HTTP retries and current llama-server port; repaired locality, IPv6 and retry/resource validation. + - Treating unverified OpenAI-compatible endpoints as local; nonfinite retry delays. + +Concrete failures addressed +---------------------------- + +* PR12's required integer schema accepted a string; JSON repair changed quoted + ``True, None`` text. Full JSON Schema validation now enforces constraints; + output repair protects string values. +* PR15's local-only guard accepted an arbitrary remote HTTPS endpoint. Unknown + routing now fails closed and generic loopback listings alone are insufficient. +* PR13 could time out despite already receiving a matching MCP SSE result, as + it waited for connection closure. Parsing now returns immediately at that result. +* PR12's agent and LLM both owned tool loops. The agent now disables nested + execution, uses strict arguments and shares one scoped executor. +* PR14's tool repair could complete a truncated filesystem path into an action. + Its parser change is excluded; regression tests ensure it cannot execute. +* PR14's plain-text template test failed without PyYAML. Plain text now loads + independently, and malformed directory entries produce visible errors. +* The original logging implementation lost call linkage, response token counts + and finish reasons, split in-memory databases across threads and committed + partial interactions. Transactions and full-payload storage address these. + +Validation boundaries +---------------------- + +The offline suite uses real localhost HTTP fixtures and subprocesses without +model downloads. Optional interoperability tests drive the official OpenAI +Python SDK and official MCP Python SDK (legacy and 2026 stateless, stdio and +HTTP JSON/SSE). CI tests Python 3.9--3.14 and includes platform checks. + +Native Apple runtime inference requires an eligible Mac and SDK setup; +AirLLM/GPU behavior and every external engine/model combination are not +certified by protocol tests. The added Windows job exposed a concurrent model-file +publication race; bounded Windows lock-error retries preserve atomic replacement +and the prior cache on persistent failure. Platform-specific path and connection +error assumptions in tests were corrected. No supported-server popularity ranking, +performance superiority or guaranteed memory fit is established. diff --git a/docs/source/discovery.rst b/docs/source/discovery.rst new file mode 100644 index 0000000..38e6e3b --- /dev/null +++ b/docs/source/discovery.rst @@ -0,0 +1,101 @@ +Discover servers and model capabilities +====================================== + +These APIs are unreleased additions. ``discover()`` probes known loopback +endpoints concurrently without generating text. ``probe_endpoint(url)`` checks +one endpoint; extra URLs can be supplied to discovery. Authentication is not +handled by discovery, so an authenticated server may appear unavailable. + +.. code-block:: bash + + local-llm-kit doctor + local-llm-kit doctor --json --url http://127.0.0.1:9000/v1 + local-llm-kit doctor --require-local + +The CLI returns zero when a live server is found, or when a verified local model +is found if ``--require-local`` is set. JSON includes failures and notes. + +.. code-block:: python + + from local_llm_kit import discover, find_local_server, probe_endpoint + + report = discover(timeout=0.75) + for server in report.live: + for model in server.models: + locality = 'remote' if model.remote else ('local' if model.local_verified else 'unknown') + print(server.provider, model.id, model.capabilities, locality) + + server = find_local_server(require_local=True) # a report or None + single = probe_endpoint('http://127.0.0.1:1234/v1') + +What is measured +---------------- + +The OpenAI model list identifies a reachable server and served IDs. When the +provider can be recognized from its response, native metadata may enrich it: + +* Ollama: ``/api/tags`` and ``/api/show`` for routing, capabilities and context. +* llama.cpp: ``/props`` for model path, configured context and modality flags. +* LM Studio: native model API for capabilities and loaded instances. +* apfel: capability fields in the model list. + +A connection preset or port does not establish model capabilities. Missing +metadata remains unknown. Reports identify providers on a best-effort basis; +proxies can hide or imitate another server's response. + +Local execution guard +--------------------- + +A loopback address alone does not establish local inference. For example, an +Ollama cloud route is accessible through a local daemon but executes elsewhere. +``ServerReport.local_models`` requires loopback plus explicit provider metadata; +``local_only()`` requires every listed model to satisfy it. + +.. code-block:: python + + from local_llm_kit import LLM + + llm = LLM('qwen2.5:0.5b', backend='ollama', require_local=True) + llm.assert_local() # raises if the route is remote or cannot be verified + +Known in-process engines are accepted. Ollama requires successful native +routing metadata. Generic OpenAI-compatible servers must expose native +metadata that verifies the requested model. Unknown routing fails closed. +Checks repeat before chat/completion, including a reused client. + +This is a metadata check, not a network sandbox. It trusts the local server, +does not prohibit engine downloads, and does not constrain tools. Prepare model +weights and dependencies separately for offline use. Remote URLs, unavailable +authenticated endpoints, SSH tunnels and opaque proxies cannot be assumed local. + +Capability lookup and retries +------------------------------ + +``backend_kwargs={'auto_detect_capabilities': True}`` enables Ollama capability +lookup when constructing a client; otherwise its configured context remains a +fallback. Discovery and the explicit ``detect_backend_capabilities()`` API read +the server's metadata. Detection errors are returned with the result. + +Inference HTTP adapters use a shared retry policy for selected transient +statuses and connection failures. Discovery uses short per-probe timeouts and +no inference retry/backoff. Configure inference with ``max_retries``: + +.. code-block:: python + + from local_llm_kit.retry import RetryPolicy + + llm = LLM('served-model', backend='vllm', backend_kwargs={ + 'max_retries': RetryPolicy(max_retries=3, initial_delay=0.5, max_delay=8), + }) + +Only connection setup is retried for streams, since replaying emitted output +would duplicate tokens. Delays must be finite; Retry-After delta seconds are +bounded. A total inference deadline is still controlled by the backend timeout. + +Validation scope +----------------- + +Offline HTTP fixtures verify these contracts. ``LOCAL_LLM_KIT_LIVE=1 pytest +tests/test_live_servers.py`` enables checks against existing local servers; +individual skips mean a required engine/model was not available. The tests do +not download models or establish cross-engine performance rankings. diff --git a/docs/source/examples.rst b/docs/source/examples.rst index 4b143dd..d91379d 100644 --- a/docs/source/examples.rst +++ b/docs/source/examples.rst @@ -12,6 +12,8 @@ fully offline and deterministic; it does not measure model quality. python examples/rag_minimal.py --backend echo --model echo python examples/vision_chat.py --backend echo --model echo python examples/openai_compatible.py + python examples/apple_foundation.py # eligible Mac only; else setup steps + python examples/apple_foundation.py --bridge # needs `apfel --serve` running ``simple_chat.py`` demonstrates streaming and multi-turn calls. ``tools_structured.py`` demonstrates modern tools and JSON output. @@ -19,6 +21,9 @@ fully offline and deterministic; it does not measure model quality. ``vision_chat.py`` shows text fallback; a meaningful image answer needs a vision model and a supporting HTTP backend. ``openai_compatible.py`` attempts the local HTTP server and falls back to echo if it is unavailable. +``apple_foundation.py`` uses Apple's on-device model natively +(``--bridge`` uses ``apfel --serve``); both print setup steps instead of +failing when the model or server is unavailable. For a prepared Ollama model: diff --git a/docs/source/index.rst b/docs/source/index.rst index 8fa049f..78a9bcf 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -9,6 +9,7 @@ Welcome to local_llm_kit's documentation! installation quickstart + discovery backends tutorials @@ -19,6 +20,8 @@ Welcome to local_llm_kit's documentation! models api_reference examples + mcp + advanced_features best_practices .. toctree:: @@ -35,15 +38,18 @@ Welcome to local_llm_kit's documentation! contributing changelog + community_pr_review Features -------- * OpenAI-compatible API interface * Local model adapters: Transformers, llama.cpp and optional experimental AirLLM -* Native Ollama chat and HTTP presets covering 12 local runtimes (see :doc:`backends`) +* Native Ollama/Apple chat and HTTP runtime presets (see :doc:`backends`) +* Server discovery and real capability reporting, with an on-device guard (see :doc:`discovery`) * Chat completion API * Function calling capability +* MCP (Model Context Protocol) host: discover and call tools from MCP servers * Streaming responses * JSON mode output * Memory management diff --git a/docs/source/installation.rst b/docs/source/installation.rst index bed4d30..e35dd38 100644 --- a/docs/source/installation.rst +++ b/docs/source/installation.rst @@ -26,6 +26,7 @@ Select optional dependencies as needed: pip install "local-llm-kit[transformers]" pip install "local-llm-kit[llamacpp]" pip install "local-llm-kit[airllm]" + pip install "local-llm-kit[apple-fm]" # macOS 26+, Xcode 26+, Python 3.10+ pip install "local-llm-kit[server]" pip install "local-llm-kit[embeddings]" pip install "local-llm-kit[rag]" diff --git a/docs/source/mcp.rst b/docs/source/mcp.rst new file mode 100644 index 0000000..8237a5e --- /dev/null +++ b/docs/source/mcp.rst @@ -0,0 +1,126 @@ +MCP tools (Model Context Protocol) +================================== + +`Model Context Protocol `_ (MCP) is a standard +way for applications to expose *tools* to an LLM host. ``local_llm_kit`` can act +as an MCP **host**: it connects to one or more MCP servers, discovers the tools +they advertise, converts them to OpenAI ``tools`` specs, and feeds them to your +local model — including the auto-execution tool loop. + +Why it matters: instead of hand-writing a tool for every capability, you point +Local LLM Kit at any MCP server (filesystem, git, sqlite, fetch, a private API, +...) and its tools become available to a local model. + +Design notes +------------ + +* **Stdlib only.** The client lives in ``local_llm_kit.mcp`` and imports the + Python standard library (``subprocess``, ``urllib``, ``json``, ...). The light + core is unchanged and no new dependency is required. In particular, the + official ``mcp`` SDK requires Python >= 3.10, while Local LLM Kit keeps + working on Python 3.9. +* **Two transports.** ``stdio`` (a local server launched as a subprocess) and + ``http`` (Streamable HTTP JSON-RPC, JSON body or request-scoped SSE). +* **Explicit connections.** A local stdio process can itself use the network. + Select trusted tools and configure their network behavior for offline use. + +Quick start (Python) +-------------------- + +.. code-block:: python + + from local_llm_kit import LLM + from local_llm_kit.mcp import MCPServer + + # 1. Connect to a server and see what it offers. + with MCPServer( + "fs", + command="npx", + args=["-y", "@modelcontextprotocol/server-filesystem", "/tmp"], + ) as server: + for tool in server.tools(): + print(tool.name, "-", tool.description) + + # 2. Register its tools on a model and chat normally. + llm = LLM(model_path="qwen2.5-0.5b-instruct-q4_k_m.gguf", backend="llamacpp") + llm.add_mcp_server("fs", command="npx", args=[...]) # or pass an MCPServer + reply = llm.chat([{"role": "user", "content": "List the files in /tmp"}]) + llm.close() # closes MCP connections too + +Discovered tools are namespaced ``__`` by default (so two servers +can both expose ``search``); pass ``prefix=False`` to keep the raw names, or a +string to choose the namespace. ``include=[...]`` / ``exclude=[...]`` filter by +the server's own tool names. + +Quick start (CLI) +----------------- + +Inspect and call tools without writing code: + +.. code-block:: bash + + # List the tools a server advertises. + local-llm-kit mcp tools --command "npx -y @modelcontextprotocol/server-filesystem /tmp" + + # Emit them as OpenAI tool specs (JSON). + local-llm-kit mcp tools --command "uvx mcp-server-git" --json + + # Call one tool. + local-llm-kit mcp call --command "uvx mcp-server-git" --tool git_status --args '{"repo_path": "."}' + + # Remote (Streamable HTTP) server, with an extra header. + local-llm-kit mcp tools --url https://example.com/mcp --header "Authorization: Bearer $TOKEN" + +Chat with a model and MCP tools attached: + +.. code-block:: bash + + local-llm-kit chat -m ./models/qwen.gguf --backend llamacpp \ + --mcp-command "npx -y @modelcontextprotocol/server-filesystem /tmp" + +``--mcp-command`` and ``--mcp-url`` may be repeated. When any server is +connected, tool execution is enabled for that session so the model can actually +use the tools. + +Protocol coverage +----------------- + +By default the client uses a legacy ``initialize`` handshake for compatibility +with existing servers, followed by ``tools/list`` (with pagination) and +``tools/call``. Select ``MCPServer(..., protocol_version='2026-07-28')`` for the +current stateless revision: it uses ``server/discover``, per-request protocol +and client metadata, plus HTTP method/name headers. An unsupported explicit +revision fails rather than silently claiming compatibility. + +Both paths are exercised against the official Python MCP SDK. The tools client +flattens text content; images/audio/resources use descriptive placeholders. +This does not implement resources, prompts, subscriptions, OAuth or interactive +multi-round requests. Protocol references: +`MCP SDK version negotiation `_ +and `MCP lifecycle `_. + +Content-block flattening returns ``isError`` results as +:class:`~local_llm_kit.mcp.MCPToolError`, which the tool loop surfaces as an +ordinary tool-output string rather than a crash. + +Security +-------- + +MCP servers are powerful — a filesystem server can read and write files, a shell +server can run commands. Treat a server command exactly like running that +program yourself: + +* Prefer local ``stdio`` servers you trust; vet the package before ``npx``/``uvx``. +* Only point ``--url`` at endpoints you control. +* Tool execution can be disabled per call with ``execute_tools=False``. + +Limitations +----------- + +* The client implements the tools surface (``tools/list``, ``tools/call``). + MCP *resources* and *prompts* are not exposed as tools. +* HTTP transport requires the server to answer a single POST with either a JSON + body or an SSE stream; long-lived server-to-client streaming and OAuth + authorization flows are not implemented. +* Not every local model is good at tool calling; a capable instruction-tuned + model is still required. See :doc:`models`. diff --git a/examples/apple_foundation.py b/examples/apple_foundation.py new file mode 100644 index 0000000..020afa9 --- /dev/null +++ b/examples/apple_foundation.py @@ -0,0 +1,102 @@ +""" +Apple Foundation Models example: on-device inference with zero setup. + +Two paths, same OpenAI-shaped API: + +1. Native (recommended on eligible Macs):: + + pip install "local-llm-kit[apple-fm]" # macOS 26+, Xcode 26+, Python 3.10+ + + from local_llm_kit import LLM + + llm = LLM(model_path="apple-foundationmodel", backend="apple-fm") + print(llm.chat([{"role": "user", "content": "Say hi in one sentence."}])) + +2. Bridge (no Xcode needed):: + + brew install apfel # macOS 26+, Apple Silicon, Apple Intelligence on + apfel --serve # serves http://localhost:11434/v1 + + The ``apfel`` preset speaks to that server with the shared + OpenAI-compatible adapter (same code path as vLLM/LM Studio presets). + +Run: python examples/apple_foundation.py [--bridge] [--model MODEL] +""" + +import argparse +import sys + +PREREQUISITES = """\ +Apple Foundation Models prerequisites (https://support.apple.com/en-us/121115): + + native: macOS 26+, Apple Intelligence-capable Mac with Apple Intelligence + on, Xcode 26+ (SDK agreement accepted), Python 3.10+, + pip install "local-llm-kit[apple-fm]" + bridge: macOS 26+, Apple Silicon, Apple Intelligence on, `brew install apfel` + then `apfel --serve` +""" + + +def _preflight_native(): + from local_llm_kit.backends.apple_fm import AppleFMBackend + + ok, reason = AppleFMBackend.is_available() + if not ok: + print("Apple Foundation Models unavailable: %s" % reason) + print(PREREQUISITES) + return False + return True + + +def run_native(model, message): + if not _preflight_native(): + return 2 + from local_llm_kit import LLM + + llm = LLM(model_path=model, backend="apple-fm") + response = llm.chat([{"role": "user", "content": message}]) + print(response["choices"][0]["message"]["content"]) + return 0 + + +def run_bridge(model, message, base_url): + from local_llm_kit import LLM + + llm = LLM( + model_path=model, + backend="apfel", + backend_kwargs={"base_url": base_url}, + ) + try: + response = llm.chat([{"role": "user", "content": message}]) + except ConnectionError as exc: + print("Could not reach an OpenAI-compatible server: %s" % exc) + print("Start one first, e.g. `apfel --serve`, then retry.") + return 2 + print(response["choices"][0]["message"]["content"]) + return 0 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Chat with Apple's on-device model.") + parser.add_argument("--model", "-m", default="apple-foundationmodel") + parser.add_argument( + "--message", + "-q", + default="Say hi in one sentence.", + help="Single message to send (default: a greeting prompt).", + ) + parser.add_argument( + "--bridge", + action="store_true", + help="Use the apfel bridge server instead of the native SDK backend.", + ) + parser.add_argument( + "--base-url", + default="http://localhost:11434/v1", + help="Bridge server URL (default: apfel --serve default).", + ) + args = parser.parse_args() + if args.bridge: + sys.exit(run_bridge(args.model, args.message, args.base_url)) + sys.exit(run_native(args.model, args.message)) diff --git a/examples/conversation_logging.py b/examples/conversation_logging.py new file mode 100644 index 0000000..83c4e22 --- /dev/null +++ b/examples/conversation_logging.py @@ -0,0 +1,81 @@ +""" +Example: SQLite conversation logging + prompt templates with local_llm_kit. + +Demonstrates the Phase 2 features: + * PromptTemplate / TemplateRegistry for reusable prompts. + * ConversationLog for persisting conversations, messages, and tool calls. + * LLM(conversation_log=...) for automatic interaction logging. + +Runs fully offline with ``--backend echo``. + +Usage: + python examples/conversation_logging.py --backend echo --prompt "Hello" +""" + +import os +import tempfile + +from local_llm_kit import ( + LLM, + ConversationLog, + register_template, + render_template, +) + + +def main(): + import argparse + + from local_llm_kit.backends import BACKENDS + + parser = argparse.ArgumentParser(description="Conversation logging demo") + parser.add_argument("--backend", "-b", choices=sorted(BACKENDS), default="echo") + parser.add_argument("--model", "-m", default="echo") + parser.add_argument("--prompt", "-q", default="Hello, how are you?") + parser.add_argument( + "--db", + default=None, + help="SQLite log path (default: a temp file for this demo).", + ) + args = parser.parse_args() + + # --- Register a reusable prompt template ------------------------------- + register_template("greeting", "You are {{model}}, a helpful assistant.") + + # --- Set up the SQLite conversation log (stdlib sqlite3 only) ---------- + db_path = args.db or os.path.join(tempfile.mkdtemp(), "demo_chat.db") + log = ConversationLog(db_path) + print("Logging conversations to: {0}".format(db_path)) + + # --- Create an LLM wired to the log ----------------------------------- + system_prompt = render_template("greeting", model=args.model) + llm = LLM( + model_path=args.model, + backend=args.backend, + conversation_log=log, + ) + + # --- Send a message (automatically logged) ----------------------------- + response = llm.chat( + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": args.prompt}, + ], + tools=[], + ) + reply = response["choices"][0]["message"] + print("Assistant: {0}".format(reply.get("content", reply))) + + # --- List conversations from the DB ------------------------------------- + convs = log.get_conversations(10) + print("\nLogged {0} conversation(s).".format(len(convs))) + if convs: + cid = convs[0]["id"] + print("\n--- Exported transcript ---") + print(log.export_conversation(cid, format="text")[:500]) + + log.close() + + +if __name__ == "__main__": + main() diff --git a/examples/discover_servers.py b/examples/discover_servers.py new file mode 100644 index 0000000..4a49398 --- /dev/null +++ b/examples/discover_servers.py @@ -0,0 +1,115 @@ +"""Find running local LLM servers and report what they can actually do. + +Defaults to loopback metadata probes; extra URLs are explicit. No model downloads. +The optional --chat flag performs inference. +If nothing is listening it explains what to start instead of failing. + + python examples/discover_servers.py + python examples/discover_servers.py --url localhost:9000 + python examples/discover_servers.py --json + python examples/discover_servers.py --require-local # exit 1 if not on-device +""" + +import argparse +import json +import sys + +from local_llm_kit import LLM, discover, find_local_server + + +def describe(server): + print("\n%s [%s] %sms" % (server.base_url, server.provider, server.latency_ms)) + if server.context_window: + print(" server context window: %d tokens" % server.context_window) + if server.vision is not None: + print(" server reports vision: %s" % ("yes" if server.vision else "no")) + for model in server.models: + bits = [] + if model.context_length: + bits.append("ctx %d" % model.context_length) + if model.capabilities: + bits.append(", ".join(model.capabilities)) + suffix = "" + if model.remote: + suffix = " OFF-DEVICE -> %s" % (model.remote_host or "remote") + print(" %-40s %s%s" % (model.id[:40], " ".join(bits), suffix)) + for note in server.notes: + print(" note: %s" % note) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--url", + dest="urls", + action="append", + default=None, + help="extra endpoint to probe (repeatable)", + ) + parser.add_argument("--timeout", type=float, default=0.75) + parser.add_argument("--json", action="store_true", help="print the raw report") + parser.add_argument( + "--require-local", + action="store_true", + help="exit non-zero unless an on-device model is available", + ) + parser.add_argument( + "--chat", action="store_true", help="also run one prompt against the first on-device model" + ) + args = parser.parse_args(argv) + + report = discover(extra_urls=args.urls, timeout=args.timeout) + + if args.json: + print(json.dumps(report.to_dict(), indent=2)) + else: + print( + "Probed %d endpoints in %sms; %d responded." + % (report.probed, report.elapsed_ms, len(report.live)) + ) + for server in report.live: + describe(server) + for server in report.offline: + if server.status is not None: + print("\nReachable but not ready: %s (%s)" % (server.base_url, server.error)) + + on_device = report.on_device() + if args.json and not args.chat: + return 0 if (on_device if args.require_local else report.live) else 1 + if not report.live: + print("\nNo local LLM server answered. Start one, for example:") + print(" ollama serve && ollama pull qwen2.5:0.5b") + print(" python examples/discover_servers.py") + elif not on_device: + print("\nServers are up; no model has verified on-device execution metadata.") + else: + print("\nOn-device model available on %s" % on_device[0].provider) + + if args.chat: + # find_local_server() is the convenience form of the loop above. + server = find_local_server(extra_urls=args.urls, timeout=args.timeout) + if server is None: + print("\n--chat needs a server offering an on-device model.") + return 1 + model = server.local_models[0] + print("\nPrompting %r (this loads the model and can take a moment)..." % model.id) + is_ollama = server.provider == "ollama" + kwargs = {"host": server.base_url[:-3]} if is_ollama else {"base_url": server.base_url} + llm = LLM( + model.id, + backend="ollama" if is_ollama else "openai-compat", + backend_kwargs=kwargs, + require_local=True, + ) + response = llm.chat( + [{"role": "user", "content": "Say hello in five words."}], max_tokens=32 + ) + print(" ->", response["choices"][0]["message"]["content"].strip()) + + if args.require_local: + return 0 if on_device else 1 + return 0 if report.live else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/hybrid_rag.py b/examples/hybrid_rag.py new file mode 100644 index 0000000..b48fa27 --- /dev/null +++ b/examples/hybrid_rag.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Example: Small Offline Hybrid RAG with BM25, Dense Embeddings, and RRF. + +Demonstrates: +1. High-level RAGPipeline document ingestion and chunking. +2. Hybrid Search combining Dense Cosine Similarity and Okapi BM25. +3. Reciprocal Rank Fusion (RRF) scoring for exact technical keyword matching. +4. Metadata filtering and JSON index persistence. + +Run: + python examples/hybrid_rag.py +""" + +import os +import sys +import tempfile + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from local_llm_kit import LLM +from local_llm_kit.embeddings import hash_embed +from local_llm_kit.rag import RAGPipeline, SimpleVectorStore + + +def deterministic_embed(texts): + if isinstance(texts, str): + texts = [texts] + return hash_embed(list(texts), dim=32) + + +def main(): + print("=== Local LLM Kit: Hybrid RAG (BM25 + Dense RRF) ===\n") + + # 1. Initialize store with offline embedder + store = SimpleVectorStore(embed_fn=deterministic_embed) + + # 2. Add domain documents with metadata + docs = [ + "Kubernetes deployment manifests manage replica sets and pods in cloud clusters.", + "PostgreSQL 16 index optimization: B-Tree vs GIN indexes for JSONB columns.", + "Error ERR_CONN_REFUSED: Database connection dropped due to connection pool saturation.", + "Python typing system: TypeVar, ParamSpec, and Protocol for static type checking.", + ] + metas = [ + {"category": "devops", "env": "prod"}, + {"category": "database", "env": "prod"}, + {"category": "troubleshooting", "env": "prod"}, + {"category": "python", "env": "dev"}, + ] + + store.add(docs, metadatas=metas, ids=["doc-k8s", "doc-pg", "doc-err", "doc-py"]) + print(f"Indexed {len(store)} documents.") + + # 3. Hybrid search (combines semantic embeddings and exact BM25 keyword matching) + query = "ERR_CONN_REFUSED saturation" + print(f"\nSearching with mode='hybrid' for: {query!r}...") + hits = store.search(query, k=2, mode="hybrid") + for hit in hits: + print(f" [{hit['id']}] (score: {hit['score']:.4f}) {hit['text']}") + + # 4. Metadata filtering + print("\nFiltering by metadata: {'env': 'dev'}...") + dev_hits = store.search("typing", k=2, filter={"env": "dev"}) + for hit in dev_hits: + print(f" [{hit['id']}] {hit['text']}") + + # 5. Persistence: save and reload + with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as tmp: + save_path = tmp.name + + store.save(save_path) + print(f"\nSaved index to {save_path}") + + reloaded = SimpleVectorStore.load(save_path, embed_fn=deterministic_embed) + os.unlink(save_path) + print(f"Reloaded store from disk: {len(reloaded)} documents verified.") + + # 6. High-level RAGPipeline answering + llm = LLM("llama3.2:3b", backend="echo") + pipeline = RAGPipeline(llm=llm, store=reloaded) + result = pipeline.query("What causes ERR_CONN_REFUSED?", k=1, mode="hybrid") + print("\nRAGPipeline Query Output:") + print(f"Answer: {result['answer']}") + print(f"Retrieved sources: {len(result['sources'])}") + + +if __name__ == "__main__": + main() diff --git a/examples/mcp_tools.py b/examples/mcp_tools.py new file mode 100644 index 0000000..a421c7f --- /dev/null +++ b/examples/mcp_tools.py @@ -0,0 +1,131 @@ +"""Use Model Context Protocol (MCP) tools with a local model. + +This example runs fully offline: it starts a tiny MCP server (defined inline +below) over stdio, discovers the tools it advertises, and registers them on an +``LLM`` backed by the deterministic ``echo`` backend. Swap in a real model and a +real server command to do something useful. + +Run it:: + + python examples/mcp_tools.py + python examples/mcp_tools.py --server "npx -y @modelcontextprotocol/server-filesystem /tmp" + +A real server needs to be installed (npx/uvx/pip) and may talk to the network; +the demo server below never does. +""" + +import argparse +import shlex +import sys + +from local_llm_kit import LLM +from local_llm_kit.mcp import MCPServer + +# A minimal JSON-RPC MCP server on stdin/stdout. Real servers implement far +# more, but this is enough to show discovery + invocation end to end. +DEMO_SERVER = r""" +import datetime, json, sys + +TOOLS = [ + { + "name": "utc_now", + "description": "Return the current UTC time (ISO-8601).", + "inputSchema": {"type": "object", "properties": {}}, + }, + { + "name": "echo_text", + "description": "Echo the given text back.", + "inputSchema": { + "type": "object", + "properties": {"text": {"type": "string"}}, + "required": ["text"], + }, + }, +] + + +def handle(msg): + method, mid, params = msg.get("method"), msg.get("id"), msg.get("params") or {} + if mid is None: + return None # notification + if method == "initialize": + return {"jsonrpc": "2.0", "id": mid, "result": { + "protocolVersion": "2025-06-18", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "demo", "version": "1.0"}, + }} + if method == "tools/list": + return {"jsonrpc": "2.0", "id": mid, "result": {"tools": TOOLS}} + if method == "tools/call": + name = params.get("name") + args = params.get("arguments") or {} + if name == "utc_now": + text = datetime.datetime.utcnow().isoformat() + "Z" + elif name == "echo_text": + text = "echo: %s" % args.get("text", "") + else: + return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32602, "message": "unknown tool"}} + return {"jsonrpc": "2.0", "id": mid, "result": {"content": [{"type": "text", "text": text}]}} + return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no method"}} + + +for line in sys.stdin: + line = line.strip() + if not line: + continue + try: + message = json.loads(line) + except ValueError: + continue + response = handle(message) + if response is not None: + sys.stdout.write(json.dumps(response) + "\n") + sys.stdout.flush() +""" + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--server", + default=None, + help="Full MCP server command (stdio). Defaults to the built-in demo server.", + ) + args = parser.parse_args(argv) + + if args.server: + parts = shlex.split(args.server, posix=(sys.platform != "win32")) + server = MCPServer("cli-server", command=parts[0], args=parts[1:]) + else: + server = MCPServer("demo", command=sys.executable, args=["-c", DEMO_SERVER]) + + with server: + tools = server.tools() + print("Discovered %d MCP tool(s) from %r:" % (len(tools), server.name)) + for tool in tools: + print(" - %s: %s" % (tool.name, tool.description)) + + # Call one directly (no model involved). + print("\nDirect call -> utc_now: %s" % server.call_tool("utc_now", {})) + + # Register them on an LLM; `chat` will include and (auto-)execute them. + llm = LLM(model_path="echo", backend="echo") + try: + names = llm.add_mcp_server(server) + print("\nRegistered on LLM: %s" % ", ".join(names)) + response = llm.chat( + [{"role": "user", "content": "What time is it? Use the utc_now tool."}] + ) + print("\nModel said:\n%s" % response["choices"][0]["message"]["content"]) + print( + "\n(With a real tool-calling model the loop above would call the MCP " + "tool and answer with its result. Try: --server 'ollama' or point " + "--backend at a local model.)" + ) + finally: + llm.close() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/structured_json.py b/examples/structured_json.py new file mode 100644 index 0000000..75b8cb5 --- /dev/null +++ b/examples/structured_json.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Example: Resilient Structured Outputs and Opt-In JSON Output Repair. + +Demonstrates: +1. Automated repair of corrupted, malformed, or conversational local model outputs. +2. Self-correcting structured chat loop with JSON schema validation. + +Run: + python examples/structured_json.py +""" + +import os +import sys + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from local_llm_kit import extract_json, repair_json + + +def main(): + print("=== Local LLM Kit: Resilient Structured Output & Auto-Repair ===\n") + + # Sample malformed output commonly produced by small local LLMs: + # - Markdown code fences + # - Conversational preface and postscript + # - Trailing commas + # - Single-quoted strings + # - Python literals (True, None) + # - Truncated braces + malformed_output = """ + Certainly! Here is the JSON representation you requested: + ```json + { + 'status': 'success', + 'code': 200, + 'is_active': True, + 'metadata': None, + 'tags': ['local-ai', 'agent', 'mcp',], + 'metrics': { + 'latency_ms': 12.5, + ``` + I hope this helps! Reach out if you need further adjustments. + """ + + print("Raw Corrupted LLM Output:") + print(malformed_output.strip()) + + print("\nRepairing JSON via repair_json()...") + cleaned = repair_json(malformed_output) + print("Cleaned JSON String:") + print(cleaned) + + print("\nParsed Data Object via extract_json():") + data = extract_json(malformed_output) + print(data) + print(f"Data type: {type(data).__name__}") + print( + f"Status: {data.get('status')}, Active: {data.get('is_active')}, Tags: {data.get('tags')}" + ) + + +if __name__ == "__main__": + main() diff --git a/examples/vram_advisor.py b/examples/vram_advisor.py new file mode 100644 index 0000000..0373bd6 --- /dev/null +++ b/examples/vram_advisor.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Example: Hardware-Aware VRAM Estimator and Model Sizing Advisor. + +Demonstrates: +1. Querying host physical RAM and GPU VRAM. +2. Estimating approximate memory footprints for quantized models and KV caches. +3. Receiving hardware-aware quantization recommendations before downloading. + +Run: + python examples/vram_advisor.py +""" + +import os +import sys + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from local_llm_kit.hardware import estimate_model_vram, get_system_memory, recommend_quantization + + +def main(): + print("=== Local LLM Kit: Hardware VRAM Advisor ===\n") + + # 1. System memory detection + mem = get_system_memory() + print("Host Environment:") + print(f" Platform: {mem['platform']}") + print( + f" Total RAM: {mem['total_ram_gb']:.1f} GB ({mem['available_ram_gb']:.1f} GB available)" + ) + if mem["gpu_vram_gb"] > 0: + desc = "Apple Silicon Unified Memory" if mem["is_apple_silicon"] else "Dedicated GPU VRAM" + print(f" GPU Memory: {mem['gpu_vram_gb']:.1f} GB ({desc})") + + # 2. Compare memory for popular model sizes + print("\nModel Memory Footprints at 4096 Context:") + for params in [3.0, 7.0, 8.0, 14.0, 70.0]: + q4 = estimate_model_vram(params, quant="Q4_K_M", context_length=4096) + q8 = estimate_model_vram(params, quant="Q8_0", context_length=4096) + fp16 = estimate_model_vram(params, quant="FP16", context_length=4096) + print( + f" {params:4.1f}B Model: Q4_K_M ~{q4['total_gb']:5.2f} GB | Q8_0 ~{q8['total_gb']:5.2f} GB | FP16 ~{fp16['total_gb']:5.2f} GB" + ) + + # 3. Recommendation for 8B model + print("\nRecommendation for 8B Model on Current Machine:") + try: + rec = recommend_quantization(8.0, context_length=4096) + print(f" {rec['recommendation']}") + except ValueError as exc: + print(f" {exc}") + + +if __name__ == "__main__": + main() diff --git a/llms.txt b/llms.txt index 57a3af3..632e220 100644 --- a/llms.txt +++ b/llms.txt @@ -1,28 +1,38 @@ # Local LLM Kit -> A lightweight Python interface for offline language models and local LLM servers. Import: `local_llm_kit`; distribution: `local-llm-kit`; license: MIT. +> Lightweight Python client for local models and local inference servers. Distribution: local-llm-kit. Import: local_llm_kit. MIT. Core Python 3.9+, stdlib plus typing-extensions. -## Where it fits +## Status -Applications that want one OpenAI-shaped chat/completion interface across local runtimes, native tool calls and structured outputs where supported, an offline deterministic test backend, or small embedding/RAG helpers. The core client uses stdlib HTTP and typing-extensions; inference packages are optional extras. +PyPI 0.2.0 is the stable release. Discovery, Apple FM, MCP, agents, validated structured output, hybrid retrieval, logging, hardware advice and Responses are unreleased additions on feat/consolidated-community-upgrades. Do not describe them as shipped in 0.2.0. -## Actual API +## API and fit -`from local_llm_kit import LLM, chat, complete, embed, tool` +Use when an application needs an OpenAI-shaped Python chat/completion API across local runtimes, request-scoped tools, an offline echo fixture, or small retrieval helpers. Example: `LLM('echo', backend='echo').chat([{'role':'user','content':'Hi'}])`; answer text is `response['choices'][0]['message']['content']`. -`LLM(model_path="echo", backend="echo").chat([{"role":"user","content":"Hello"}])` returns a dictionary; text is at `response["choices"][0]["message"]["content"]`. +In-process adapters: transformers, llamacpp, experimental airllm, native apple-fm. HTTP: native ollama and OpenAI-compatible presets vllm, sglang, lmstudio, localai, llama-server, jan, gpt4all, mlx-lm, koboldcpp, transformers-serve, apfel. Generic servers use openai-compat with base_url. A preset connects to an already-running engine; it does not host or install it. Features depend on the chosen model/runtime. These are compatibility options, not a usage ranking. -Backends: echo, transformers, llamacpp, ollama, openai-compat and experimental airllm. Server presets: sglang, vllm, lmstudio, localai, llama-server, jan, gpt4all, mlx-lm and koboldcpp. These cover 12 distinct local runtimes; this is not a usage ranking. A preset connects to an already-running server with a served model ID; it does not install or host that engine. GPT4All and MLX-LM presets have no embedding endpoint; use a separate embedding backend. +## Unreleased additions -## Boundaries +- `discover`, `probe_endpoint`, `find_local_server` and CLI `doctor`: read native capability metadata when available. Unknown locality stays unknown. `LLM(..., require_local=True)` refuses unverified/remote execution and checks again before chat/completion. It trusts metadata and is not a network sandbox. +- HTTP adapters use `max_retries` (integer or RetryPolicy), default 2. Streaming retries only connection setup, never emitted output. +- Apple FM uses Apple's SDK on an eligible Mac, Python 3.10+, macOS 26+, Xcode 26+ and enabled Apple Intelligence. Fresh sessions, schema forwarding, stop-aware streams, inline image attachment adapter and exact token count. Actual vision requires SDK/OS image support. apfel maps completions to chat and has no embeddings. +- `MCPServer`, `LLM.add_mcp_server`, CLI `mcp tools|call`: synchronous stdio/HTTP tools subset, namespacing and deadlines. `Agent` owns a bounded tool loop using the same executor as LLM.chat. Invalid truncated arguments are never repaired into executable tool calls. +- `LLM.chat_structured`: JSON Schema type/constraint checks via optional [structured] or Pydantic. `repair_json`/`extract_json` are opt-in output helpers. +- `SimpleVectorStore`, `RAGPipeline`: BM25, dense/lexical rank fusion, optional MMR, filters, delete and JSON persistence. A small in-memory store, not a distributed vector database. Citation prompts do not validate grounding. +- `ConversationLog`: opt-in SQLite logging, atomic completed interactions, original tool IDs, full payload export, completed streams, thread-safe in-memory databases. PromptTemplate uses plain substitution; YAML needs [yaml]. +- `get_system_memory`, `estimate_model_vram`, `recommend_quantization`: measured or unknown memory and approximate budgets; no guaranteed fit or artificial pooled GPU memory. +- Development server: stateless `/v1/responses` text/image inputs, function calls/results, text.format and SSE lifecycle. Stateful/hosted tools/background/reasoning controls are unsupported. Existing chat/completions and embeddings remain available. Server is a development adapter, not an authenticated multi-user gateway. -Capabilities depend on the chosen model/runtime. Protocol tests are not hardware benchmarks. AirLLM call contracts are tested with doubles; real model/GPU execution is not certified, and its stream is buffered. The bundled HTTP server is a development shim. Remote tool execution defaults to off; per-call Python tools are request-scoped. Weights and dependencies must be prepared before offline use. These integrations are included in version 0.2.0. +## Validation boundaries + +Core stays light. Native inference dependencies are optional and prepared weights are needed offline. Protocol fixture tests and official OpenAI/MCP SDK checks do not certify every engine, model or hardware configuration. AirLLM streaming is buffered. Python tool deadlines bound waiting; running functions may continue. Native schema enforcement is backend-dependent; the structured helper validates returned JSON separately. No claim of being fastest or universally best is established. ## References - [Repository and quickstart](https://github.com/1Utkarsh1/Local-LLM-kit) +- [Released 0.2.0 API](https://github.com/1Utkarsh1/Local-LLM-kit/tree/v0.2.0) - [Backend compatibility](https://github.com/1Utkarsh1/Local-LLM-kit/blob/main/docs/source/backends.rst) -- [Python API](https://github.com/1Utkarsh1/Local-LLM-kit/blob/main/docs/source/api_reference.rst) +- [API reference](https://github.com/1Utkarsh1/Local-LLM-kit/blob/main/docs/source/api_reference.rst) - [Examples](https://github.com/1Utkarsh1/Local-LLM-kit/tree/main/examples) -- [Changelog](https://github.com/1Utkarsh1/Local-LLM-kit/blob/main/CHANGELOG.md) - [Bug reports](https://github.com/1Utkarsh1/Local-LLM-kit/issues) diff --git a/local_llm_kit.egg-info/PKG-INFO b/local_llm_kit.egg-info/PKG-INFO deleted file mode 100644 index ceee3d2..0000000 --- a/local_llm_kit.egg-info/PKG-INFO +++ /dev/null @@ -1,249 +0,0 @@ -Metadata-Version: 2.4 -Name: local-llm-kit -Version: 0.1.2 -Summary: OpenAI-like interface for local LLMs -Home-page: https://github.com/1Utkarsh1/local-llm-kit -Author: Utkarsh Rajput -Author-email: utkarshrajput815@gmail.com -Classifier: Development Status :: 3 - Alpha -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: MIT License -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Requires-Python: >=3.8 -Description-Content-Type: text/markdown -License-File: LICENSE -Requires-Dist: typing-extensions>=4.0.0 -Provides-Extra: transformers -Requires-Dist: torch>=1.12.0; extra == "transformers" -Requires-Dist: transformers>=4.25.0; extra == "transformers" -Requires-Dist: accelerate>=0.16.0; extra == "transformers" -Provides-Extra: llamacpp -Requires-Dist: llama-cpp-python>=0.1.77; extra == "llamacpp" -Provides-Extra: all -Requires-Dist: torch>=1.12.0; extra == "all" -Requires-Dist: transformers>=4.25.0; extra == "all" -Requires-Dist: accelerate>=0.16.0; extra == "all" -Requires-Dist: llama-cpp-python>=0.1.77; extra == "all" -Dynamic: author -Dynamic: author-email -Dynamic: classifier -Dynamic: description -Dynamic: description-content-type -Dynamic: home-page -Dynamic: license-file -Dynamic: provides-extra -Dynamic: requires-dist -Dynamic: requires-python -Dynamic: summary - -# Local LLM Kit - -An OpenAI-like interface for local Large Language Models. This package allows you to interact with local LLMs using an API similar to OpenAI's, including support for chat completions, function calling, streaming responses, and more. - -**Created by Utkarsh Rajput (GitHub: [1Utkarsh1](https://github.com/1Utkarsh1))** - A powerful tool for working with local language models with all the convenience of the OpenAI API. - -## Features - -- 🗣️ **Chat and Completion API**: Similar to OpenAI's API -- 🧩 **Multiple Backend Support**: Works with Hugging Face Transformers and llama.cpp -- 🛠️ **Function Calling**: Register Python functions that LLMs can call -- 📱 **Streaming Support**: Stream responses token by token -- 🧠 **Memory Management**: Auto-truncation and context management -- 📊 **Logprobs**: Get token probabilities for generations -- 📝 **Prompt Formatting**: Supports various model template formats (Llama, Mistral, etc.) -- 🌐 **JSON Mode**: Enforce structured JSON output - -## Installation - -### Basic Installation - -```bash -pip install local-llm-kit -``` - -### With Backend Support - -```bash -# For Hugging Face Transformers support -pip install "local-llm-kit[transformers]" - -# For llama.cpp support -pip install "local-llm-kit[llamacpp]" - -# For all backends -pip install "local-llm-kit[all]" -``` - -## Quick Start - -### Chat with a Model - -```python -from local_llm_kit import chat - -response = chat( - messages=[ - {"role": "system", "content": "You are a helpful assistant."}, - {"role": "user", "content": "Tell me about the solar system."} - ], - model_path="path/to/your/model", # Local model path or HF model name - temperature=0.7, - max_tokens=512 -) - -print(response["choices"][0]["message"]["content"]) -``` - -### Text Completion - -```python -from local_llm_kit import complete - -response = complete( - prompt="The solar system consists of", - model_path="path/to/your/model", - temperature=0.7, - max_tokens=512 -) - -print(response["choices"][0]["text"]) -``` - -### Function Calling - -```python -from local_llm_kit import LLM - -# Define a function with its schema -def get_weather(location: str, unit: str = "celsius"): - """Get the weather for a location.""" - # In a real app, this would call a weather API - return {"temperature": 22, "unit": unit, "description": f"Sunny in {location}"} - -weather_function = { - "name": "get_weather", - "description": "Get the current weather for a location", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. San Francisco, CA" - }, - "unit": { - "type": "string", - "enum": ["celsius", "fahrenheit"], - "description": "The unit of temperature" - } - }, - "required": ["location"] - } -} - -# Create LLM instance -llm = LLM(model_path="path/to/your/model") - -# Register the function -llm.add_function( - name="get_weather", - schema=weather_function, - implementation=get_weather -) - -# Chat with function calling -response = llm.chat( - messages=[ - {"role": "user", "content": "What's the weather like in Paris?"} - ], - # The function will be automatically called if the model chooses to use it -) - -print(response["choices"][0]["message"]["content"]) -``` - -### Streaming Responses - -```python -from local_llm_kit import chat - -for chunk in chat( - messages=[ - {"role": "user", "content": "Write a short poem about nature."} - ], - model_path="path/to/your/model", - stream=True -): - # Process each token as it's generated - if "choices" in chunk and chunk["choices"] and "delta" in chunk["choices"][0]: - delta = chunk["choices"][0]["delta"] - if "content" in delta: - print(delta["content"], end="", flush=True) -``` - -## Command Line Interface - -Local LLM Kit includes a CLI for easy interaction with models. - -### Interactive Chat - -```bash -local-llm-kit chat --model path/to/your/model --system "You are a helpful assistant." -``` - -### Text Completion - -```bash -local-llm-kit complete --model path/to/your/model --prompt "Once upon a time," -``` - -## Advanced Usage - -### Using Different Backends - -```python -from local_llm_kit import LLM - -# Using Transformers backend -llm_transformers = LLM( - model_path="mistralai/Mistral-7B-Instruct-v0.1", - backend="transformers", - backend_kwargs={"device": "cuda", "torch_dtype": "float16"} -) - -# Using llama.cpp backend -llm_llamacpp = LLM( - model_path="path/to/model.gguf", - backend="llamacpp", - backend_kwargs={"n_gpu_layers": -1, "n_ctx": 4096} -) -``` - -### JSON Mode - -```python -from local_llm_kit import chat - -response = chat( - messages=[ - {"role": "user", "content": "Generate a JSON list of 3 planets with their diameter."} - ], - model_path="path/to/your/model", - format="json" -) - -import json -planets = json.loads(response["choices"][0]["message"]["content"]) -print(planets) -``` - -## License - -MIT License - -## Contributing - -Contributions are welcome! Please feel free to submit a Pull Request. diff --git a/local_llm_kit.egg-info/SOURCES.txt b/local_llm_kit.egg-info/SOURCES.txt deleted file mode 100644 index 7cfd8b6..0000000 --- a/local_llm_kit.egg-info/SOURCES.txt +++ /dev/null @@ -1,34 +0,0 @@ -CHANGELOG.md -LICENSE -MANIFEST.in -README.md -requirements.txt -setup.py -docs/source/api_reference.rst -docs/source/best_practices.rst -docs/source/index.rst -docs/source/models.rst -docs/source/quickstart.rst -docs/source/tutorials.rst -examples/__init__.py -examples/simple_chat.py -local_llm_kit/__init__.py -local_llm_kit/chat.py -local_llm_kit/cli.py -local_llm_kit/function_calling.py -local_llm_kit/llm.py -local_llm_kit/memory.py -local_llm_kit/prompt_formatting.py -local_llm_kit.egg-info/PKG-INFO -local_llm_kit.egg-info/SOURCES.txt -local_llm_kit.egg-info/dependency_links.txt -local_llm_kit.egg-info/entry_points.txt -local_llm_kit.egg-info/requires.txt -local_llm_kit.egg-info/top_level.txt -local_llm_kit/backends/__init__.py -local_llm_kit/backends/base.py -local_llm_kit/backends/llamacpp.py -local_llm_kit/backends/transformers.py -tests/__init__.py -tests/test_function_calling.py -tests/test_prompt_formatting.py \ No newline at end of file diff --git a/local_llm_kit.egg-info/dependency_links.txt b/local_llm_kit.egg-info/dependency_links.txt deleted file mode 100644 index 8b13789..0000000 --- a/local_llm_kit.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/local_llm_kit.egg-info/entry_points.txt b/local_llm_kit.egg-info/entry_points.txt deleted file mode 100644 index 281ca8d..0000000 --- a/local_llm_kit.egg-info/entry_points.txt +++ /dev/null @@ -1,2 +0,0 @@ -[console_scripts] -local-llm-kit = local_llm_kit.cli:main diff --git a/local_llm_kit.egg-info/requires.txt b/local_llm_kit.egg-info/requires.txt deleted file mode 100644 index e8eb3fe..0000000 --- a/local_llm_kit.egg-info/requires.txt +++ /dev/null @@ -1,15 +0,0 @@ -typing-extensions>=4.0.0 - -[all] -torch>=1.12.0 -transformers>=4.25.0 -accelerate>=0.16.0 -llama-cpp-python>=0.1.77 - -[llamacpp] -llama-cpp-python>=0.1.77 - -[transformers] -torch>=1.12.0 -transformers>=4.25.0 -accelerate>=0.16.0 diff --git a/local_llm_kit.egg-info/top_level.txt b/local_llm_kit.egg-info/top_level.txt deleted file mode 100644 index aea1f78..0000000 --- a/local_llm_kit.egg-info/top_level.txt +++ /dev/null @@ -1,3 +0,0 @@ -examples -local_llm_kit -tests diff --git a/local_llm_kit/__init__.py b/local_llm_kit/__init__.py index c6efedc..8c78415 100644 --- a/local_llm_kit/__init__.py +++ b/local_llm_kit/__init__.py @@ -1,8 +1,9 @@ """ local_llm_kit - OpenAI-compatible interface for local LLMs. -Backends: transformers, llama.cpp (GGUF), Ollama, generic OpenAI-compatible -servers (vLLM, LM Studio, llama-server), and an offline ``echo`` mock. +Backends: transformers, llama.cpp (GGUF), Ollama, Apple Foundation Models +(on-device system model), generic OpenAI-compatible +servers (vLLM, LM Studio, llama-server, apfel), and an offline ``echo`` mock. Core install stays light (stdlib + typing-extensions); heavy dependencies are optional extras, lazily imported. @@ -11,8 +12,23 @@ __version__ = "0.2.0" from .chat import achat, acomplete, chat, complete, embed +from .discovery import ( + DiscoveryReport, + ModelRecord, + ServerReport, + discover, + find_local_server, + probe_endpoint, +) from .function_calling import FunctionCall, FunctionRegistry, add_function, parse_function_calls from .llm import LLM, clear_backend_cache, clear_client_cache, get_client +from .mcp import ( + MCPError, + MCPServer, + MCPTool, + MCPToolError, + mcp_tools_to_openai, +) from .tools import ( ToolCall, ToolRegistry, @@ -28,6 +44,11 @@ "get_client", "clear_backend_cache", "clear_client_cache", + "MCPServer", + "MCPTool", + "MCPError", + "MCPToolError", + "mcp_tools_to_openai", "chat", "complete", "embed", @@ -43,4 +64,43 @@ "normalize_tools", "parse_function_calls", "parse_tool_calls", + "discover", + "probe_endpoint", + "find_local_server", + "DiscoveryReport", + "ServerReport", + "ModelRecord", ] + + +_LAZY_EXPORTS = { + "Agent": "agent", + "AgentResult": "agent", + "ConversationLog": "conversation_log", + "get_conversation_log": "conversation_log", + "PromptTemplate": "prompt_templates", + "TemplateRegistry": "prompt_templates", + "register_template": "prompt_templates", + "get_template": "prompt_templates", + "render_template": "prompt_templates", + "chat_structured": "structured", + "extract_json": "structured", + "repair_json": "structured", + "validate_schema": "structured", + "get_system_memory": "hardware", + "estimate_model_vram": "hardware", + "recommend_quantization": "hardware", + "RAGPipeline": "rag", + "SimpleVectorStore": "rag", +} +__all__ += list(_LAZY_EXPORTS) + + +def __getattr__(name): + if name not in _LAZY_EXPORTS: + raise AttributeError("module %r has no attribute %r" % (__name__, name)) + from importlib import import_module + + value = getattr(import_module("." + _LAZY_EXPORTS[name], __name__), name) + globals()[name] = value + return value diff --git a/local_llm_kit/agent.py b/local_llm_kit/agent.py new file mode 100644 index 0000000..6ffcf7f --- /dev/null +++ b/local_llm_kit/agent.py @@ -0,0 +1,143 @@ +"""A bounded tool-calling loop with request-scoped tools and error feedback.""" + +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Sequence + +from .tools import ToolCall, ToolRegistry, _validate_tool_timeout, normalize_tools + + +@dataclass +class AgentResult: + """Final answer, full exchange, and number of attempted tool calls.""" + + content: str + steps: List[Dict[str, Any]] = field(default_factory=list) + tool_calls_executed: int = 0 + success: bool = True + iterations: int = 0 + + +class Agent: + """Run a synchronous LLM with Python tools and connected MCPServer instances. + + Tools execute only when explicitly passed here. MCP tool names are prefixed + with the server name. The caller owns MCP connection lifetimes. A timeout + bounds waiting for a Python tool, but cannot undo or interrupt its side effects. + """ + + def __init__( + self, + llm: Any, + tools: Optional[Sequence[Any]] = None, + mcp_clients: Optional[Sequence[Any]] = None, + system: Optional[str] = None, + max_steps: int = 10, + tool_timeout: Optional[float] = 10.0, + ): + if isinstance(max_steps, bool) or not isinstance(max_steps, int) or max_steps < 1: + raise ValueError("max_steps must be a positive integer.") + _validate_tool_timeout(tool_timeout) + self.llm = llm + self.system = system + self.max_steps = max_steps + self.tool_timeout = tool_timeout + self.mcp_clients = list(mcp_clients or []) + self._registry = ToolRegistry() + for item in tools or []: + if callable(item): + spec = normalize_tools([item])[0]["function"] + implementation = item + elif isinstance(item, dict) and normalize_tools([item]): + spec = normalize_tools([item])[0]["function"] + implementation = None + else: + raise TypeError("Agent tools must be callables or function tool specs.") + self._register(spec, implementation) + + def _register(self, spec: Dict[str, Any], implementation: Any) -> None: + name = spec["name"] + if self._registry.has_function(name): + raise ValueError("Duplicate agent tool name: %s" % name) + self._registry.add_function(name=name, schema=spec, implementation=implementation) + + def _collect_all_tool_specs(self) -> List[Dict[str, Any]]: + from .mcp import sanitize_tool_name + + # Rebuild the MCP portion per run so disconnected/changed servers cannot + # leave stale implementations behind in a reused agent. + registry = ToolRegistry() + registry.functions.update(self._registry.functions) + registry.implementations.update(self._registry.implementations) + for client in self.mcp_clients: + for tool in client.list_tools(): + name = sanitize_tool_name("%s__%s" % (client.name, tool.name)) + if registry.has_function(name): + raise ValueError("Duplicate agent tool name: %s" % name) + + def invoke(_client=client, _name=tool.name, **arguments): + return _client.call_tool(_name, arguments) + + registry.add_function(name, tool.to_openai(name)["function"], invoke) + self._run_registry = registry + return registry.get_tool_list() + + def run( + self, + prompt: str, + messages: Optional[List[Dict[str, Any]]] = None, + **kwargs: Any, + ) -> AgentResult: + """Return a final answer or an unsuccessful result at the turn limit. + + Invalid JSON tool arguments are reported to the model without executing + them. They are never repaired into an action the model did not specify. + """ + if not isinstance(prompt, str): + raise TypeError("prompt must be a string.") + if kwargs.get("stream"): + raise ValueError("Agent.run does not support stream=True.") + history = [{"role": "system", "content": self.system}] if self.system else [] + history.extend(dict(message) for message in messages or []) + history.append({"role": "user", "content": prompt}) + specs = self._collect_all_tool_specs() + by_name = {spec["function"]["name"]: spec for spec in specs} + calls = 0 + for step in range(self.max_steps): + chat_kwargs = dict(kwargs, execute_tools=False) + if specs: + chat_kwargs["tools"] = specs + response = self.llm.chat(messages=history, **chat_kwargs) + choices = response.get("choices", []) + if not choices: + return AgentResult("", history, calls, False, step + 1) + message = dict(choices[0].get("message", {}), role="assistant") + history.append(message) + tool_calls = message.get("tool_calls") + if not tool_calls: + return AgentResult(message.get("content") or "", history, calls, True, step + 1) + for record in tool_calls: + calls += 1 + try: + call = ToolCall.from_dict(record) + result = self._run_registry.execute_call( + call, list(by_name), by_name.get(call.name), self.tool_timeout + ) + except (TypeError, ValueError) as exc: + result = ( + "Error: invalid tool call (%s). Provide a complete JSON object." + % str(exc)[:200] + ) + function = record.get("function", {}) if isinstance(record, dict) else {} + history.append( + { + "role": "tool", + "tool_call_id": ( + record.get("id", "call_%s" % calls) + if isinstance(record, dict) + else "call_%s" % calls + ), + "name": function.get("name", "") if isinstance(function, dict) else "", + "content": result, + } + ) + return AgentResult("", history, calls, False, self.max_steps) diff --git a/local_llm_kit/backends/__init__.py b/local_llm_kit/backends/__init__.py index 9b5d2ac..1558eac 100644 --- a/local_llm_kit/backends/__init__.py +++ b/local_llm_kit/backends/__init__.py @@ -25,6 +25,7 @@ "OllamaBackend", "OpenAICompatBackend", "AirLLMBackend", + "AppleFMBackend", "BACKENDS", "BACKEND_ALIASES", "OPENAI_SERVER_URLS", @@ -42,12 +43,14 @@ "OllamaBackend": (".ollama", "OllamaBackend"), "OpenAICompatBackend": (".openai_compat", "OpenAICompatBackend"), "AirLLMBackend": (".airllm", "AirLLMBackend"), + "AppleFMBackend": (".apple_fm", "AppleFMBackend"), } #: Short backend name -> "module:Class" (module relative to this package). BACKENDS: Dict[str, str] = { "transformers": ".transformers:TransformersBackend", "airllm": ".airllm:AirLLMBackend", + "apple-fm": ".apple_fm:AppleFMBackend", "llamacpp": ".llamacpp:LlamaCppBackend", "llama_cpp": ".llamacpp:LlamaCppBackend", "llama.cpp": ".llamacpp:LlamaCppBackend", @@ -57,6 +60,7 @@ "openai": ".openai_compat:OpenAICompatBackend", "openai_compat": ".openai_compat:OpenAICompatBackend", "openai-compat": ".openai_compat:OpenAICompatBackend", + "apfel": ".openai_compat:OpenAICompatBackend", "vllm": ".openai_compat:OpenAICompatBackend", "lmstudio": ".openai_compat:OpenAICompatBackend", "llama-server": ".openai_compat:OpenAICompatBackend", @@ -65,15 +69,21 @@ #: Canonical-name aliases kept as a separate dict for docs/CLI completion. BACKEND_ALIASES: Dict[str, str] = { "mock": "echo", + "apple": "apple-fm", + "apple-foundation": "apple-fm", + "foundation-models": "apple-fm", + "foundationmodels": "apple-fm", "llama_cpp": "llamacpp", "llama-cpp": "llamacpp", "llama.cpp": "llamacpp", "openai": "openai-compat", "openai_compat": "openai-compat", + "apfel": "openai-compat", "vllm": "openai-compat", "lmstudio": "openai-compat", "llama-server": "openai-compat", "sglang": "openai-compat", + "transformers-serve": "openai-compat", "localai": "openai-compat", "jan": "openai-compat", "gpt4all": "openai-compat", @@ -87,12 +97,22 @@ BACKENDS[_alias] = BACKENDS[_canonical] # Connection presets; callers may override base_url for any server or port. +# +# NOTE on llama-server: llama.cpp moved its default listen port from 8080 to +# 9931 in October 2026 (ggml-org/llama.cpp#30159, merged 2026-10-09); the +# published Docker image still binds 8080 inside the container. This preset +# follows the upstream binary. On an older llama-server build, or against the +# container, pass the port explicitly: +# backend_kwargs={"base_url": "http://localhost:8080/v1"} +# `local-llm-kit doctor` probes both ports and reports what is actually up. OPENAI_SERVER_URLS: Dict[str, str] = { + "apfel": "http://localhost:11434/v1", "vllm": "http://localhost:8000/v1", "sglang": "http://localhost:30000/v1", + "transformers-serve": "http://localhost:8000/v1", "lmstudio": "http://localhost:1234/v1", "localai": "http://localhost:8080/v1", - "llama-server": "http://localhost:8080/v1", + "llama-server": "http://localhost:9931/v1", "jan": "http://127.0.0.1:1337/v1", "gpt4all": "http://127.0.0.1:4891/v1", "mlx-lm": "http://127.0.0.1:8080/v1", diff --git a/local_llm_kit/backends/apple_fm.py b/local_llm_kit/backends/apple_fm.py new file mode 100644 index 0000000..8c18977 --- /dev/null +++ b/local_llm_kit/backends/apple_fm.py @@ -0,0 +1,903 @@ +""" +Apple Foundation Models backend (on-device system model). + +Uses Apple's official ``apple-fm-sdk`` (Python bindings for the Foundation +Models framework) to run inference on the on-device model at the core of +Apple Intelligence. Prompts and responses stay on the Mac; no API key, no +network, no model downloads. + +Requirements (verified against ``apple/apple-fm-sdk`` and PyPI 2026-10-16): + +* macOS 26.0+ +* Apple Intelligence-capable Mac with Apple Intelligence turned on + (https://support.apple.com/en-us/121115) +* Xcode 26.0+ with the Xcode/SDK agreement accepted (the SDK builds native + bindings against the macOS SDK) +* Python 3.10+ +* ``pip install "local-llm-kit[apple-fm]"`` (installs ``apple-fm-sdk>=0.2.1``) + +Design notes: + +* Stdlib-only at import time. ``apple_fm_sdk`` is imported lazily inside + :meth:`AppleFMBackend.__init__` so the core install stays light and + non-Mac platforms import this module cleanly. +* One fresh :class:`LanguageModelSession` per request. Backend instances are + shared through the module-level cache in :mod:`local_llm_kit.llm`, so a + long-lived session would leak transcripts across unrelated ``LLM`` calls. + Per-request sessions keep calls isolated; the system model weights stay + loaded by the OS either way. +* ``supports_native_chat`` is True because chat history is passed through + (system messages become session instructions), but tool execution stays in + the client-side loop: tools are described in the prompt text and parsed + from the reply, exactly like the other prompt-based backends. The SDK's + automatic in-framework tool execution is deliberately not used so the + security model (scoped, validated, time-bounded, opt-in on the server) + stays uniform across backends. +* Structured output uses the SDK's native ``json_schema`` guided generation + when ``response_format={"type": "json_schema", ...}`` is given. Plain + ``json_object`` requests use the prompt/repair path shared with the other + backends. +* Streaming yields text deltas. The SDK's ``stream_response`` yields + full-text snapshots (not deltas), so this backend diffs consecutive + snapshots. Guided (schema) responses do not stream server-side either; + they are returned as one completed chunk. +* Embeddings are not available on-device (``apfel --serve`` likewise + answers ``POST /v1/embeddings`` with 501); :meth:`embed` is not + implemented and raises :exc:`NotImplementedError`. +* Vision: OpenAI-style ``image_url`` parts carrying inline base64 data URLs + are materialised to temporary files and passed as ``ImageAttachment`` + objects (the SDK takes image *files*, not data URLs). Remote ``http(s)`` + URLs are rejected — this backend never downloads images for a request. + Actual image understanding additionally needs the macOS 27 SDK (older + runtimes raise ``ImagePromptError``); text fallback still applies to + plain-text backends. +* Token counting: :meth:`count_tokens` stays a cheap heuristic like the + other backends; :meth:`count_tokens_exact` uses the SDK's async + ``token_count`` for exact budgeting against ``context_size``. +""" + +import asyncio +import base64 +import math +import os +import queue +import sys +import tempfile +import threading +import time +from typing import Any, Dict, Iterator, List, Optional, Tuple + +from .base import BaseBackend + +#: Model id reported in responses. Matches the id served by +#: ``apfel --serve`` (https://github.com/Arthur-Ficial/apfel), so configs +#: can switch between the native backend and the bridge without edits. +APPLE_MODEL_ID = "apple-foundationmodel" + +#: Fallback window when the runtime value cannot be read. The documented +#: live sizes are 4096 tokens (macOS 26, or M1/M2 Macs) and 8192 tokens +#: (macOS 27 on M3+ with 12GB+), read at runtime via +#: ``SystemLanguageModel.context_size``. +_FALLBACK_CONTEXT_WINDOW = 4096 + +_MISSING_SDK_HINT = ( + "The apple-fm backend needs Apple's Foundation Models SDK for Python: " + 'pip install "local-llm-kit[apple-fm]". Requires macOS 26+, Xcode 26+ ' + "(SDK agreement accepted), Python 3.10+, and Apple Intelligence turned on: " + "https://support.apple.com/en-us/121115" +) + +#: Actionable hints per ``SystemLanguageModelUnavailableReason``. +_REASON_HINTS = { + "APPLE_INTELLIGENCE_NOT_ENABLED": ( + "Apple Intelligence is not enabled. Turn it on in System Settings and " + "wait for the on-device model to finish downloading " + "(https://support.apple.com/en-us/121115)." + ), + "DEVICE_NOT_ELIGIBLE": ( + "This Mac is not eligible for Apple Foundation Models (requires an " + "Apple Intelligence-capable Mac)." + ), + "MODEL_NOT_READY": ( + "The on-device model is still downloading or preparing. Try again " + "after Apple Intelligence finishes setting up." + ), +} + + +def _reason_text(reason: Any) -> str: + name = getattr(reason, "name", None) or str(reason) + hint = _REASON_HINTS.get(str(name), "") + if hint: + return "%s %s" % (name, hint) + return str(name) + + +class AppleFMBackend(BaseBackend): + """On-device Apple Foundation Models backend (async SDK, sync facade). + + Import-safe everywhere: importing this module never requires macOS or + the SDK. Instantiation validates the platform, the interpreter, the + SDK presence, and model availability, in that order, with actionable + errors. + """ + + backend_name = "apple-fm" + supports_vision = True + supports_embeddings = False + supports_native_chat = True + + def __init__( + self, + model: str = APPLE_MODEL_ID, + use_case: Any = "general", + guardrails: Any = "default", + context_window: Optional[int] = None, + instructions: Optional[str] = None, + timeout: Optional[float] = None, + **kwargs: Any, + ) -> None: + """Args: + model: Model id reported in responses (informational: the device + exposes exactly one system model; defaults to + ``"apple-foundationmodel"``). + use_case: ``"general"`` (default) or ``"content_tagging"``; also + accepts the SDK's ``SystemLanguageModelUseCase`` enum. + guardrails: ``"default"`` or ``"permissive_content_transformations"``; + also accepts the SDK's ``SystemLanguageModelGuardrails`` enum. + context_window: Override the runtime ``context_size`` value. + instructions: Persona instructions prepended to every session + (per-call ``system`` messages are appended after these). + timeout: Seconds to wait for a generation before raising + :exc:`TimeoutError` (``None`` waits indefinitely, matching the + in-process backends). + """ + if sys.platform != "darwin": + raise RuntimeError( + "The apple-fm backend runs only on macOS (this platform is %r). " + "Apple's SDK has no Linux/Windows build." % (sys.platform,) + ) + if sys.version_info < (3, 10): + raise RuntimeError( + "The apple-fm backend needs Python 3.10+ (running %s); " + "apple-fm-sdk declares requires-python >= 3.10." % (sys.version.split()[0],) + ) + try: + import apple_fm_sdk as fm # type: ignore + except ImportError as exc: + raise ImportError(_MISSING_SDK_HINT) from exc + self._fm = fm + + self.model = model or APPLE_MODEL_ID + self.model_path = self.model + if timeout is not None and ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not math.isfinite(timeout) + or timeout <= 0 + ): + raise ValueError("timeout must be a finite positive number or None.") + self.timeout = timeout + self.base_instructions = instructions + self.use_case = self._normalize_use_case(use_case) + self.guardrails = self._normalize_guardrails(guardrails) + + system_model = fm.SystemLanguageModel(use_case=self.use_case, guardrails=self.guardrails) + available, reason = system_model.is_available() + if not available: + raise RuntimeError("Apple Foundation Models are unavailable: %s" % _reason_text(reason)) + self._system_model = system_model + + if context_window is not None: + if ( + isinstance(context_window, bool) + or not isinstance(context_window, int) + or context_window < 1 + ): + raise ValueError("context_window must be a positive integer.") + self._context_window = context_window + else: + try: + self._context_window = int(system_model.context_size) + if self._context_window < 1: + self._context_window = _FALLBACK_CONTEXT_WINDOW + except Exception: + self._context_window = _FALLBACK_CONTEXT_WINDOW + + # -- availability preflight ---------------------------------------- + + @staticmethod + def is_available() -> Any: + """Return ``(True, None)`` when the system model is usable. + + Never raises: returns ``(False, reason-string)`` when the platform, + interpreter, SDK, or model is unsuitable. Useful as a CLI/example + preflight before constructing the backend (which raises). + """ + if sys.platform != "darwin": + return False, "requires macOS (running on %s)" % sys.platform + if sys.version_info < (3, 10): + return False, "requires Python 3.10+" + try: + import apple_fm_sdk as fm # type: ignore + except ImportError: + return False, _MISSING_SDK_HINT + try: + available, reason = fm.SystemLanguageModel().is_available() + except Exception as exc: # e.g. bindings built without the macOS 26 SDK + return False, "availability check failed: %s" % exc + if available: + return True, None + return False, _reason_text(reason) + + # -- option normalisation ------------------------------------------ + + def _normalize_use_case(self, use_case: Any) -> Any: + fm = self._fm + enum = fm.SystemLanguageModelUseCase + if isinstance(use_case, enum): + return use_case + key = str(use_case).strip().lower().replace("-", "_") + mapping = {"general": enum.GENERAL, "content_tagging": enum.CONTENT_TAGGING} + if key not in mapping: + raise ValueError( + "Unknown use_case %r; choose 'general' or 'content_tagging'." % (use_case,) + ) + return mapping[key] + + def _normalize_guardrails(self, guardrails: Any) -> Any: + fm = self._fm + enum = fm.SystemLanguageModelGuardrails + if isinstance(guardrails, enum): + return guardrails + key = str(guardrails).strip().lower().replace("-", "_") + mapping = { + "default": enum.DEFAULT, + "permissive_content_transformations": enum.PERMISSIVE_CONTENT_TRANSFORMATIONS, + "permissive": enum.PERMISSIVE_CONTENT_TRANSFORMATIONS, + } + if key not in mapping: + raise ValueError( + "Unknown guardrails %r; choose 'default' or " + "'permissive_content_transformations'." % (guardrails,) + ) + return mapping[key] + + def _options( + self, + temperature: float, + max_new_tokens: int, + seed: Optional[int] = None, + ) -> Any: + """Map generic sampling controls onto ``GenerationOptions``. + + Only knobs the SDK exposes are set: ``temperature`` always, + ``maximum_response_tokens`` always (the SDK warns strict caps can + malform output, so callers should prefer generous values), + greedy sampling for ``temperature == 0``, and seeded random + sampling when ``seed`` is given. ``top_p``/``top_k``/penalties have + no SDK equivalent and are documented as ignored. + """ + fm = self._fm + sampling = None + if temperature == 0: + sampling = fm.SamplingMode.greedy() + elif seed is not None: + sampling = fm.SamplingMode.random(seed=int(seed)) + return fm.GenerationOptions( + temperature=temperature, + sampling=sampling, + maximum_response_tokens=int(max_new_tokens), + ) + + # -- sync bridge for the async-only SDK ----------------------------- + + def _run(self, coro_factory: Any) -> Any: + """Await a coroutine factory from synchronous code. + + Uses ``asyncio.run`` when no loop is running in this thread + (the common path, including ``asyncio.to_thread`` workers). When + called from inside a running loop, the work moves to a helper + thread with its own loop. This synchronous facade still blocks the + caller; use LLM.achat() from async code. + """ + + async def bounded(): + return await asyncio.wait_for(coro_factory(), timeout=self.timeout) + + try: + asyncio.get_running_loop() + except RuntimeError: + return asyncio.run(bounded()) + + box: Dict[str, Any] = {} + + def _target() -> None: + try: + box["result"] = asyncio.run(bounded()) + except BaseException as exc: # re-raised in the caller thread + box["error"] = exc + + worker = threading.Thread(target=_target, daemon=True) + worker.start() + worker.join(None if self.timeout is None else self.timeout + 0.2) + if worker.is_alive(): + raise TimeoutError( + "Apple Foundation Models request timed out after %s seconds." % (self.timeout,) + ) + if "error" in box: + raise box["error"] + return box.get("result") + + def _new_session(self, instructions: Optional[str]) -> Any: + combined = ( + "\n\n".join(part for part in (self.base_instructions, instructions) if part) or None + ) + return self._fm.LanguageModelSession(instructions=combined, model=self._system_model) + + # -- prompt API ----------------------------------------------------- + + def generate( + self, + prompt: str, + temperature: float = 0.7, + max_new_tokens: int = 512, + top_p: float = 0.95, + top_k: int = 40, + repetition_penalty: float = 1.1, + stream: bool = False, + logprobs: bool = False, + top_logprobs: Optional[int] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + if not isinstance(prompt, str): + raise TypeError("prompt must be a string.") + if stream: + text = "".join( + chunk["text"] + for chunk in self.generate_stream( + prompt, + temperature=temperature, + max_new_tokens=max_new_tokens, + **kwargs, + ) + ) + return {"text": text, "finish_reason": "stop", "model": self.model} + options = self._options(temperature, max_new_tokens, kwargs.get("seed")) + stop = kwargs.get("stop") + session = self._new_session(None) + + async def _call() -> Any: + return await session.respond(prompt, options=options) + + text = self._run(_call) + if not isinstance(text, str): + text = str(text) + text = _apply_stop(text, stop) + return {"text": text, "finish_reason": "stop", "model": self.model} + + def generate_stream( + self, + prompt: str, + temperature: float = 0.7, + max_new_tokens: int = 512, + top_p: float = 0.95, + top_k: int = 40, + repetition_penalty: float = 1.1, + logprobs: bool = False, + top_logprobs: Optional[int] = None, + **kwargs: Any, + ) -> Iterator[Dict[str, Any]]: + if not isinstance(prompt, str): + raise TypeError("prompt must be a string.") + options = self._options(temperature, max_new_tokens, kwargs.get("seed")) + stop = kwargs.get("stop") + for delta in _stop_deltas(self._stream_snapshots(prompt, options), stop): + yield {"text": delta} + + # -- chat API (native sessions) ------------------------------------ + + def chat( + self, + messages: List[Dict[str, Any]], + temperature: float = 0.7, + max_new_tokens: int = 512, + top_p: float = 0.95, + top_k: int = 40, + repetition_penalty: float = 1.1, + stream: bool = False, + stop: Optional[List[str]] = None, + tools: Optional[List[Dict[str, Any]]] = None, + tool_choice: Any = None, + response_format: Optional[Dict[str, Any]] = None, + seed: Optional[int] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + if stream: + chunks = list( + self.chat_stream( + messages, + temperature=temperature, + max_new_tokens=max_new_tokens, + stop=stop, + tools=tools, + tool_choice=tool_choice, + response_format=response_format, + seed=seed, + **kwargs, + ) + ) + text = "".join(chunk.get("text", "") for chunk in chunks) + finish = next( + (c["finish_reason"] for c in reversed(chunks) if c.get("finish_reason")), + "stop", + ) + return {"text": text, "finish_reason": finish, "model": self.model} + parts, instructions, attachments = self._chat_prompt(messages, tools) + options = self._options(temperature, max_new_tokens, seed) + schema = _json_schema_from_response_format(response_format) + with self._materialized(attachments) as objects: + prompt = _assemble_prompt(parts, objects) + session = self._new_session(instructions) + + async def _call() -> Any: + if schema is not None: + return await session.respond(prompt, json_schema=schema, options=options) + return await session.respond(prompt, options=options) + + result = self._run(_call) + text = _generated_content_to_text(result) + text = _apply_stop(text, stop) + return {"text": text, "finish_reason": "stop", "model": self.model} + + def chat_stream( + self, + messages: List[Dict[str, Any]], + temperature: float = 0.7, + max_new_tokens: int = 512, + top_p: float = 0.95, + top_k: int = 40, + repetition_penalty: float = 1.1, + stop: Optional[List[str]] = None, + tools: Optional[List[Dict[str, Any]]] = None, + tool_choice: Any = None, + response_format: Optional[Dict[str, Any]] = None, + seed: Optional[int] = None, + **kwargs: Any, + ) -> Iterator[Dict[str, Any]]: + parts, instructions, attachments = self._chat_prompt(messages, tools) + options = self._options(temperature, max_new_tokens, seed) + if _json_schema_from_response_format(response_format) is not None: + # The SDK does not stream guided generation; emit one chunk. + result = self.chat( + messages, + temperature=temperature, + max_new_tokens=max_new_tokens, + stop=stop, + tools=tools, + tool_choice=tool_choice, + response_format=response_format, + seed=seed, + **kwargs, + ) + yield {"text": result["text"], "finish_reason": result["finish_reason"]} + return + with self._materialized(attachments) as objects: + prompt = _assemble_prompt(parts, objects) + for delta in _stop_deltas(self._stream_snapshots(prompt, options, instructions), stop): + yield {"text": delta} + + def _chat_prompt( + self, + messages: List[Dict[str, Any]], + tools: Optional[List[Dict[str, Any]]], + ) -> Tuple[List[Tuple[str, Any]], Optional[str], List[Tuple[str, bytes]]]: + """Split messages into prompt parts, session instructions, attachments. + + Returns ``(parts, instructions, attachments)`` where ``parts`` is a + list of ``("text", str)`` / ``("image", index)`` tuples (indexes into + ``attachments``, a list of ``(suffix, bytes)``), and ``instructions`` + holds the joined system messages. Text-only histories assemble to + exactly the ``Role: text`` string the previous implementation sent. + """ + system_parts: List[str] = [] + parts: List[Tuple[str, Any]] = [] + attachments: List[Tuple[str, bytes]] = [] + for message in messages or []: + if not isinstance(message, dict): + continue + if message.get("role") == "system": + text = self.message_text(message) + if text: + system_parts.append(text) + continue + role = str(message.get("role", "user")).capitalize() + content = message.get("content") + if message.get("tool_calls"): + import json + + parts.append(("text", "Assistant tool calls: " + json.dumps(message["tool_calls"]))) + if message.get("role") == "tool": + role = "Tool %s" % message.get("name", message.get("tool_call_id", "")) + if isinstance(content, list): + texts: List[str] = [] + for item in content: + kind, value = _split_content_part(item) + if kind == "text": + texts.append(value) + else: + if texts: + parts.append(("text", "%s: %s" % (role, "".join(texts)))) + texts = [] + attachments.append(value) + parts.append(("image", len(attachments) - 1)) + parts.append(("text", "%s: %s" % (role, "".join(texts)))) + else: + parts.append(("text", "%s: %s" % (role, self.message_text(message)))) + parts.append(("text", "Assistant:")) + if tools: + parts.append( + ( + "text", + "Available tools (JSON):\n" + + _tools_documentation(tools) + + '\nTo call a tool, return only {"tool_calls":[{"function":{"name":"tool_name","arguments":{}}}]}. Do not invent tool results.', + ) + ) + instructions = "\n\n".join(system_parts) or None + return parts, instructions, attachments + + def _materialized(self, attachments: List[Tuple[str, bytes]]) -> Any: + """Context manager yielding ``ImageAttachment`` objects for image bytes. + + Files live only for the block (the SDK reads them synchronously + during the request) and are removed afterwards, even on failure. + """ + import contextlib + import pathlib + + @contextlib.contextmanager + def _manager() -> Any: + paths: List[str] = [] + try: + for suffix, data in attachments: + handle, path = tempfile.mkstemp(prefix="llmk-apple-", suffix=suffix) + with os.fdopen(handle, "wb") as stream: + stream.write(data) + paths.append(path) + if paths and not hasattr(self._fm, "ImageAttachment"): + raise NotImplementedError( + "This Apple SDK lacks image attachments; use an SDK/OS with image support." + ) + yield [self._fm.ImageAttachment(pathlib.Path(path)) for path in paths] + finally: + for path in paths: + try: + os.unlink(path) + except OSError: + pass + + return _manager() + + def _stream_snapshots( + self, + prompt: Any, + options: Any, + instructions: Optional[str] = None, + ) -> Iterator[str]: + """Yield text *deltas* from the SDK's full-text snapshots. + + The async iteration runs on a worker thread (the SDK streams via a + background callback); snapshots cross over a queue and the caller + thread diffs them into deltas. + """ + inbox: "queue.Queue[Any]" = queue.Queue(maxsize=32) + sentinel = object() + cancelled = threading.Event() + state: Dict[str, Any] = {} + + async def enqueue(item): + while not cancelled.is_set(): + try: + inbox.put_nowait(item) + return + except queue.Full: + await asyncio.sleep(0.01) + + async def consume(): + state.update(loop=asyncio.get_running_loop(), task=asyncio.current_task()) + try: + session = self._new_session(instructions) + async for snapshot in session.stream_response(prompt, options): + await enqueue(str(snapshot)) + except asyncio.CancelledError: + raise + except Exception as exc: + await enqueue(exc) + finally: + await enqueue(sentinel) + + def target(): + try: + asyncio.run(consume()) + except asyncio.CancelledError: + pass + + worker = threading.Thread(target=target, daemon=True) + worker.start() + previous = "" + deadline = None if self.timeout is None else time.monotonic() + self.timeout + try: + while True: + remaining = None if deadline is None else max(0, deadline - time.monotonic()) + try: + item = inbox.get(timeout=remaining) + except queue.Empty: + raise TimeoutError( + "Apple Foundation Models stream exceeded its timeout." + ) from None + if item is sentinel: + break + if isinstance(item, BaseException): + raise item + snapshot = str(item) + if not snapshot.startswith(previous): + raise RuntimeError("Apple stream revised text already emitted to the caller.") + delta = snapshot[len(previous) :] + previous = snapshot + if delta: + yield delta + finally: + cancelled.set() + loop, task = state.get("loop"), state.get("task") + if loop is not None and task is not None and not task.done(): + try: + loop.call_soon_threadsafe(task.cancel) + except RuntimeError: + pass # The producer finished while the consumer closed. + # shortcut: cancellation is cooperative; SDK code that ignores it + # needs a subprocess if hard termination becomes necessary. + worker.join(0.2) + + # -- introspection -------------------------------------------------- + + def get_context_window(self) -> int: + return self._context_window + + def count_tokens(self, text: str) -> int: + """~4 chars/token heuristic (the SDK's exact ``token_count`` is async + and would add a round trip per call; use :meth:`count_tokens_exact` + for exact budgeting against ``context_size``).""" + if not text: + return 0 + return max(1, len(text) // 4) + + def count_tokens_exact( + self, text: Optional[str] = None, instructions: Optional[str] = None + ) -> int: + """Exact token count via the SDK's async ``token_count``. + + Pass either ``text`` (a prompt) or ``instructions`` (system text), + not both — mirroring the SDK's own mutual exclusivity. Useful for + precise budgeting against :meth:`get_context_window`. + """ + if (text is None) == (instructions is None): + raise ValueError("Pass exactly one of text= or instructions=.") + + async def _call() -> Any: + if instructions is not None: + return await self._system_model.token_count(instructions=instructions) + return await self._system_model.token_count(text) + + return int(self._run(_call)) + + def model_info(self) -> Dict[str, Any]: + info = super().model_info() + info.update( + { + "on_device": True, + "requires_network": False, + "use_case": _enum_name(self.use_case), + "guardrails": _enum_name(self.guardrails), + "variant": self._variant_name(), + } + ) + return info + + def _variant_name(self) -> Optional[str]: + try: + variant = self._system_model.variant + except Exception: + return None + if variant is None: + return None + return getattr(variant, "display_name", None) or str(variant) + + def list_models(self) -> List[Dict[str, Any]]: + return [{"id": self.model, "object": "model", "owned_by": "apple"}] + + +# -- helpers ------------------------------------------------------------ + + +#: Maximum inline image size materialised to disk (matches the 20 MB base64 +#: cap documented for ``apfel --serve`` vision input). +_MAX_IMAGE_BYTES = 20 * 1024 * 1024 + +#: Allowed image suffixes for materialised data URLs (sanitised; anything +#: else falls back to ``.png`` so temp files keep a safe extension). +_IMAGE_SUFFIXES = ("png", "jpg", "jpeg", "gif", "webp", "bmp", "tiff", "heic") + + +def _assemble_prompt(parts: List[Tuple[str, Any]], objects: List[Any]) -> Any: + """Build the SDK prompt from parts. + + Text-only histories assemble to the plain ``Role: text`` string used + before vision support existed; histories with images become a mixed + ``[str, ImageAttachment, ...]`` list. + """ + if not objects: + return "\n".join(text for kind, text in parts if kind == "text") + prompt: List[Any] = [] + for kind, value in parts: + if kind == "text": + prompt.append(value) + else: + prompt.append(objects[value]) + return prompt + + +def _split_content_part(part: Any) -> Tuple[str, Any]: + """Split one OpenAI content part into ``("text", str)`` or image bytes. + + Returns ``("image", (suffix, bytes))`` for ``image_url`` parts with + inline ``data:image/...;base64,`` URLs. Anything else degrades to text + (``[image]`` placeholder), preserving the old fallback for shapes this + backend cannot materialise. + """ + if isinstance(part, str): + return "text", part + if not isinstance(part, dict): + return "text", str(part) + ptype = part.get("type", "text") + if ptype == "text": + return "text", str(part.get("text", "")) + if ptype in ("image_url", "image"): + image = part.get("image_url", part.get("image", "")) + url = image.get("url", "") if isinstance(image, dict) else image + if isinstance(url, str) and url.startswith("data:image/"): + return "image", _parse_image_data_url(url) + if isinstance(url, str) and url: + raise ValueError( + "Apple Foundation Models image parts must use inline base64 " + "data URLs; remote URLs are never downloaded (got %r...)." % (url[:48],) + ) + return "text", "[image]" + return "text", str(part.get("text", "")) + + +def _parse_image_data_url(url: str) -> Tuple[str, bytes]: + """Decode ``data:image/;base64,`` to ``(suffix, bytes)``.""" + try: + header, _, payload = url.partition(",") + if not payload or "base64" not in header: + raise ValueError("missing base64 payload") + mime = header[5:].split(";")[0].strip().lower() + subtype = "".join(c for c in mime.split("/")[-1] if c.isalnum()) or "png" + suffix = "." + (subtype if subtype in _IMAGE_SUFFIXES else "png") + if len(payload) > ((_MAX_IMAGE_BYTES + 2) // 3) * 4: + raise ValueError("Inline image exceeds the 20 MiB limit.") + data = base64.b64decode(payload, validate=True) + except Exception as exc: + raise ValueError("Invalid inline image data URL: %s" % (exc,)) from exc + if not data: + raise ValueError("Invalid inline image data URL: empty payload.") + if len(data) > _MAX_IMAGE_BYTES: + raise ValueError( + "Inline image is %d bytes; the limit is %d bytes." % (len(data), _MAX_IMAGE_BYTES) + ) + return suffix, data + + +def _stop_deltas(chunks: Iterator[str], stop: Any) -> Iterator[str]: + """Hold a suffix so a stop sequence split across chunks never leaks.""" + stops = [stop] if isinstance(stop, str) else list(stop or []) + stops = [marker for marker in stops if isinstance(marker, str) and marker] + pending = "" + hold = max((len(marker) - 1 for marker in stops), default=0) + try: + for chunk in chunks: + pending += chunk + cut = min((pending.find(marker) for marker in stops if marker in pending), default=-1) + if cut >= 0: + if cut: + yield pending[:cut] + return + emit = len(pending) - hold + if emit > 0: + yield pending[:emit] + pending = pending[emit:] + if pending: + yield pending + finally: + close = getattr(chunks, "close", None) + if close: + close() + + +def _apply_stop(text: str, stop: Any) -> str: + if not stop: + return text + stops = [stop] if isinstance(stop, str) else list(stop) + cut = len(text) + for marker in stops: + if not isinstance(marker, str) or not marker: + continue + index = text.find(marker) + if index != -1: + cut = min(cut, index) + return text[:cut] + + +def _json_schema_from_response_format(response_format: Any) -> Optional[Dict[str, Any]]: + if not isinstance(response_format, dict): + return None + if response_format.get("type") != "json_schema": + return None + schema = response_format.get("json_schema", {}) + if isinstance(schema, dict): + inner = schema.get("schema", schema) + if isinstance(inner, dict): + return inner + return None + + +def _generated_content_to_text(result: Any) -> str: + """Best-effort conversion of an SDK response to text. + + Plain ``respond()`` returns ``str``; ``json_schema`` guided generation + returns ``GeneratedContent`` (verified: ``to_json() -> str`` in + ``apple-fm-sdk`` 0.2.x ``generable.py``). + """ + if isinstance(result, str): + return result + to_json = getattr(result, "to_json", None) + if callable(to_json): + try: + text = to_json() + if isinstance(text, str): + return text + except Exception: + pass + return str(result) + + +def _tools_documentation(tools: List[Dict[str, Any]]) -> str: + import json as _json + + specs = [] + for tool in tools: + if not isinstance(tool, dict): + continue + fn = tool.get("function", tool) if isinstance(tool, dict) else {} + if not isinstance(fn, dict) or not fn.get("name"): + continue + specs.append( + { + "name": fn.get("name"), + "description": fn.get("description", ""), + "parameters": fn.get("parameters", {}), + } + ) + try: + return _json.dumps(specs) + except (TypeError, ValueError): + return str(specs) + + +def _enum_name(value: Any) -> str: + name = getattr(value, "name", None) + if isinstance(name, str): + return name.lower() + text = getattr(value, "value", value) + return str(text).lower() diff --git a/local_llm_kit/backends/ollama.py b/local_llm_kit/backends/ollama.py index cc2b849..ae65ada 100644 --- a/local_llm_kit/backends/ollama.py +++ b/local_llm_kit/backends/ollama.py @@ -8,10 +8,12 @@ """ import json +import math import urllib.error import urllib.request from typing import Any, Dict, Iterator, List, Optional, Union +from ..retry import DEFAULT_RETRY, RetryPolicy, coerce_policy, retry_after_seconds from .base import BaseBackend _GENERATE_PATH = "/api/generate" @@ -21,6 +23,12 @@ _TAGS_PATH = "/api/tags" _SHOW_PATH = "/api/show" +#: Timeout used by the optional capability lookup, which must not stall a call. +_DETECT_TIMEOUT = 5.0 + +#: Capability detection is best-effort and must stay fast: one attempt only. +_NO_RETRY = RetryPolicy(max_retries=0) + _OPTION_KEYS = { "temperature", "top_p", @@ -48,10 +56,14 @@ class OllamaBackend(BaseBackend): """Backend for Ollama servers. Import-safe without any optional deps.""" backend_name = "ollama" - supports_vision = True # images pass through in chat messages supports_embeddings = True supports_native_chat = True + #: Vision is forwarded as image content parts, so it is *capable* by default. + #: The loaded model may not be: :meth:`detect_capabilities` narrows this to + #: what the server reports for the model. + _default_supports_vision = True + def __init__( self, model: str = "llama3.1", @@ -60,26 +72,159 @@ def __init__( context_window: int = 4096, keep_alive: str = "5m", headers: Optional[Dict[str, str]] = None, + auto_detect_capabilities: bool = False, + max_retries: Union[int, RetryPolicy, None] = None, **kwargs: Any, ) -> None: """Args: model: Model name as known to Ollama (e.g. ``"llama3.1"``). host: Ollama server base URL. timeout: HTTP timeout in seconds. - context_window: Reported context window (Ollama does not expose a - single reliable value; override via ``num_ctx`` passthrough or - this parameter). + context_window: Fallback context window, used until the server reports + the model's real one. Ollama's ``/api/show`` publishes it (for + example 32768 for ``qwen2.5:0.5b``), so 4096 is only a floor. keep_alive: Ollama ``keep_alive`` value sent with requests. headers: Extra HTTP headers. + auto_detect_capabilities: Read the model's real context length and + capability list from the server on first use. Off by default so + constructing a backend never requires a running server; turn it on + to get truthful ``context_window``/``supports_vision``. + max_retries: Retries for transient failures — a refused connection + (``ollama serve`` has not started yet) or a ``429``/``5xx`` answer. + Defaults to two retries with exponential backoff and ``Retry-After`` + support, matching the official OpenAI Python client. Pass ``0`` for + single-attempt behaviour, an int for a custom count, or a + :class:`~local_llm_kit.retry.RetryPolicy`. """ self.model = model self.model_path = model self.host = host.rstrip("/") - self.timeout = timeout + if ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not math.isfinite(timeout) + or timeout <= 0 + ): + raise ValueError("timeout must be a finite positive number.") + self.timeout = float(timeout) self.context_window = context_window self.keep_alive = keep_alive self.extra_headers = dict(headers or {}) self.default_options = dict(kwargs) # e.g. num_ctx=8192 + self.auto_detect_capabilities = bool(auto_detect_capabilities) + self.retry = coerce_policy(DEFAULT_RETRY if max_retries is None else max_retries) + #: Capability names reported by the server (``None`` until detected). + self.capabilities: Optional[List[str]] = None + #: True when the model is routed to a remote host such as ollama.com. + self.remote = False + self.remote_host: Optional[str] = None + self._detected = False + self._routing_verified = False + + # -- capability detection ------------------------------------------ + + @property + def supports_vision(self) -> bool: # type: ignore[override] + """True when images can usefully reach the model. + + Reports the server's own ``vision`` capability once detected, and the + adapter's forwarding ability otherwise. + """ + if self.capabilities is not None: + return any(c.lower() in ("vision", "image") for c in self.capabilities) + return self._default_supports_vision + + def detect_capabilities(self, timeout: Optional[float] = None) -> Dict[str, Any]: + """Ask the server what this model can do. Never raises. + + Reads ``POST /api/show`` for the true ``context_length`` and + ``capabilities``, and ``GET /api/tags`` for ``remote_host`` (Ollama + marks provider-routed models there). Updates + :attr:`context_window`, :attr:`capabilities`, :attr:`remote` and + :attr:`remote_host` in place. + + Returns: + The detection outcome, including what changed. A failure is + reported in ``"error"`` and leaves the current values untouched. + """ + result: Dict[str, Any] = { + "model": self.model, + "detected": False, + "capabilities": None, + "context_window": self.context_window, + "remote": self.remote, + "remote_host": self.remote_host, + "error": None, + } + effective_timeout = self.timeout if timeout is None else timeout + try: + show = self._post_json( + _SHOW_PATH, {"model": self.model}, timeout=effective_timeout, policy=_NO_RETRY + ) + except Exception as exc: # noqa: BLE001 - detection is best-effort + result["error"] = str(exc) + return result + + capabilities = show.get("capabilities") + if isinstance(capabilities, list) and capabilities: + self.capabilities = [str(c) for c in capabilities] + result["capabilities"] = list(self.capabilities) + + context_length = self._context_length_from(show) + if context_length: + self.context_window = context_length + result["context_window"] = context_length + + self._detect_remote(effective_timeout) + result.update( + { + "detected": True, + "remote": self.remote, + "remote_host": self.remote_host, + "routing_verified": self._routing_verified, + } + ) + self._detected = True + return result + + @staticmethod + def _context_length_from(show: Dict[str, Any]) -> Optional[int]: + """Pull ``.context_length`` out of an ``/api/show`` body.""" + info = show.get("model_info") + if not isinstance(info, dict): + return None + for key, value in info.items(): + if key.endswith(".context_length") and isinstance(value, int) and value > 0: + return value + return None + + def _detect_remote(self, timeout: float) -> None: + """Record whether ``/api/tags`` marks this model as provider-routed.""" + self._routing_verified = False + try: + tags = self._get_json(_TAGS_PATH, timeout=timeout, policy=_NO_RETRY) + except Exception: # noqa: BLE001 - best-effort + return + for entry in tags.get("models") or []: + if not isinstance(entry, dict): + continue + candidate = entry.get("name") or entry.get("model") + if candidate not in (self.model, self.model + ":latest"): + continue + self._routing_verified = True + self.remote = False + self.remote_host = None + host = entry.get("remote_host") + if isinstance(host, str) and host: + self.remote = True + self.remote_host = host + elif entry.get("remote_model"): + self.remote = True + self.remote_host = host or "remote" + elif self.model.lower().endswith(":cloud"): + self.remote = True + self.remote_host = host or "remote" + return # -- prompt API ---------------------------------------------------- @@ -297,6 +442,13 @@ def _embed_single(self, text: str) -> List[float]: # -- introspection ------------------------------------------------- def get_context_window(self) -> int: + """Return the model's context window, detecting the real value if asked. + + With ``auto_detect_capabilities=True`` the first call asks the server; + a server that is down or silent leaves the configured fallback in place. + """ + if self.auto_detect_capabilities and not self._detected: + self.detect_capabilities(timeout=_DETECT_TIMEOUT) return self.context_window def count_tokens(self, text: str) -> int: @@ -308,24 +460,47 @@ def count_tokens(self, text: str) -> int: def model_info(self) -> Dict[str, Any]: info = super().model_info() info.update({"host": self.host, "keep_alive": self.keep_alive}) + if self.capabilities is not None: + info["capabilities"] = list(self.capabilities) + if self.remote: + info["remote"] = True + info["remote_host"] = self.remote_host return info def list_models(self) -> List[Dict[str, Any]]: - """GET /api/tags, normalized to ``[{"id", "object", ...}]``.""" + """GET /api/tags, normalized to ``[{"id", "object", ...}]``. + + Each entry keeps the server's own ``capabilities`` (for example + ``["completion", "tools", "thinking"]``), the model's real + ``context_length``, and ``remote_host`` when Ollama routes the model to + a provider such as ollama.com rather than running it on this machine. + """ resp = self._get_json(_TAGS_PATH) out = [] for m in resp.get("models", []) or []: - out.append( - { - "id": m.get("name", m.get("model", "unknown")), - "object": "model", - "owned_by": "ollama", - "size": m.get("size"), - "digest": m.get("digest"), - "modified_at": m.get("modified_at"), - "details": m.get("details", {}), - } - ) + details = m.get("details", {}) or {} + entry: Dict[str, Any] = { + "id": m.get("name", m.get("model", "unknown")), + "object": "model", + "owned_by": "ollama", + "size": m.get("size"), + "digest": m.get("digest"), + "modified_at": m.get("modified_at"), + "details": details, + } + capabilities = m.get("capabilities") + if isinstance(capabilities, list): + entry["capabilities"] = [str(c) for c in capabilities] + context_length = details.get("context_length") + if isinstance(context_length, int): + entry["context_length"] = context_length + remote_host = m.get("remote_host") + if isinstance(remote_host, str) and remote_host: + entry["remote"] = True + entry["remote_host"] = remote_host + elif m.get("remote_model") or str(entry["id"]).lower().endswith(":cloud"): + entry["remote"] = True + out.append(entry) return out def show(self) -> Dict[str, Any]: @@ -499,73 +674,110 @@ def _headers(self) -> Dict[str, str]: headers.update(self.extra_headers) return headers - def _post_json(self, path: str, payload: Dict[str, Any]) -> Dict[str, Any]: + def _open_with_retry( + self, + request_factory: Any, + method: str, + path: str, + timeout: Optional[float], + policy: Optional[Any] = None, + ) -> Any: + """Run a request, retrying transient failures per :attr:`retry`. + + Retries a refused connection — the usual "``ollama serve`` has not + started yet" case — and the transient statuses (``429``/``5xx``), which + cover a model still being loaded. ``4xx`` client errors fail at once. + """ + effective = self.retry if policy is None else policy + effective_timeout = self.timeout if timeout is None else timeout + attempt = 0 + while True: + try: + return urllib.request.urlopen(request_factory(), timeout=effective_timeout) + except urllib.error.HTTPError as e: + if effective.should_retry_status(e.code) and attempt < effective.max_retries: + delay = retry_after_seconds(e.headers) + e.close() + effective.sleep(attempt + 1, delay) + attempt += 1 + continue + try: + body = e.read().decode("utf-8", errors="replace") + finally: + e.close() + raise RuntimeError( + "Ollama request %s %s failed with HTTP %s: %s" % (method, path, e.code, body) + ) from e + except urllib.error.URLError as e: + if attempt < effective.max_retries: + effective.sleep(attempt + 1) + attempt += 1 + continue + raise ConnectionError( + "Ollama server not reachable at %s (%s). Is Ollama running? " + "Start it with `ollama serve` and pull a model with " + "`ollama pull %s`." % (self.host, e.reason, self.model) + ) from e + + def _post_json( + self, + path: str, + payload: Dict[str, Any], + timeout: Optional[float] = None, + policy: Optional[Any] = None, + ) -> Dict[str, Any]: data = json.dumps(payload).encode("utf-8") - req = urllib.request.Request( - self.host + path, - data=data, - headers=self._headers(), - method="POST", - ) + + def _request() -> Any: + return urllib.request.Request( + self.host + path, + data=data, + headers=self._headers(), + method="POST", + ) + try: - with urllib.request.urlopen(req, timeout=self.timeout) as resp: + with self._open_with_retry(_request, "POST", path, timeout, policy) as resp: return json.loads(resp.read().decode("utf-8")) - except urllib.error.HTTPError as e: - body = e.read().decode("utf-8", errors="replace") - raise RuntimeError( - "Ollama request POST %s failed with HTTP %s: %s" % (path, e.code, body) - ) from e - except urllib.error.URLError as e: - raise ConnectionError( - "Ollama server not reachable at %s (%s). Is Ollama running? " - "Start it with `ollama serve` and pull a model with " - "`ollama pull %s`." % (self.host, e.reason, self.model) - ) from e except (ValueError, json.JSONDecodeError) as e: raise RuntimeError("Ollama returned invalid JSON: %s" % e) from e - def _post_json_lines(self, path: str, payload: Dict[str, Any]) -> Iterator[Dict[str, Any]]: - """POST with ``stream=True``; yields one dict per JSON line.""" + def _post_json_lines( + self, + path: str, + payload: Dict[str, Any], + policy: Optional[Any] = None, + ) -> Iterator[Dict[str, Any]]: + """POST with ``stream=True``; yields one dict per JSON line. + + Only the connection phase is retried: once lines have been yielded, + retrying would replay tokens the caller already received. + """ data = json.dumps(payload).encode("utf-8") - req = urllib.request.Request( - self.host + path, - data=data, - headers=self._headers(), - method="POST", - ) - try: - with urllib.request.urlopen(req, timeout=self.timeout) as resp: - for raw_line in resp: - line = raw_line.decode("utf-8", errors="replace").strip() - if not line: - continue - try: - yield json.loads(line) - except ValueError: - continue # skip keep-alive / partial lines - except urllib.error.HTTPError as e: - body = e.read().decode("utf-8", errors="replace") - raise RuntimeError( - "Ollama request POST %s failed with HTTP %s: %s" % (path, e.code, body) - ) from e - except urllib.error.URLError as e: - raise ConnectionError( - "Ollama server not reachable at %s (%s). Is Ollama running? " - "Start it with `ollama serve`." % (self.host, e.reason) - ) from e - - def _get_json(self, path: str) -> Dict[str, Any]: - req = urllib.request.Request(self.host + path, headers=self._headers(), method="GET") - try: - with urllib.request.urlopen(req, timeout=self.timeout) as resp: - return json.loads(resp.read().decode("utf-8")) - except urllib.error.HTTPError as e: - body = e.read().decode("utf-8", errors="replace") - raise RuntimeError( - "Ollama request GET %s failed with HTTP %s: %s" % (path, e.code, body) - ) from e - except urllib.error.URLError as e: - raise ConnectionError( - "Ollama server not reachable at %s (%s). Is Ollama running? " - "Start it with `ollama serve`." % (self.host, e.reason) - ) from e + + def _request() -> Any: + return urllib.request.Request( + self.host + path, + data=data, + headers=self._headers(), + method="POST", + ) + + with self._open_with_retry(_request, "POST", path, None, policy) as resp: + for raw_line in resp: + line = raw_line.decode("utf-8", errors="replace").strip() + if not line: + continue + try: + yield json.loads(line) + except ValueError: + continue # skip keep-alive / partial lines + + def _get_json( + self, path: str, timeout: Optional[float] = None, policy: Optional[Any] = None + ) -> Dict[str, Any]: + def _request() -> Any: + return urllib.request.Request(self.host + path, headers=self._headers(), method="GET") + + with self._open_with_retry(_request, "GET", path, timeout, policy) as resp: + return json.loads(resp.read().decode("utf-8")) diff --git a/local_llm_kit/backends/openai_compat.py b/local_llm_kit/backends/openai_compat.py index 9dbb73a..6c8badc 100644 --- a/local_llm_kit/backends/openai_compat.py +++ b/local_llm_kit/backends/openai_compat.py @@ -10,15 +10,24 @@ - ``POST /v1/embeddings`` - ``GET /v1/models`` +Provider profiles: ``provider`` selects protocol quirks. ``"apfel"`` targets +``apfel --serve`` (https://github.com/Arthur-Ficial/apfel), whose server +answers 400 to sampling fields it does not implement (``top_k``/penalties) +and 501 to ``POST /v1/completions`` and ``POST /v1/embeddings``. That +profile therefore omits those fields, maps prompt completions to chat, +and reports no embedding support. + Stdlib-only (``urllib`` + ``json``). ``api_key`` is optional — local servers usually don't need one. """ import json +import math import urllib.error import urllib.request from typing import Any, Dict, Iterator, List, Optional, Union +from ..retry import DEFAULT_RETRY, RetryPolicy, coerce_policy, retry_after_seconds from .base import BaseBackend _DONE = "[DONE]" @@ -41,6 +50,7 @@ def __init__( context_window: int = 4096, headers: Optional[Dict[str, str]] = None, provider: str = "openai-compat", + max_retries: Union[int, RetryPolicy, None] = None, **kwargs: Any, ) -> None: """Args: @@ -51,16 +61,30 @@ def __init__( timeout: HTTP timeout in seconds. context_window: Reported context window (override per server). headers: Extra HTTP headers. + max_retries: Retries for transient failures — a refused connection or a + ``429``/``5xx`` answer. Defaults to two retries with exponential + backoff and ``Retry-After`` support, matching the official OpenAI + Python client. Pass ``0`` for single-attempt behaviour, an int for a + custom count, or a :class:`~local_llm_kit.retry.RetryPolicy`. """ self.model = model self.provider = provider - self.supports_embeddings = provider not in ("gpt4all", "mlx-lm") + self.supports_embeddings = provider not in ("gpt4all", "mlx-lm", "apfel") + self._chat_only = provider == "apfel" self.model_path = model self.base_url = base_url.rstrip("/") self.api_key = api_key - self.timeout = timeout + if ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not math.isfinite(timeout) + or timeout <= 0 + ): + raise ValueError("timeout must be a finite positive number.") + self.timeout = float(timeout) self.context_window = context_window self.extra_headers = dict(headers or {}) + self.retry = coerce_policy(DEFAULT_RETRY if max_retries is None else max_retries) self.default_params = dict(kwargs) # -- prompt API (/v1/completions) ---------------------------------- @@ -78,6 +102,14 @@ def generate( top_logprobs: Optional[int] = None, **kwargs: Any, ) -> Dict[str, Any]: + if self._chat_only: + return self.chat( + [{"role": "user", "content": prompt}], + temperature=temperature, + max_new_tokens=max_new_tokens, + stream=stream, + **kwargs, + ) if stream: text = "".join( c["text"] @@ -127,6 +159,14 @@ def generate_stream( top_logprobs: Optional[int] = None, **kwargs: Any, ) -> Iterator[Dict[str, Any]]: + if self._chat_only: + yield from self.chat_stream( + [{"role": "user", "content": prompt}], + temperature=temperature, + max_new_tokens=max_new_tokens, + **kwargs, + ) + return payload = self._completion_payload( prompt, temperature, @@ -196,6 +236,9 @@ def chat( } if tool_calls: result["tool_calls"] = tool_calls + reasoning = "".join(chunk.get("reasoning_content", "") for chunk in chunks) + if reasoning: + result["reasoning_content"] = reasoning return result payload = self._chat_payload( messages, @@ -221,6 +264,7 @@ def chat( return { "text": self._content_text(message.get("content")), "tool_calls": message.get("tool_calls"), + "reasoning_content": message.get("reasoning_content") or message.get("reasoning"), "finish_reason": choice.get("finish_reason", "stop"), "usage": resp.get("usage"), "model": resp.get("model", self.model), @@ -264,6 +308,10 @@ def chat_stream( chunk: Dict[str, Any] = { "text": self._content_text(delta.get("content")), } + if delta.get("reasoning_content") or delta.get("reasoning"): + chunk["reasoning_content"] = ( + delta.get("reasoning_content") or delta["reasoning"] + ) if delta.get("tool_calls"): chunk["tool_calls_delta"] = delta["tool_calls"] for part in delta["tool_calls"]: @@ -286,7 +334,12 @@ def chat_stream( chunk["finish_reason"] = choice["finish_reason"] if calls: chunk["tool_calls"] = [calls[index] for index in sorted(calls)] - if chunk["text"] or chunk.get("finish_reason") or "tool_calls_delta" in chunk: + if ( + chunk["text"] + or chunk.get("finish_reason") + or "tool_calls_delta" in chunk + or chunk.get("reasoning_content") + ): yield chunk # -- embeddings (/v1/embeddings) ----------------------------------- @@ -379,13 +432,15 @@ def _completion_payload( ) -> Dict[str, Any]: # top_k / repetition_penalty are not OpenAI fields; most local # servers accept them as extra body params, so pass through. - kwargs.setdefault("top_k", top_k) - penalty_key = ( - "repetition_penalty" - if self.provider in ("vllm", "sglang", "mlx-lm") - else "repeat_penalty" - ) - kwargs.setdefault(penalty_key, repetition_penalty) + # Exception: the apfel profile rejects them with HTTP 400, so omit. + if self.provider != "apfel": + kwargs.setdefault("top_k", top_k) + penalty_key = ( + "repetition_penalty" + if self.provider in ("vllm", "sglang", "mlx-lm") + else "repeat_penalty" + ) + kwargs.setdefault(penalty_key, repetition_penalty) payload = self._base_sampling(temperature, max_new_tokens, top_p, stream=stream, **kwargs) payload["prompt"] = prompt return payload @@ -406,13 +461,16 @@ def _chat_payload( seed: Optional[int], **kwargs: Any, ) -> Dict[str, Any]: - kwargs.setdefault("top_k", top_k) - penalty_key = ( - "repetition_penalty" - if self.provider in ("vllm", "sglang", "mlx-lm") - else "repeat_penalty" - ) - kwargs.setdefault(penalty_key, repetition_penalty) + # See _completion_payload: the apfel profile rejects top_k/penalty + # fields with HTTP 400, so omit them there. + if self.provider != "apfel": + kwargs.setdefault("top_k", top_k) + penalty_key = ( + "repetition_penalty" + if self.provider in ("vllm", "sglang", "mlx-lm") + else "repeat_penalty" + ) + kwargs.setdefault(penalty_key, repetition_penalty) payload = self._base_sampling(temperature, max_new_tokens, top_p, stream=stream, **kwargs) payload["messages"] = [ { @@ -460,81 +518,98 @@ def _headers(self, stream: bool = False) -> Dict[str, str]: headers.update(self.extra_headers) return headers + def _open_with_retry(self, request_factory: Any, method: str, path: str) -> Any: + """Run a request, retrying transient failures per :attr:`retry`. + + Retries a refused connection (the server has not started yet) and the + transient HTTP statuses (``429``, ``5xx`` — llama.cpp answers ``503`` + while it loads a model). Client errors such as ``400`` fail immediately. + The error messages match the single-attempt behaviour. + """ + policy = self.retry + attempt = 0 + while True: + try: + return urllib.request.urlopen(request_factory(), timeout=self.timeout) + except urllib.error.HTTPError as e: + if policy.should_retry_status(e.code) and attempt < policy.max_retries: + delay = retry_after_seconds(e.headers) + e.close() + policy.sleep(attempt + 1, delay) + attempt += 1 + continue + try: + body = e.read().decode("utf-8", errors="replace") + finally: + e.close() + raise RuntimeError( + "OpenAI-compatible request %s %s%s failed with HTTP %s: %s" + % (method, self.base_url, path, e.code, body) + ) from e + except urllib.error.URLError as e: + if attempt < policy.max_retries: + policy.sleep(attempt + 1) + attempt += 1 + continue + raise ConnectionError( + "Server not reachable at %s (%s). Is your OpenAI-compatible " + "server (vLLM / LM Studio / llama-server) running with " + "--host/--port matching base_url?" % (self.base_url, e.reason) + ) from e + def _post_json(self, path: str, payload: Dict[str, Any]) -> Dict[str, Any]: data = json.dumps(payload).encode("utf-8") - req = urllib.request.Request( - self.base_url + path, - data=data, - headers=self._headers(), - method="POST", - ) - try: - with urllib.request.urlopen(req, timeout=self.timeout) as resp: - return json.loads(resp.read().decode("utf-8")) - except urllib.error.HTTPError as e: - body = e.read().decode("utf-8", errors="replace") - raise RuntimeError( - "OpenAI-compatible request POST %s%s failed with HTTP %s: %s" - % (self.base_url, path, e.code, body) - ) from e - except urllib.error.URLError as e: - raise ConnectionError( - "Server not reachable at %s (%s). Is your OpenAI-compatible " - "server (vLLM / LM Studio / llama-server) running with " - "--host/--port matching base_url?" % (self.base_url, e.reason) - ) from e + + def _request() -> Any: + return urllib.request.Request( + self.base_url + path, + data=data, + headers=self._headers(), + method="POST", + ) + + with self._open_with_retry(_request, "POST", path) as resp: + return json.loads(resp.read().decode("utf-8")) def _post_sse(self, path: str, payload: Dict[str, Any]) -> Iterator[Dict[str, Any]]: - """POST with ``stream=True``; parses SSE ``data:`` frames.""" + """POST with ``stream=True``; parses SSE ``data:`` frames. + + Only the connection phase is retried: once the first frame has been + yielded, retrying would replay tokens the caller already received. + """ data = json.dumps(payload).encode("utf-8") - req = urllib.request.Request( - self.base_url + path, - data=data, - headers=self._headers(stream=True), - method="POST", - ) - try: - with urllib.request.urlopen(req, timeout=self.timeout) as resp: - for raw_line in resp: - line = raw_line.decode("utf-8", errors="replace").strip() - if not line or line.startswith(":"): - continue # blank / keep-alive comment - if not line.startswith("data:"): - continue - data_str = line[len("data:") :].strip() - if data_str == _DONE: - break - try: - event = json.loads(data_str) - except ValueError: - continue # partial frame; skip - if isinstance(event, dict): - yield event - except urllib.error.HTTPError as e: - body = e.read().decode("utf-8", errors="replace") - raise RuntimeError( - "OpenAI-compatible request POST %s%s failed with HTTP %s: %s" - % (self.base_url, path, e.code, body) - ) from e - except urllib.error.URLError as e: - raise ConnectionError( - "Server not reachable at %s (%s). Is your OpenAI-compatible " - "server running?" % (self.base_url, e.reason) - ) from e + + def _request() -> Any: + return urllib.request.Request( + self.base_url + path, + data=data, + headers=self._headers(stream=True), + method="POST", + ) + + with self._open_with_retry(_request, "POST", path) as resp: + for raw_line in resp: + line = raw_line.decode("utf-8", errors="replace").strip() + if not line or line.startswith(":"): + continue # blank / keep-alive comment + if not line.startswith("data:"): + continue + data_str = line[len("data:") :].strip() + if data_str == _DONE: + break + try: + event = json.loads(data_str) + except ValueError: + continue # partial frame; skip + if isinstance(event, dict): + yield event def _get_json(self, path: str) -> Dict[str, Any]: - req = urllib.request.Request(self.base_url + path, headers=self._headers(), method="GET") - try: - with urllib.request.urlopen(req, timeout=self.timeout) as resp: - result = json.loads(resp.read().decode("utf-8")) - return result if isinstance(result, dict) else {"data": result} - except urllib.error.HTTPError as e: - body = e.read().decode("utf-8", errors="replace") - raise RuntimeError( - "OpenAI-compatible request GET %s%s failed with HTTP %s: %s" - % (self.base_url, path, e.code, body) - ) from e - except urllib.error.URLError as e: - raise ConnectionError( - "Server not reachable at %s (%s)." % (self.base_url, e.reason) - ) from e + def _request() -> Any: + return urllib.request.Request( + self.base_url + path, headers=self._headers(), method="GET" + ) + + with self._open_with_retry(_request, "GET", path) as resp: + result = json.loads(resp.read().decode("utf-8")) + return result if isinstance(result, dict) else {"data": result} diff --git a/local_llm_kit/cli.py b/local_llm_kit/cli.py index 16b78dc..49a9e79 100644 --- a/local_llm_kit/cli.py +++ b/local_llm_kit/cli.py @@ -28,6 +28,7 @@ import inspect import json import os +import shlex import sys from typing import Any, Dict, List, NoReturn, Optional, Tuple @@ -48,6 +49,8 @@ "handle_pull_command", "handle_list_command", "handle_embed_command", + "handle_doctor_command", + "handle_mcp_command", ] @@ -348,6 +351,13 @@ def _create_llm(args: argparse.Namespace, backend_kwargs: Dict[str, Any]) -> Any if not model: _fail("a model is required (pass --model/-m).") backend = _normalize_backend(getattr(args, "backend", None)) + log = None + if getattr(args, "conversation_log", None): + from .conversation_log import DEFAULT_LOG_PATH, ConversationLog + + log = ConversationLog( + DEFAULT_LOG_PATH if args.conversation_log == "default" else args.conversation_log + ) try: return LLM( model_path=model, @@ -355,6 +365,7 @@ def _create_llm(args: argparse.Namespace, backend_kwargs: Dict[str, Any]) -> Any temperature=getattr(args, "temperature", 0.7), max_new_tokens=getattr(args, "max_tokens", 512) or 512, backend_kwargs=backend_kwargs, + **({"conversation_log": log} if log is not None else {}), ) except ImportError as exc: missing = str(exc) @@ -451,27 +462,7 @@ def _chat_once( # but third-party-compatible signatures may not). kwargs = {k: v for k, v in kwargs.items() if v is not None or k == "messages"} - try: - return llm.chat(**kwargs) - except TypeError: - # Last-resort legacy fallback for unfamiliar signatures. - fallback: Dict[str, Any] = { - "messages": messages, - "stream": stream, - } - if functions is not None: - fallback["functions"] = functions - elif tools is not None: - fallback["functions"] = [t["function"] for t in tools] - if tool_choice is not None: - fallback["function_call"] = _tool_choice_to_function_call(tool_choice) - if legacy_format is not None: - fallback["format"] = legacy_format - if temperature is not None: - fallback["temperature"] = temperature - if max_tokens is not None: - fallback["max_tokens"] = max_tokens - return llm.chat(**fallback) + return llm.chat(**kwargs) def _complete_once( @@ -566,8 +557,8 @@ def _add_common_llm_args(parser: argparse.ArgumentParser, *, require_model: bool "-b", choices=BACKEND_CHOICES, default=None, - help="Local backend or server preset (including airllm, sglang, vllm, " - "lmstudio, localai, llama-server). Default: auto-detect.", + help="Local backend or server preset (including apple-fm, apfel, airllm, " + "sglang, vllm, lmstudio, localai, llama-server). Default: auto-detect.", ) parser.add_argument( "--temperature", @@ -611,6 +602,132 @@ def _add_common_backend_tuning(parser: argparse.ArgumentParser) -> None: ) +def _add_mcp_connection_args(parser: argparse.ArgumentParser) -> None: + """Shared connection flags for ``mcp`` subcommands.""" + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument( + "--command", + dest="mcp_command", + default=None, + metavar="CMD", + help="Start a local server over stdio, e.g. " + "'npx -y @modelcontextprotocol/server-filesystem /tmp'.", + ) + group.add_argument( + "--url", + dest="mcp_url", + default=None, + metavar="URL", + help="Connect to a Streamable HTTP endpoint, e.g. 'http://localhost:3001/mcp'.", + ) + parser.add_argument( + "--name", + default=None, + help="Server name (defaults to a name derived from the command/URL).", + ) + parser.add_argument( + "--header", + dest="mcp_headers", + action="append", + default=None, + metavar="K:V", + help="Extra HTTP header for --url servers (repeatable).", + ) + parser.add_argument( + "--timeout", + type=float, + default=30.0, + help="Per-request timeout in seconds (default: 30).", + ) + + +def _split_mcp_command(command: str) -> Tuple[str, List[str]]: + """Split a full command string into (executable, args) via shlex.""" + try: + parts = shlex.split(command, posix=(os.name != "nt")) + except ValueError as exc: + _fail("could not parse MCP command {0!r}: {1}".format(command, exc)) + if not parts: + _fail("MCP command is empty.") + return parts[0], parts[1:] + + +def _derive_mcp_name(command: Optional[str], url: Optional[str], index: int) -> str: + """A readable, unique-ish server name from a command or URL.""" + if url: + host = url.split("//", 1)[-1].split("/", 1)[0].split(":", 1)[0] + return "{0}-{1}".format(host or "http", index) + if command: + first = command.split()[0] if command.split() else "mcp" + stem = os.path.splitext(os.path.basename(first))[0] or "mcp" + return "{0}-{1}".format(stem, index) + return "mcp-{0}".format(index) + + +def _parse_headers(pairs: Optional[List[str]]) -> Optional[Dict[str, str]]: + """Parse ``--header K:V`` values into a dict.""" + if not pairs: + return None + headers: Dict[str, str] = {} + for pair in pairs: + if ":" not in pair: + _fail("invalid --header {0!r}; expected 'Name: value'.".format(pair)) + key, _, value = pair.partition(":") + key = key.strip() + if not key: + _fail("invalid --header {0!r}; empty name.".format(pair)) + headers[key] = value.strip() + return headers + + +def _build_mcp_servers_from_args(args: argparse.Namespace) -> List[Any]: + """Build (but do not open) MCPServer objects from chat/generic args.""" + from .mcp import MCPServer + + servers: List[Any] = [] + for i, raw in enumerate(getattr(args, "mcp_command", None) or [], start=1): + command, extra = _split_mcp_command(raw) + servers.append( + MCPServer( + getattr(args, "name", None) or _derive_mcp_name(raw, None, i), + command=command, + args=extra, + timeout=getattr(args, "timeout", 30.0) or 30.0, + ) + ) + for i, raw_url in enumerate(getattr(args, "mcp_url", None) or [], start=1): + servers.append( + MCPServer( + getattr(args, "name", None) or _derive_mcp_name(None, raw_url, i), + url=raw_url, + headers=_parse_headers(getattr(args, "mcp_headers", None)), + timeout=getattr(args, "timeout", 30.0) or 30.0, + ) + ) + return servers + + +def _register_mcp_on_llm(llm: Any, args: argparse.Namespace) -> List[str]: + """Connect MCP servers from CLI args and register their tools on *llm*.""" + servers = _build_mcp_servers_from_args(args) + registered: List[str] = [] + for server in servers: + try: + names = llm.add_mcp_server(server) + except Exception as exc: # noqa: BLE001 - report, don't crash the REPL + _eprint( + "Warning: MCP server {0!r} unavailable ({1}); skipping.".format(server.name, exc) + ) + continue + _eprint( + "MCP: {0} -> {1} tool(s)".format(server.name, len(names)) + if names + else "MCP: {0} advertised no tools".format(server.name) + ) + registered.extend(names) + return registered + + def build_parser() -> argparse.ArgumentParser: """Build the top-level argument parser (split out for testability).""" parser = argparse.ArgumentParser( @@ -641,6 +758,14 @@ def build_parser() -> argparse.ArgumentParser: chat_p = sub.add_parser("chat", help="Interactive chat with a model.") _add_common_llm_args(chat_p, require_model=True) _add_common_backend_tuning(chat_p) + chat_p.add_argument( + "--conversation-log", + nargs="?", + const="default", + default=None, + metavar="DB", + help="Opt in to SQLite chat logging; optionally choose a database path.", + ) chat_p.add_argument("--system", "-s", default=None, help="System message.") chat_p.add_argument( "--message", @@ -687,6 +812,25 @@ def build_parser() -> argparse.ArgumentParser: help="Path to a JSON file with OpenAI-style tool definitions. " "May be given multiple times.", ) + chat_p.add_argument( + "--mcp-command", + dest="mcp_command", + action="append", + default=None, + metavar="CMD", + help="Connect a local MCP server over stdio and register its tools. " + "Give the full command, e.g. 'npx -y @modelcontextprotocol/server-filesystem /tmp'. " + "May be given multiple times.", + ) + chat_p.add_argument( + "--mcp-url", + dest="mcp_url", + action="append", + default=None, + metavar="URL", + help="Connect a remote MCP server over Streamable HTTP and register " + "its tools. May be given multiple times.", + ) chat_p.add_argument( "--function-call", default=None, @@ -846,12 +990,116 @@ def build_parser() -> argparse.ArgumentParser: help="Read input texts from a file (one per non-empty line), " "or '-' for stdin.", ) - return parser + # -- doctor ---------------------------------------------------------- + doctor_p = sub.add_parser( + "doctor", + aliases=["discover", "probe"], + help="Find running local LLM servers and report what they can do.", + description=( + "Probe the well-known local LLM endpoints (Ollama, LM Studio, " + "llama.cpp, vLLM, LocalAI, Jan, GPT4All, MLX-LM, KoboldCpp, ...), " + "read each server's own capability metadata, and report which " + "models are genuinely on-device." + ), + ) + doctor_p.add_argument( + "--url", + dest="urls", + action="append", + default=None, + metavar="BASE_URL", + help="Extra endpoint to probe, e.g. --url localhost:9000. Repeatable.", + ) + doctor_p.add_argument( + "--timeout", + type=float, + default=None, + help="Per-request timeout in seconds (default: 0.75).", + ) + doctor_p.add_argument( + "--json", + dest="json", + action="store_true", + default=False, + help="Emit the full report as JSON (machine-readable, includes failures).", + ) + doctor_p.add_argument( + "--require-local", + dest="require_local", + action="store_true", + default=False, + help="Exit non-zero unless a server with only on-device models is found.", + ) + doctor_p.add_argument( + "--keep-loading", + dest="keep_loading", + action="store_true", + default=False, + help="Wait and report servers that are still loading a model " + "(a 5xx answer instead of a refused connection).", + ) + doctor_p.add_argument( + "--quiet", + "-q", + action="store_true", + default=False, + help="Print nothing; use the exit code (0 = found).", + ) + # -- mcp ------------------------------------------------------------- + mcp_p = sub.add_parser( + "mcp", + help="Inspect and call tools from Model Context Protocol (MCP) servers.", + ) + mcp_sub = mcp_p.add_subparsers(dest="mcp_action", metavar="ACTION") -# --------------------------------------------------------------------------- -# Command handlers -# --------------------------------------------------------------------------- + mcp_tools_p = mcp_sub.add_parser( + "tools", help="List the tools a server advertises (OpenAI tool specs)." + ) + _add_mcp_connection_args(mcp_tools_p) + mcp_tools_p.add_argument( + "--json", + dest="json", + action="store_true", + default=False, + help="Emit OpenAI-style tool specs as JSON instead of a table.", + ) + + mcp_call_p = mcp_sub.add_parser("call", help="Call a single tool on a server.") + _add_mcp_connection_args(mcp_call_p) + mcp_call_p.add_argument("--tool", required=True, help="Tool name to call (as advertised).") + mcp_call_p.add_argument( + "--args", + default=None, + help="Tool arguments: inline JSON object or a path to a JSON file.", + ) + + logs = sub.add_parser("logs", help="List, inspect or export saved conversations.") + logs_sub = logs.add_subparsers(dest="logs_action", required=True) + for action in ("list", "show", "export"): + command = logs_sub.add_parser(action) + command.add_argument("--db", default=None, help="SQLite database path.") + if action == "list": + command.add_argument("--limit", type=int, default=20) + else: + command.add_argument("id", help="Conversation ID.") + command.add_argument( + "--format", + choices=["json", "text", "openai"], + default="text" if action == "show" else "json", + ) + hardware = sub.add_parser( + "hardware", help="Inspect available memory and estimate a model budget." + ) + hardware.add_argument( + "--params-b", type=float, default=None, help="Parameter count in billions." + ) + hardware.add_argument("--context-length", type=int, default=4096) + hardware.add_argument( + "--memory-gb", type=float, default=None, help="Override measured available memory in GiB." + ) + + return parser def handle_chat_command( @@ -873,41 +1121,33 @@ def handle_chat_command( llm = _create_llm(args, backend_kwargs) - messages: List[Dict[str, Any]] = [] - if getattr(args, "system", None): - messages.append({"role": "system", "content": args.system}) - - stream = bool(getattr(args, "stream", False)) - temperature = getattr(args, "temperature", 0.7) - max_tokens = getattr(args, "max_tokens", 512) - logprobs = bool(getattr(args, "logprobs", False)) - - def _run_once() -> Dict[str, Any]: - result = _chat_once( - llm, - messages, - functions=functions, - tools=tools, - tool_choice=tool_choice, - legacy_format=legacy_format, - modern_format=modern_format, - temperature=temperature, - max_tokens=max_tokens, - stream=False, - execute_tools=execute_tools, - logprobs=logprobs, - ) - if not isinstance(result, dict) or not result.get("choices"): - _fail("backend returned an unexpected response: {0!r}".format(result)) - return result - - # -- one-shot mode ---------------------------------------------------- - if getattr(args, "message", None): - messages.append({"role": "user", "content": args.message}) - if stream: - print("Assistant: ", end="", flush=True) - acc = "" - chunks = _chat_once( + try: + # Register tools from any MCP servers requested on the command line. + mcp_names: List[str] = [] + if getattr(args, "mcp_command", None) or getattr(args, "mcp_url", None): + mcp_names = _register_mcp_on_llm(llm, args) + if mcp_names: + spec_by_name = {s["function"]["name"]: s for s in llm.list_tools()} + tools = list(tools or []) + [ + spec_by_name[name] for name in mcp_names if name in spec_by_name + ] + if tool_choice is None: + tool_choice = "auto" + # Live MCP tools are meant to run; enable the executor unless the + # user explicitly passed tools that cannot be executed (schemas only). + execute_tools = True + + messages: List[Dict[str, Any]] = [] + if getattr(args, "system", None): + messages.append({"role": "system", "content": args.system}) + + stream = bool(getattr(args, "stream", False)) + temperature = getattr(args, "temperature", 0.7) + max_tokens = getattr(args, "max_tokens", 512) + logprobs = bool(getattr(args, "logprobs", False)) + + def _run_once() -> Dict[str, Any]: + result = _chat_once( llm, messages, functions=functions, @@ -917,61 +1157,20 @@ def _run_once() -> Dict[str, Any]: modern_format=modern_format, temperature=temperature, max_tokens=max_tokens, - stream=True, + stream=False, execute_tools=execute_tools, logprobs=logprobs, ) - try: - for chunk in chunks: - piece = _extract_delta_text(chunk) - if piece: - print(piece, end="", flush=True) - acc += piece - except ImportError as exc: - _fail("streaming needs no extra deps, but the backend failed: {0}".format(exc)) - print() - messages.append({"role": "assistant", "content": acc}) - return - response = _run_once() - assistant = response["choices"][0]["message"] - messages.append(assistant) - if not _print_tool_calls_from_message(assistant): - print(assistant.get("content")) - if execute_tools and ("tool_calls" in assistant or "function_call" in assistant): - _eprint( - "Note: --execute-tools was given, but tools loaded from JSON " - "files provide schemas only, so there is nothing local to run. " - "Register Python implementations via llm.add_tool() to enable " - "in-process execution." - ) - return - - # -- interactive REPL --------------------------------------------------- - print( - "Chat with {0} (type 'exit' or 'quit' to end, 'clear' to reset history)".format(args.model) - ) - try: - while True: - try: - user_input = input("\nYou: ") - except EOFError: - print() - break - if user_input.strip().lower() in ("exit", "quit"): - break - if user_input.strip().lower() == "clear": - messages = [] - if getattr(args, "system", None): - messages.append({"role": "system", "content": args.system}) - print("Chat history cleared.") - continue - if not user_input.strip(): - continue - messages.append({"role": "user", "content": user_input}) + if not isinstance(result, dict) or not result.get("choices"): + _fail("backend returned an unexpected response: {0!r}".format(result)) + return result + # -- one-shot mode ---------------------------------------------------- + if getattr(args, "message", None): + messages.append({"role": "user", "content": args.message}) if stream: - print("\nAssistant: ", end="", flush=True) - acc_text = "" + print("Assistant: ", end="", flush=True) + acc = "" chunks = _chat_once( llm, messages, @@ -991,16 +1190,55 @@ def _run_once() -> Dict[str, Any]: piece = _extract_delta_text(chunk) if piece: print(piece, end="", flush=True) - acc_text += piece - except Exception as exc: # noqa: BLE001 - print("\nError during streaming: {0}".format(exc)) - messages.pop() - continue + acc += piece + except ImportError as exc: + _fail("streaming needs no extra deps, but the backend failed: {0}".format(exc)) print() - messages.append({"role": "assistant", "content": acc_text}) - else: + messages.append({"role": "assistant", "content": acc}) + return + response = _run_once() + assistant = response["choices"][0]["message"] + messages.append(assistant) + if not _print_tool_calls_from_message(assistant): + print(assistant.get("content")) + if execute_tools and ("tool_calls" in assistant or "function_call" in assistant): + _eprint( + "Note: --execute-tools was given, but tools loaded from JSON " + "files provide schemas only, so there is nothing local to run. " + "Register Python implementations via llm.add_tool() to enable " + "in-process execution." + ) + return + + # -- interactive REPL --------------------------------------------------- + print( + "Chat with {0} (type 'exit' or 'quit' to end, 'clear' to reset history)".format( + args.model + ) + ) + try: + while True: try: - response = _chat_once( + user_input = input("\nYou: ") + except EOFError: + print() + break + if user_input.strip().lower() in ("exit", "quit"): + break + if user_input.strip().lower() == "clear": + messages = [] + if getattr(args, "system", None): + messages.append({"role": "system", "content": args.system}) + print("Chat history cleared.") + continue + if not user_input.strip(): + continue + messages.append({"role": "user", "content": user_input}) + + if stream: + print("\nAssistant: ", end="", flush=True) + acc_text = "" + chunks = _chat_once( llm, messages, functions=functions, @@ -1010,21 +1248,56 @@ def _run_once() -> Dict[str, Any]: modern_format=modern_format, temperature=temperature, max_tokens=max_tokens, - stream=False, + stream=True, execute_tools=execute_tools, logprobs=logprobs, ) - except Exception as exc: # noqa: BLE001 - print("\nError: {0}".format(exc)) - messages.pop() - continue - if "choices" in response and response["choices"]: - assistant_msg = response["choices"][0]["message"] - messages.append(assistant_msg) - if not _print_tool_calls_from_message(assistant_msg): - print("\nAssistant: {0}".format(assistant_msg.get("content"))) - except KeyboardInterrupt: - print("\nExiting chat...") + try: + for chunk in chunks: + piece = _extract_delta_text(chunk) + if piece: + print(piece, end="", flush=True) + acc_text += piece + except Exception as exc: # noqa: BLE001 + print("\nError during streaming: {0}".format(exc)) + messages.pop() + continue + print() + messages.append({"role": "assistant", "content": acc_text}) + else: + try: + response = _chat_once( + llm, + messages, + functions=functions, + tools=tools, + tool_choice=tool_choice, + legacy_format=legacy_format, + modern_format=modern_format, + temperature=temperature, + max_tokens=max_tokens, + stream=False, + execute_tools=execute_tools, + logprobs=logprobs, + ) + except Exception as exc: # noqa: BLE001 + print("\nError: {0}".format(exc)) + messages.pop() + continue + if "choices" in response and response["choices"]: + assistant_msg = response["choices"][0]["message"] + messages.append(assistant_msg) + if not _print_tool_calls_from_message(assistant_msg): + print("\nAssistant: {0}".format(assistant_msg.get("content"))) + except KeyboardInterrupt: + print("\nExiting chat...") + finally: + close = getattr(llm, "close", None) + if callable(close): + close() + log = getattr(llm, "conversation_log", None) + if log is not None: + log.close() def handle_completion_command( @@ -1495,11 +1768,242 @@ def handle_embed_command(args: argparse.Namespace) -> None: print(json.dumps(payload)) +# --------------------------------------------------------------------------- +# doctor +# --------------------------------------------------------------------------- + + +def _describe_model(model: Any) -> str: + """One-line capability summary for a discovered model.""" + bits = [] + if model.context_length: + bits.append("ctx %d" % model.context_length) + if model.capabilities: + bits.append(", ".join(model.capabilities)) + return " ".join(bits) if bits else "capabilities unknown" + + +def _render_doctor(report: Any, require_local: bool) -> None: + """Print a human-readable discovery report.""" + print( + "Probed %d local endpoints in %sms; %d responded." + % (report.probed, report.elapsed_ms, len(report.live)) + ) + + if report.live: + print("\nLive servers:") + width = max(len(s.base_url) for s in report.servers) + for server in report.live: + count = len(server.models) + status = "%d model%s" % (count, "" if count == 1 else "s") + if server.loading: + status = "loading a model" + print( + " ok %-*s %-10s %7sms %s" + % ( + width, + server.base_url, + server.provider, + server.latency_ms, + status, + ) + ) + else: + print("\nNo local LLM server responded.") + + for server in report.live: + print("\n%s (%s)" % (server.provider, server.base_url)) + if server.context_window: + print(" server context window: %d tokens" % server.context_window) + if server.vision is not None: + print(" server vision support: %s" % ("yes" if server.vision else "no")) + for model in server.models: + marker = ( + " OFF-DEVICE -> %s" % (model.remote_host or "remote") + if model.remote + else ("" if model.local_verified else " locality unknown") + ) + print(" %-38s %s%s" % (model.id[:38], _describe_model(model), marker)) + for note in server.notes: + print(" note: %s" % note) + + offline = [s for s in report.offline if s.status is not None] + if offline: + print("\nReachable but not ready:") + for server in offline: + print(" %-*s %s" % (28, server.base_url, server.error)) + if not report.live and not offline: + tried = ", ".join( + sorted({s.base_url.split("//")[-1].split("/")[0] for s in report.offline}) + ) + print("\nNothing was listening on: %s" % tried) + + on_device = report.on_device() + if require_local and not on_device: + print( + "\nNo server offering an on-device model was found." + "\n Start one (for example `ollama serve`) and pull a local model" + "\n (`ollama pull qwen2.5:0.5b`), or re-run without --require-local." + ) + elif on_device: + first = on_device[0] + model = first.local_models[0] if first.local_models else None + print("\nReady to use (on-device):") + if model is not None: + print(' LLM("%s", backend="%s")' % (model.id, first.provider)) + else: + print(' LLM(, backend="%s")' % first.provider) + elif report.live: + print( + "\nServers are up; no model has verified on-device execution metadata." + "\n Inspect the server's native model/routing metadata before requiring locality." + ) + + +def handle_doctor_command(args: argparse.Namespace) -> int: + """Handle `doctor`: report running local LLM servers and their capabilities.""" + try: + from .discovery import DEFAULT_TIMEOUT, discover + except ImportError as exc: # pragma: no cover - packaging error + _fail("the discovery module is unavailable ({0}).".format(exc)) + + timeout = getattr(args, "timeout", None) or DEFAULT_TIMEOUT + try: + report = discover(extra_urls=getattr(args, "urls", None), timeout=float(timeout)) + except ValueError as exc: + _fail(str(exc)) + + require_local = bool(getattr(args, "require_local", False)) + if getattr(args, "keep_loading", False): + for server in report.offline: + if server.status is not None and server.status >= 500: + server.loading = True + + if bool(getattr(args, "json", False)): + print(json.dumps(report.to_dict(), indent=2)) + elif not getattr(args, "quiet", False): + _render_doctor(report, require_local) + + if require_local: + return 0 if report.on_device() else 1 + return 0 if report.live else 1 + + # --------------------------------------------------------------------------- # Entrypoint # --------------------------------------------------------------------------- +def _print_mcp_tools(server: Any, tools: List[Any]) -> None: + """Human-readable table of a server's tools.""" + from .mcp import sanitize_tool_name + + print("Server: {0} ({1})".format(server.name, server.transport_kind)) + if not tools: + print(" (no tools advertised)") + return + for tool in tools: + summary = (tool.description or "").strip().splitlines() + first_line = summary[0] if summary else "" + print(" - {0}: {1}".format(sanitize_tool_name(tool.name), first_line)) + params = (tool.input_schema or {}).get("properties") or {} + required = set((tool.input_schema or {}).get("required") or []) + for pname, meta in params.items(): + ptype = (meta or {}).get("type", "any") if isinstance(meta, dict) else "any" + flag = " (required)" if pname in required else "" + print(" {0}: {1}{2}".format(pname, ptype, flag)) + + +def handle_mcp_command(args: argparse.Namespace) -> None: + """Handle ``mcp tools`` and ``mcp call`` subcommands.""" + action = getattr(args, "mcp_action", None) + if action not in ("tools", "call"): + _fail("mcp requires an action: 'tools' or 'call'.") + + from .mcp import MCPServer + + command = getattr(args, "mcp_command", None) + url = getattr(args, "mcp_url", None) + name = getattr(args, "name", None) + try: + if command: + exe, extra = _split_mcp_command(command) + server = MCPServer( + name or _derive_mcp_name(command, None, 1), + command=exe, + args=extra, + timeout=getattr(args, "timeout", 30.0) or 30.0, + ) + else: + server = MCPServer( + name or _derive_mcp_name(None, url, 1), + url=url, + headers=_parse_headers(getattr(args, "mcp_headers", None)), + timeout=getattr(args, "timeout", 30.0) or 30.0, + ) + except ValueError as exc: + _fail("invalid MCP server configuration: {0}".format(exc)) + + try: + server.open() + except Exception as exc: # noqa: BLE001 - surface a clean CLI error + _fail("could not connect to MCP server: {0}".format(exc)) + + try: + if action == "tools": + tools = server.list_tools() + if getattr(args, "json", False): + print(json.dumps(server.to_openai_tools(), indent=2)) + else: + _print_mcp_tools(server, tools) + return + raw_args = getattr(args, "args", None) + parsed = _load_json_value_or_file(raw_args, "--args") if raw_args else {} + if parsed is None: + parsed = {} + if not isinstance(parsed, dict): + _fail("--args must be a JSON object.") + try: + output = server.call_tool(args.tool, parsed) + except Exception as exc: # noqa: BLE001 - tool errors are reported, not raised + _fail("tool {0!r} failed: {1}".format(args.tool, exc)) + print(output) + finally: + server.close() + + +def handle_logs_command(args: argparse.Namespace) -> None: + from .conversation_log import DEFAULT_LOG_PATH, ConversationLog + + path = args.db or DEFAULT_LOG_PATH + if not os.path.isfile(path): + _fail("Conversation database does not exist: %s" % path) + try: + with ConversationLog(path) as log: + if args.logs_action == "list": + if args.limit < 1: + raise ValueError("--limit must be positive.") + print(json.dumps(log.get_conversations(args.limit), indent=2)) + else: + print(log.export_conversation(args.id, args.format)) + except (KeyError, ValueError, OSError) as exc: + _fail(str(exc)) + + +def handle_hardware_command(args: argparse.Namespace) -> None: + from .hardware import get_system_memory, recommend_quantization + + try: + result = get_system_memory() + if args.params_b is not None: + result["recommendation"] = recommend_quantization( + args.params_b, args.memory_gb, args.context_length + ) + print(json.dumps(result, indent=2)) + except ValueError as exc: + _fail(str(exc)) + + def main(argv: Optional[List[str]] = None) -> int: """Main CLI entrypoint. Returns a process exit code.""" parser = build_parser() @@ -1527,6 +2031,14 @@ def main(argv: Optional[List[str]] = None) -> int: handle_list_command(args) elif command == "embed": handle_embed_command(args) + elif command in ("doctor", "discover", "probe"): + return handle_doctor_command(args) + elif command == "mcp": + handle_mcp_command(args) + elif command == "logs": + handle_logs_command(args) + elif command == "hardware": + handle_hardware_command(args) else: parser.print_help() return 1 diff --git a/local_llm_kit/conversation_log.py b/local_llm_kit/conversation_log.py new file mode 100644 index 0000000..c30b31c --- /dev/null +++ b/local_llm_kit/conversation_log.py @@ -0,0 +1,631 @@ +"""Opt-in SQLite conversation history with atomic writes and lossless message export. + +One locked connection works across threads, including an in-memory database. +Nothing is written until a ConversationLog is explicitly constructed. +""" + +import json +import os +import threading +import uuid +from functools import wraps +from typing import Any, Dict, List, Optional + +__all__ = ["ConversationLog", "DEFAULT_LOG_PATH", "get_conversation_log"] + + +def _locked(method): + @wraps(method) + def call(self, *args, **kwargs): + with self._lock: + return method(self, *args, **kwargs) + + return call + + +def _atomic(method): + @wraps(method) + def call(self, *args, **kwargs): + with self._lock, self._conn: + self._batch = True + try: + return method(self, *args, **kwargs) + finally: + self._batch = False + + return call + + +# --------------------------------------------------------------------------- +# Default on-disk path (XDG_DATA_HOME or ~/.local/share/local-llm-kit/) +# --------------------------------------------------------------------------- + + +def _default_log_path() -> str: + """Resolve the default SQLite log path (XDG_DATA_HOME or platform default).""" + xdg = os.environ.get("XDG_DATA_HOME") + if xdg: + return os.path.join(xdg, "local-llm-kit", "conversation_logs.db") + return os.path.join( + os.path.expanduser("~"), + ".local", + "share", + "local-llm-kit", + "conversation_logs.db", + ) + + +DEFAULT_LOG_PATH = _default_log_path() + + +def _ensure_parent_dir(path: str) -> None: + """Create the parent directory of *path* if it does not exist.""" + parent = os.path.dirname(path) + if parent and not os.path.isdir(parent): + os.makedirs(parent, exist_ok=True) + + +def _now_ts() -> int: + import time + + return int(time.time()) + + +# --------------------------------------------------------------------------- +# SQLite schema +# --------------------------------------------------------------------------- + +_SCHEMA = """ +CREATE TABLE IF NOT EXISTS conversations ( + id TEXT PRIMARY KEY, + created_at INTEGER NOT NULL, + model TEXT, + system_prompt TEXT, + metadata TEXT +); + +CREATE TABLE IF NOT EXISTS messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + conversation_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + role TEXT NOT NULL, + content TEXT, + model TEXT, + finish_reason TEXT, + prompt_tokens INTEGER, + completion_tokens INTEGER, + payload TEXT, + FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS tool_calls ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + message_id INTEGER NOT NULL, + name TEXT NOT NULL, + arguments TEXT NOT NULL, + result TEXT, + call_id TEXT, + FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE +); +""" + + +# --------------------------------------------------------------------------- +# ConversationLog +# --------------------------------------------------------------------------- + + +class ConversationLog: + """SQLite-backed persistent log of LLM conversations. + + Stores conversations, their messages (user / assistant / tool / system), + and any tool-call records produced during a turn. Connections are + serialized with a reentrant lock, including complete interaction transactions. + + :param path: filesystem path to the SQLite database file. When + ``None`` the default XDG/standard-path location is used + (see :data:`DEFAULT_LOG_PATH`). + """ + + def __init__(self, path: Optional[str] = None) -> None: + import sqlite3 + + self._path = str(path) if path is not None else DEFAULT_LOG_PATH + self._lock = threading.RLock() + self._batch = False + _ensure_parent_dir(self._path) + self._conn = sqlite3.connect(self._path, check_same_thread=False, timeout=30.0) + self._conn.row_factory = sqlite3.Row + self._conn.execute("PRAGMA foreign_keys = ON") + with self._conn: + self._conn.executescript(_SCHEMA) + # Preserve databases made by the original prototype. + for table, column in (("messages", "payload"), ("tool_calls", "call_id")): + columns = {row[1] for row in self._conn.execute("PRAGMA table_info(%s)" % table)} + if column not in columns: + self._conn.execute("ALTER TABLE %s ADD COLUMN %s TEXT" % (table, column)) + + @_locked + def close(self) -> None: + """Close the store; it cannot be used again after closing.""" + self._conn.close() + + def __enter__(self) -> "ConversationLog": + return self + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + self.close() + + def _execute( + self, + query: str, + params: Optional[tuple] = None, + commit: bool = False, + ) -> Any: + """Execute a statement while the caller holds the connection lock.""" + conn = self._conn + cur = conn.execute(query, params or ()) + if commit and not self._batch: + conn.commit() + return cur + + # -- CRUD ----------------------------------------------------------------- + + @_locked + def create( + self, + model: Optional[str] = None, + system_prompt: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + ) -> str: + """Create a new conversation and return its ID.""" + conv_id = uuid.uuid4().hex + ts = _now_ts() + meta_json = json.dumps(metadata) if metadata is not None else None + self._execute( + "INSERT INTO conversations (id, created_at, model, system_prompt, metadata) " + "VALUES (?, ?, ?, ?, ?)", + (conv_id, ts, model, system_prompt, meta_json), + commit=True, + ) + return conv_id + + @_locked + def add_message( + self, + conv_id: str, + role: str, + content: Optional[str], + model: Optional[str] = None, + finish_reason: Optional[str] = None, + prompt_tokens: Optional[int] = None, + completion_tokens: Optional[int] = None, + payload: Optional[Dict[str, Any]] = None, + ) -> int: + """Append a message to *conv_id* and return the new message row id.""" + ts = _now_ts() + cur = self._execute( + "INSERT INTO messages " + "(conversation_id, created_at, role, content, model, finish_reason, " + " prompt_tokens, completion_tokens, payload) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + ( + conv_id, + ts, + role, + content, + model, + finish_reason, + prompt_tokens, + completion_tokens, + json.dumps(payload) if payload is not None else None, + ), + commit=True, + ) + return int(cur.lastrowid) + + @_locked + def add_tool_call( + self, + message_id: int, + name: str, + arguments: Any, + result: Optional[str] = None, + call_id: Optional[str] = None, + ) -> int: + """Record a tool call associated with *message_id*. + + *arguments* may be a ``dict`` (JSON-serialised automatically) or a + JSON string. Returns the new tool-call row id. + """ + if isinstance(arguments, dict): + args_json = json.dumps(arguments) + elif isinstance(arguments, str): + args_json = arguments + else: + args_json = json.dumps(arguments) + cur = self._execute( + "INSERT INTO tool_calls (message_id, name, arguments, result, call_id) VALUES (?, ?, ?, ?, ?)", + (message_id, name, args_json, result, call_id), + commit=True, + ) + return int(cur.lastrowid) + + @_locked + def get_conversations(self, limit: int = 100) -> List[Dict[str, Any]]: + """Return the most recent conversations (newest first).""" + conn = self._conn + rows = conn.execute( + "SELECT id, created_at, model, system_prompt, metadata " + "FROM conversations ORDER BY created_at DESC LIMIT ?", + (limit,), + ).fetchall() + return [_row_to_conv(row) for row in rows] + + @_locked + def get_conversation(self, conv_id: str) -> Dict[str, Any]: + """Return a single conversation's metadata (raises ``KeyError`` if absent).""" + conn = self._conn + row = conn.execute( + "SELECT id, created_at, model, system_prompt, metadata " + "FROM conversations WHERE id = ?", + (conv_id,), + ).fetchone() + if row is None: + raise KeyError("Conversation not found: %s" % conv_id) + return _row_to_conv(row) + + @_locked + def get_messages(self, conv_id: str) -> List[Dict[str, Any]]: + """Return all messages for *conv_id* in insertion order.""" + conn = self._conn + rows = conn.execute( + "SELECT id, conversation_id, created_at, role, content, model, " + "finish_reason, prompt_tokens, completion_tokens, payload " + "FROM messages WHERE conversation_id = ? ORDER BY id ASC", + (conv_id,), + ).fetchall() + return [_row_to_message(row) for row in rows] + + @_locked + def get_tool_calls(self, message_id: int) -> List[Dict[str, Any]]: + """Return tool-call records associated with *message_id*.""" + conn = self._conn + rows = conn.execute( + "SELECT id, message_id, name, arguments, result, call_id " + "FROM tool_calls WHERE message_id = ? ORDER BY id ASC", + (message_id,), + ).fetchall() + return [_row_to_tool_call(row) for row in rows] + + @_locked + def search(self, query: str, limit: int = 20) -> List[Dict[str, Any]]: + """Full-message search (LIKE) across all conversations. + + Returns matching message dicts enriched with the parent + conversation's ``model``. + """ + pattern = "%%%s%%" % query + conn = self._conn + rows = conn.execute( + "SELECT m.id, m.conversation_id, m.created_at, m.role, m.content, " + " m.model, m.finish_reason, m.prompt_tokens, m.completion_tokens, m.payload " + "FROM messages m " + "WHERE m.content LIKE ? " + "ORDER BY m.created_at DESC LIMIT ?", + (pattern, limit), + ).fetchall() + return [_row_to_message(row) for row in rows] + + @_locked + def delete(self, conv_id: str) -> int: + """Delete a conversation and all of its messages/tool calls. + + Returns the number of conversations removed (0 or 1). + """ + cur = self._execute( + "DELETE FROM conversations WHERE id = ?", + (conv_id,), + commit=True, + ) + return cur.rowcount + + @_locked + def clear(self) -> None: + """Delete *all* conversations, messages, and tool calls.""" + self._execute("DELETE FROM conversations", commit=True) + + # -- High-level convenience API ------------------------------------------ + + @_atomic + def log_interaction( + self, + model: str, + messages: List[Dict[str, Any]], + response: Any, + tools_used: Optional[List[Dict[str, Any]]] = None, + metadata: Optional[Dict[str, Any]] = None, + conversation_id: Optional[str] = None, + system_prompt: Optional[str] = None, + ) -> str: + """Atomically append supplied messages and a response. + + With an existing ID, supply only new messages or a complete history + beginning with previously stored messages; that prefix is deduplicated. + Full message payloads preserve images, tool IDs and reasoning fields. + """ + if conversation_id is None: + conversation_id = self.create(model, system_prompt, metadata) + else: + self.get_conversation(conversation_id) + if metadata is not None: + self._update_conversation_metadata(conversation_id, metadata) + if not isinstance(messages, list) or any(not isinstance(msg, dict) for msg in messages): + raise TypeError("messages must be a list of message objects.") + previous = [row["payload"] for row in self.get_messages(conversation_id)] + if previous and messages[: len(previous)] == previous: + messages = messages[len(previous) :] + if isinstance(response, str): + assistant, usage, finish = {"role": "assistant", "content": response}, {}, None + elif isinstance(response, dict): + choice = (response.get("choices") or [{}])[0] + assistant = dict( + choice.get("message") or {"content": response.get("text", response.get("content"))}, + role="assistant", + ) + usage, finish = response.get("usage") or {}, choice.get("finish_reason") + else: + raise TypeError("response must be text or a chat response object.") + if tools_used: + existing = list(assistant.get("tool_calls") or []) + keys = { + call.get("id") or json.dumps(call.get("function", call), sort_keys=True) + for call in existing + } + for call in tools_used: + key = call.get("id") or json.dumps(call.get("function", call), sort_keys=True) + if key not in keys: + existing.append(call) + keys.add(key) + assistant["tool_calls"] = existing + for index, message in enumerate(messages + [assistant]): + if not isinstance(message.get("role"), str) or not message["role"]: + raise ValueError("Every message must have a non-empty role.") + final = index == len(messages) + content = message.get("content") + mid = self.add_message( + conversation_id, + message["role"], + content if isinstance(content, str) or content is None else json.dumps(content), + model=model, + finish_reason=finish if final else None, + prompt_tokens=usage.get("prompt_tokens") if final else None, + completion_tokens=usage.get("completion_tokens") if final else None, + payload=message, + ) + for call in message.get("tool_calls") or []: + function = call.get("function", call) + self.add_tool_call( + mid, + function["name"], + function.get("arguments", "{}"), + call.get("result", call.get("output")), + call.get("id"), + ) + return conversation_id + + @_locked + def get_conversation_history( + self, + conversation_id: str, + include_tool_details: bool = True, + ) -> List[Dict[str, Any]]: + """Return the full message + tool-call history for a conversation. + + Each message dict is enriched with a ``tool_calls`` key (list of + parsed tool-call records) when ``include_tool_details`` is True. + + :raises KeyError: if the conversation does not exist. + """ + self.get_conversation(conversation_id) # validate existence + messages = self.get_messages(conversation_id) + if not include_tool_details: + return messages + result: List[Dict[str, Any]] = [] + for msg in messages: + enriched = dict(msg) + enriched["tool_calls"] = self.get_tool_calls(msg["id"]) + result.append(enriched) + return result + + @_locked + def export_conversation( + self, + conversation_id: str, + format: str = "json", + ) -> str: + """Export a conversation's full history in the requested format. + + Supported formats: + + * ``"json"`` -- structured JSON (conversation + messages + tool calls). + * ``"text"`` -- human-readable transcript. + * ``"openai"`` -- flattened OpenAI-style message list suitable for + ``llm.chat(messages=...)``. + + :raises KeyError: if the conversation does not exist. + :raises ValueError: for unsupported formats. + """ + fmt = format.lower().strip() + if fmt not in ("json", "text", "openai"): + raise ValueError("Unsupported export format: {0!r}".format(format)) + + conv = self.get_conversation(conversation_id) + history = self.get_conversation_history(conversation_id) + + if fmt == "json": + return json.dumps( + { + "conversation": conv, + "history": history, + }, + indent=2, + default=str, + ) + + if fmt == "text": + lines: List[str] = [] + lines.append("=== Conversation {0} ===".format(conversation_id)) + lines.append("Model: {0}".format(conv.get("model") or "(unknown)")) + ts = conv.get("created_at") + if ts is not None: + lines.append("Created: {0}".format(ts)) + sys = conv.get("system_prompt") + if sys: + lines.append("System: {0}".format(sys)) + lines.append("") + for msg in history: + role = msg.get("role", "?") + content = msg.get("content") + if role == "assistant" and not content: + content = "(no text content)" + if content: + lines.append("{0}: {1}".format(role.capitalize(), content)) + for tc in msg.get("tool_calls", []): + args = tc.get("arguments", {}) + if isinstance(args, str): + try: + args = json.loads(args) + except (ValueError, TypeError): + pass + lines.append( + "Assistant called: {0}({1})".format( + tc.get("name"), json.dumps(args) if isinstance(args, dict) else args + ) + ) + res = tc.get("result") + if res: + lines.append(" Result: {0}".format(res)) + lines.append("") + lines.append("=== End of conversation ===") + return "\n".join(lines) + + # fmt == "openai": flatten to OpenAI-style message list + openai_msgs: List[Dict[str, Any]] = [] + for msg in history: + if msg.get("payload") is not None: + openai_msgs.append(msg["payload"]) + continue + role = msg.get("role") + entry: Dict[str, Any] = {"role": role, "content": msg.get("content")} + if role == "assistant": + tcs = msg.get("tool_calls", []) + if tcs: + openai_calls = [] + for tc in tcs: + args = tc.get("arguments", "{}") + if isinstance(args, (dict, list)): + args = json.dumps(args) + openai_calls.append( + { + "id": tc.get("call_id") or "call_{0}".format(tc.get("id", "")), + "type": "function", + "function": { + "name": tc.get("name"), + "arguments": args, + }, + } + ) + entry["tool_calls"] = openai_calls + elif role == "tool": + raise ValueError( + "Legacy tool message has no original tool_call_id; export JSON/text instead of inventing replay linkage." + ) + openai_msgs.append(entry) + return json.dumps({"model": conv.get("model"), "messages": openai_msgs}, indent=2) + + # -- internal: metadata update ------------------------------------------- + + def _update_conversation_metadata(self, conv_id: str, metadata: Dict[str, Any]) -> None: + """Update metadata JSON on an existing conversation (best-effort).""" + meta_json = json.dumps(metadata) + self._execute( + "UPDATE conversations SET metadata = ? WHERE id = ?", + (meta_json, conv_id), + commit=True, + ) + + +# --------------------------------------------------------------------------- +# Row deserializers +# --------------------------------------------------------------------------- + + +def _decode_json(value: Any) -> Any: + """Best-effort JSON decode; returns the raw value when it fails.""" + if value is None: + return None + if isinstance(value, (dict, list)): + return value + try: + return json.loads(value) + except (json.JSONDecodeError, TypeError): + return value + + +def _row_to_conv(row: Any) -> Dict[str, Any]: + return { + "id": row["id"], + "created_at": row["created_at"], + "model": row["model"], + "system_prompt": row["system_prompt"], + "metadata": _decode_json(row["metadata"]), + } + + +def _row_to_message(row: Any) -> Dict[str, Any]: + return { + "id": row["id"], + "conversation_id": row["conversation_id"], + "created_at": row["created_at"], + "role": row["role"], + "content": row["content"], + "model": row["model"], + "finish_reason": row["finish_reason"], + "prompt_tokens": row["prompt_tokens"], + "completion_tokens": row["completion_tokens"], + "payload": _decode_json(row["payload"]), + } + + +def _row_to_tool_call(row: Any) -> Dict[str, Any]: + return { + "id": row["id"], + "message_id": row["message_id"], + "name": row["name"], + "arguments": _decode_json(row["arguments"]), + "result": row["result"], + "call_id": row["call_id"], + } + + +# --------------------------------------------------------------------------- +# Module-level helper +# --------------------------------------------------------------------------- + + +def get_conversation_log(path: Optional[str] = None) -> "ConversationLog": + """Return a :class:`ConversationLog` (default path if *path* is ``None``). + + A simple process-level cache is used so repeated calls with no *path* + return the same instance, avoiding repeated schema initialization. + """ + global _DEFAULT_LOG_INSTANCE + if path is None: + if _DEFAULT_LOG_INSTANCE is None: + _DEFAULT_LOG_INSTANCE = ConversationLog(path) + return _DEFAULT_LOG_INSTANCE + return ConversationLog(path) + + +_DEFAULT_LOG_INSTANCE: Optional["ConversationLog"] = None diff --git a/local_llm_kit/discovery.py b/local_llm_kit/discovery.py new file mode 100644 index 0000000..dc95190 --- /dev/null +++ b/local_llm_kit/discovery.py @@ -0,0 +1,864 @@ +""" +Find the local LLM servers that are actually running, and report what they can do. + +The most common failure in local-AI code is not a bad model call, it is not +knowing *what* is listening *where*: which port a desktop app chose, whether the +server finished loading its model, whether the loaded model can call tools, and +whether a model is genuinely on-device or quietly routed to a remote host. + +This module answers those questions with the standard library only. It probes +every known local endpoint concurrently, reads each server's own capability +metadata where that server exposes it, and never raises: a dead port is a +result, not an exception. + +Example: + from local_llm_kit import discover + + report = discover() + for server in report.servers: + print(server.base_url, server.provider, server.latency_ms) + first = report.first_live() + +Probed endpoints come from :data:`local_llm_kit.discovery.ENDPOINTS`; pass your +own with ``discover(extra_urls=["http://localhost:9000/v1"])``. + +Nothing here performs inference, downloads weights, or sends credentials. +Probes are unauthenticated metadata reads, including POST /api/show for Ollama. +""" + +import concurrent.futures +import ipaddress +import json +import math +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Sequence, Tuple + +__all__ = [ + "ENDPOINTS", + "Endpoint", + "ModelRecord", + "ServerReport", + "DiscoveryReport", + "normalize_base_url", + "probe_endpoint", + "discover", + "find_local_server", +] + +#: Sent with probes so servers and local logs can identify the caller. +_USER_AGENT = "local-llm-kit-discovery/0.3" + +#: Default per-request timeout. Loopback probes either answer immediately or not. +DEFAULT_TIMEOUT = 0.75 + +#: Cap on how many models get per-model enrichment (a `/api/show` round trip each). +_MAX_ENRICHED_MODELS = 12 + + +@dataclass(frozen=True) +class Endpoint: + """A place a local LLM server is known to listen.""" + + provider: str + base_url: str + #: Extra base URLs that are common for this provider (probed too). + note: str = "" + + +#: Known local endpoints, most commonly used first. The order is the probe +#: order, so users who run the popular tools get answers fastest. +#: +#: Ports are the upstream defaults as of October 2026, checked against each +#: project's own source or documentation: +#: +#: * ``llama-server`` appears twice on purpose. llama.cpp changed its default +#: listen port from 8080 to 9931 in October 2026 +#: (ggml-org/llama.cpp#30159, merged 2026-10-09), while the published Docker +#: image still binds 8080 (same PR). MLX-LM also defaults to 8080, which is +#: exactly why the provider is identified from the response and not the port. +#: * ``apfel`` deliberately shares Ollama's port 11434, so both entries collapse +#: into one probe and the payload decides which server is really there. +#: * Docker Model Runner serves OpenAI compatibility under an ``/engines`` +#: prefix rather than at the root (Docker model-runner API reference). +#: * ``fm-serve`` (Apple's macOS 27 system tool) has been measured on +#: 127.0.0.1:1976 by third-party testing. It is probed because a refused +#: loopback connection costs nothing, but Apple publishes no primary +#: documentation for it and its ``/v1/models`` shape is unverified. +#: * RamaLama takes the first free port in 8080-8180, so it is only caught by +#: the 8080 probe when it happens to land there. +ENDPOINTS: Tuple[Endpoint, ...] = ( + Endpoint("ollama", "http://127.0.0.1:11434/v1"), + Endpoint("lmstudio", "http://127.0.0.1:1234/v1"), + Endpoint("llama-server", "http://127.0.0.1:9931/v1"), + Endpoint("llama-server", "http://127.0.0.1:8080/v1"), + Endpoint("vllm", "http://127.0.0.1:8000/v1"), + Endpoint("localai", "http://127.0.0.1:8080/v1"), + Endpoint("sglang", "http://127.0.0.1:30000/v1"), + Endpoint("jan", "http://127.0.0.1:1337/v1"), + Endpoint("gpt4all", "http://127.0.0.1:4891/v1"), + Endpoint("mlx-lm", "http://127.0.0.1:8080/v1"), + Endpoint("koboldcpp", "http://127.0.0.1:5001/v1"), + Endpoint("text-generation-webui", "http://127.0.0.1:5000/v1"), + Endpoint("docker-model-runner", "http://127.0.0.1:12434/engines/v1"), + Endpoint("apfel", "http://127.0.0.1:11434/v1"), + Endpoint("fm-serve", "http://127.0.0.1:1976/v1"), + Endpoint("llamafile", "http://127.0.0.1:8080/v1"), +) + +#: Provider names whose model listing carries capability metadata we can read. +#: See the module docstring: capabilities come from each server's own API. +_OLLAMA_ROOT_SUFFIXES = ("/v1", "/api") + +#: Substrings in a model id or host that indicate off-device routing. +_REMOTE_MARKERS = ("cloud",) + + +def normalize_base_url(url: str) -> str: + """Return a canonical ``scheme://host[:port]/v1`` base URL. + + Accepts what users actually paste: a bare host/port, a URL with or without + ``/v1``, or a full ``.../v1/chat/completions`` endpoint. Query strings and + fragments are dropped. + """ + if not isinstance(url, str) or not url.strip(): + raise ValueError("base_url must be a non-empty string.") + text = url.strip() + if "://" not in text: + text = "http://" + text + parts = urllib.parse.urlsplit(text) + if not parts.hostname: + raise ValueError("base_url must include a host: %r" % (url,)) + if parts.scheme not in ("http", "https"): + raise ValueError("base_url must use http or https.") + if parts.username is not None or parts.password is not None: + raise ValueError("Discovery probes do not accept credentials in URLs.") + netloc = "[%s]" % parts.hostname if ":" in parts.hostname else parts.hostname + if parts.port is not None: + netloc = "%s:%d" % (netloc, parts.port) + path = parts.path.rstrip("/") + for suffix in ("/chat/completions", "/completions", "/embeddings", "/models"): + if path.endswith(suffix): + path = path[: -len(suffix)] + break + if not path.endswith("/v1"): + path = path + "/v1" if path else "/v1" + return "%s://%s%s" % (parts.scheme or "http", netloc, path) + + +def is_loopback_url(url: str) -> bool: + """Whether an HTTP endpoint explicitly addresses this machine.""" + try: + parts = urllib.parse.urlsplit(url) + if parts.scheme not in ("http", "https"): + return False + host = parts.hostname or "" + if host.lower() == "localhost": + return True + return ipaddress.ip_address(host).is_loopback + except ValueError: + return False + + +def _server_root(base_url: str) -> str: + """Strip a trailing ``/v1`` (or ``/api``) so native API paths can be built.""" + root = base_url.rstrip("/") + for suffix in _OLLAMA_ROOT_SUFFIXES: + if root.endswith(suffix): + return root[: -len(suffix)] + return root + + +@dataclass +class ModelRecord: + """One model as reported by a server, with whatever capabilities it exposes.""" + + id: str + #: Capability names the server reported (empty when the server does not say). + capabilities: List[str] = field(default_factory=list) + #: Context length the server reported for this model, if it reported one. + context_length: Optional[int] = None + #: True when the server routes this model off-device (for example Ollama's + #: ``:cloud`` models, which run on ollama.com rather than on this machine). + remote: bool = False + #: Server-native metadata explicitly identifies local execution. + local_verified: bool = False + remote_host: Optional[str] = None + #: Raw provider payload, kept for ``--json`` output and debugging. + raw: Dict[str, Any] = field(default_factory=dict) + + def to_dict(self) -> Dict[str, Any]: + return { + "id": self.id, + "capabilities": list(self.capabilities), + "context_length": self.context_length, + "remote": self.remote, + "local_verified": self.local_verified, + "remote_host": self.remote_host, + } + + @property + def supports_tools(self) -> bool: + return any("tool" in c.lower() for c in self.capabilities) + + @property + def supports_vision(self) -> bool: + return any(c.lower() in ("vision", "image") for c in self.capabilities) + + @property + def supports_embeddings(self) -> bool: + return any("embed" in c.lower() for c in self.capabilities) + + @property + def supports_thinking(self) -> bool: + return any(c.lower() in ("thinking", "reasoning") for c in self.capabilities) + + +@dataclass +class ServerReport: + """Result of probing one endpoint. A dead endpoint is a normal result.""" + + base_url: str + provider: str + live: bool = False + status: Optional[int] = None + latency_ms: Optional[float] = None + error: Optional[str] = None + models: List[ModelRecord] = field(default_factory=list) + #: Server-wide context window when the server reports one (llama.cpp, + #: apfel and LM Studio do; Ollama reports it per model instead). + context_window: Optional[int] = None + #: Server-wide vision support when the server reports it. + vision: Optional[bool] = None + #: True when the server says it is still loading its model. + loading: bool = False + #: Human-readable notes: detection evidence, degradations, next steps. + notes: List[str] = field(default_factory=list) + + @property + def remote_models(self) -> List[ModelRecord]: + """Models on this server that would leave the machine if called.""" + return [m for m in self.models if m.remote] + + @property + def local_models(self) -> List[ModelRecord]: + if not is_loopback_url(self.base_url): + return [] + return [m for m in self.models if m.local_verified and not m.remote] + + @property + def has_local_models(self) -> bool: + """True when this live server offers at least one on-device model. + + A server may offer both kinds — Ollama happily lists downloaded models + next to ``:cloud`` ones — so this is the useful "can I run offline?" + question, whereas :attr:`all_local` is the stricter "is everything + here on-device?" question. + """ + return self.live and bool(self.local_models) + + @property + def all_local(self) -> bool: + """True when the server is live and exposes no off-device models.""" + return self.live and bool(self.models) and len(self.local_models) == len(self.models) + + def to_dict(self) -> Dict[str, Any]: + return { + "base_url": self.base_url, + "provider": self.provider, + "live": self.live, + "status": self.status, + "latency_ms": self.latency_ms, + "error": self.error, + "loading": self.loading, + "context_window": self.context_window, + "vision": self.vision, + "supports_tools": self.supports_tools, + "has_local_models": self.has_local_models, + "all_local": self.all_local, + "notes": list(self.notes), + "models": [m.to_dict() for m in self.models], + } + + @property + def supports_tools(self) -> bool: + return any(m.supports_tools for m in self.models) + + @property + def supports_embeddings(self) -> bool: + return any(m.supports_embeddings for m in self.models) + + +@dataclass +class DiscoveryReport: + """Everything :func:`discover` found, including what it could not reach.""" + + servers: List[ServerReport] = field(default_factory=list) + elapsed_ms: float = 0.0 + probed: int = 0 + + @property + def live(self) -> List[ServerReport]: + return [s for s in self.servers if s.live] + + @property + def offline(self) -> List[ServerReport]: + return [s for s in self.servers if not s.live] + + def first_live(self, require_local: bool = False) -> Optional[ServerReport]: + """Return the first live server, preferring ones with on-device models. + + With *require_local*, only servers offering at least one on-device model + qualify. + """ + if require_local: + for server in self.live: + if server.has_local_models: + return server + return None + for server in self.live: + if server.has_local_models: + return server + return self.live[0] if self.live else None + + def on_device(self) -> List[ServerReport]: + """Live servers that offer at least one on-device model.""" + return [s for s in self.live if s.has_local_models] + + def local_only(self) -> List[ServerReport]: + """Live servers whose model list is entirely on-device.""" + return [s for s in self.live if s.all_local] + + def to_dict(self) -> Dict[str, Any]: + return { + "object": "local_llm_kit.discovery", + "probed": self.probed, + "elapsed_ms": self.elapsed_ms, + "live_count": len(self.live), + "servers": [s.to_dict() for s in self.servers], + } + + +# --------------------------------------------------------------------------- +# HTTP (stdlib only) +# --------------------------------------------------------------------------- + + +def _get_json(url: str, timeout: float) -> Tuple[Optional[int], Any, Optional[str]]: + """GET *url* and decode JSON. Returns ``(status, payload, error)``. + + Any failure (DNS, refused connection, timeout, non-JSON body such as the + plain-text page Ollama serves on ``/``) is reported through *error* rather + than raised, because a probe that cannot answer is a result we want to keep. + """ + request = urllib.request.Request( + url, headers={"Accept": "application/json", "User-Agent": _USER_AGENT}, method="GET" + ) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + body = response.read() + try: + return response.status, json.loads(body.decode("utf-8", errors="replace")), None + except ValueError as exc: + return response.status, None, "invalid JSON: %s" % exc + except urllib.error.HTTPError as exc: + detail = "" + try: + detail = exc.read().decode("utf-8", errors="replace")[:200] + except Exception: # pragma: no cover - body already consumed + detail = "" + return exc.code, None, "HTTP %s%s" % (exc.code, (": " + detail) if detail else "") + except urllib.error.URLError as exc: + return None, None, str(getattr(exc, "reason", exc)) + except (TimeoutError, OSError) as exc: + return None, None, str(exc) + + +def _post_json( + url: str, payload: Dict[str, Any], timeout: float +) -> Tuple[Optional[int], Any, Optional[str]]: + data = json.dumps(payload).encode("utf-8") + request = urllib.request.Request( + url, + data=data, + headers={ + "Accept": "application/json", + "Content-Type": "application/json", + "User-Agent": _USER_AGENT, + }, + method="POST", + ) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + try: + return ( + response.status, + json.loads(response.read().decode("utf-8", errors="replace")), + None, + ) + except ValueError as exc: + return response.status, None, "invalid JSON: %s" % exc + except urllib.error.HTTPError as exc: + return exc.code, None, "HTTP %s" % exc.code + except urllib.error.URLError as exc: + return None, None, str(getattr(exc, "reason", exc)) + except (TimeoutError, OSError) as exc: + return None, None, str(exc) + + +# --------------------------------------------------------------------------- +# Model listing + provider fingerprinting +# --------------------------------------------------------------------------- + + +def _looks_remote(model_id: str, payload: Dict[str, Any]) -> Tuple[bool, Optional[str]]: + """Decide whether a listed model would run off this machine. + + Ollama is explicit: ``/api/tags`` marks cloud-routed models with + ``remote_host``/``remote_model``. As a fallback, an ``:cloud`` tag on an + otherwise-local server is treated as off-device too, because that is the + conventional naming for provider-routed models. + """ + host = payload.get("remote_host") + if isinstance(host, str) and host: + return True, host + if payload.get("remote_model"): + return True, host or "remote" + if model_id.lower().endswith(":cloud"): + return True, host + return False, None + + +def _records_from_openai_models(payload: Any) -> List[ModelRecord]: + """Parse an OpenAI ``/v1/models`` payload into :class:`ModelRecord` objects. + + Also reads the extra fields servers add on top of the OpenAI shape: + ``capabilities`` and ``context_window`` (apfel), ``meta.n_ctx_train`` + (llama.cpp), and ``details.context_length`` (Ollama's OpenAI-compat view). + """ + if not isinstance(payload, dict): + return [] + data = payload.get("data") + if not isinstance(data, list): + return [] + records: List[ModelRecord] = [] + for item in data: + if isinstance(item, str): + records.append(ModelRecord(id=item)) + continue + if not isinstance(item, dict): + continue + model_id = item.get("id") or item.get("name") or item.get("model") + if not isinstance(model_id, str) or not model_id: + continue + raw_caps = item.get("capabilities") + capabilities = [str(c) for c in raw_caps] if isinstance(raw_caps, list) else [] + context_length = item.get("context_window") + if not isinstance(context_length, int): + meta = item.get("meta") + context_length = meta.get("n_ctx_train") if isinstance(meta, dict) else None + if not isinstance(context_length, int): + details = item.get("details") + context_length = details.get("context_length") if isinstance(details, dict) else None + remote, remote_host = _looks_remote(model_id, item) + records.append( + ModelRecord( + id=model_id, + capabilities=capabilities, + context_length=context_length if isinstance(context_length, int) else None, + remote=remote, + remote_host=remote_host, + raw=item, + ) + ) + return records + + +def _identify_provider(base_url: str, models_payload: Any, hint: str) -> str: + """Name the server behind *base_url* from its own response shape. + + Users point this at arbitrary ports, so the provider is inferred from + evidence in the payload rather than assumed from the port number alone. + Returns ``""`` when the payload carries no distinguishing field, which tells + the caller to try the provider-specific marker endpoints instead. + """ + data = models_payload.get("data") if isinstance(models_payload, dict) else None + first = data[0] if isinstance(data, list) and data and isinstance(data[0], dict) else {} + if isinstance(first.get("details"), dict) and "family" in first.get("details", {}): + return "ollama" + if isinstance(first.get("meta"), dict) and "n_ctx_train" in first.get("meta", {}): + return "llama-server" + if "capabilities" in first and "context_window" in first: + return "apfel" + owned_by = str(first.get("owned_by", "")).lower() + if "llamacpp" in owned_by or "llama.cpp" in owned_by: + return "llama-server" + if "lmstudio" in owned_by or "lm studio" in owned_by: + return "lmstudio" + if "vllm" in owned_by: + return "vllm" + if owned_by in ("library", "ollama"): + return "ollama" + return "" + + +def _refine_provider(root: str, timeout: float) -> str: + """Identify a server by trying each provider's own marker endpoint. + + Used when the OpenAI-compatible model list carries no distinguishing field — + LM Studio's ``/v1/models`` reports a generic owner, for example. Only + read-only metadata endpoints are touched. + """ + status, payload, _error = _get_json(root + "/api/tags", timeout) + if status == 200 and isinstance(payload, dict) and isinstance(payload.get("models"), list): + return "ollama" + status, payload, _error = _get_json(root + "/props", timeout) + if status == 200 and isinstance(payload, dict) and "default_generation_settings" in payload: + return "llama-server" + for path in ("/api/v1/models", "/api/v0/models"): + status, payload, _error = _get_json(root + path, timeout) + if status == 200 and isinstance(payload, dict) and isinstance(payload.get("models"), list): + return "lmstudio" + return "" + + +# --------------------------------------------------------------------------- +# Capability enrichment (each server's own metadata endpoint) +# --------------------------------------------------------------------------- + + +def _enrich_ollama(report: ServerReport, root: str, timeout: float) -> None: + """Read Ollama's native ``/api/tags`` and ``/api/show`` for real capabilities. + + ``/api/tags`` is the only place Ollama exposes ``remote_host`` (whether a + model runs on ollama.com) and per-model ``capabilities``; ``/api/show`` is + where the true ``context_length`` lives — the OpenAI-compatible + ``/v1/models`` view reports neither. + """ + status, payload, error = _get_json(root + "/api/tags", timeout) + if status != 200 or not isinstance(payload, dict): + report.notes.append("ollama /api/tags unavailable (%s)" % (error or status)) + return + models = payload.get("models") + if not isinstance(models, list): + return + catalog: Dict[str, Dict[str, Any]] = {} + for item in models: + if not isinstance(item, dict): + continue + name = item.get("name") or item.get("model") + if isinstance(name, str) and name: + catalog[name] = item + records: List[ModelRecord] = [] + for model_id, item in catalog.items(): + capabilities = [str(c) for c in item.get("capabilities") or [] if isinstance(c, str)] + details = item.get("details") if isinstance(item.get("details"), dict) else {} + raw_context = details.get("context_length") + remote, remote_host = _looks_remote(model_id, item) + records.append( + ModelRecord( + id=model_id, + capabilities=capabilities, + context_length=raw_context if isinstance(raw_context, int) else None, + remote=remote, + local_verified=not remote, + remote_host=remote_host, + raw=item, + ) + ) + if records: + report.models = records + report.notes.append("capabilities read from ollama /api/tags") + + +def _enrich_llama_server(report: ServerReport, root: str, timeout: float) -> None: + """Read llama.cpp ``/props`` for the live context size and modality flags.""" + status, payload, error = _get_json(root + "/props", timeout) + if status != 200 or not isinstance(payload, dict): + report.notes.append("llama.cpp /props unavailable (%s)" % (error or status)) + return + settings = payload.get("default_generation_settings") + n_ctx = settings.get("n_ctx") if isinstance(settings, dict) else None + if isinstance(n_ctx, int) and n_ctx > 0: + report.context_window = n_ctx + for model in report.models: + if model.context_length is None: + model.context_length = n_ctx + modalities = payload.get("modalities") + if isinstance(modalities, dict) and "vision" in modalities: + report.vision = bool(modalities["vision"]) + if payload.get("is_sleeping"): + report.notes.append("server is sleeping (idle sleep is enabled)") + model_path = payload.get("model_path") + if isinstance(model_path, str) and model_path: + for model in report.models: + model.local_verified = not model.remote + report.notes.append("model file: %s" % model_path) + + +def _enrich_lmstudio(report: ServerReport, root: str, timeout: float) -> None: + """Read LM Studio's native model API for vision/tool/context capabilities. + + LM Studio exposes ``capabilities.vision`` and + ``capabilities.trained_for_tool_use`` plus ``max_context_length`` on its + native endpoint only; its OpenAI-compatible ``/v1/models`` lists bare ids. + Both the current ``/api/v1/models`` and the older ``/api/v0/models`` are + tried. + """ + for path in ("/api/v1/models", "/api/v0/models"): + status, payload, _error = _get_json(root + path, timeout) + if status != 200 or not isinstance(payload, dict): + continue + entries = payload.get("models") + if not isinstance(entries, list): + entries = payload.get("data") + if not isinstance(entries, list): + continue + records: List[ModelRecord] = [] + for item in entries: + if not isinstance(item, dict): + continue + model_id = item.get("key") or item.get("id") + if not isinstance(model_id, str) or not model_id: + continue + capabilities: List[str] = [] + caps = item.get("capabilities") + if isinstance(caps, dict): + if caps.get("vision"): + capabilities.append("vision") + if caps.get("trained_for_tool_use"): + capabilities.append("tools") + reasoning = caps.get("reasoning") + if isinstance(reasoning, dict): + capabilities.append("reasoning") + model_type = item.get("type") + if isinstance(model_type, str) and model_type: + capabilities.append(model_type) + context_length = item.get("max_context_length") + if not isinstance(context_length, int): + instances = item.get("loaded_instances") + if isinstance(instances, list) and instances and isinstance(instances[0], dict): + config = instances[0].get("config") + if isinstance(config, dict): + context_length = config.get("context_length") + records.append( + ModelRecord( + id=model_id, + capabilities=capabilities, + context_length=context_length if isinstance(context_length, int) else None, + raw=item, + ) + ) + if records: + for model in records: + model.local_verified = bool(model.raw.get("loaded_instances")) + report.models = records + report.notes.append("capabilities read from lmstudio %s" % path) + return + report.notes.append("lmstudio native model API unavailable") + + +def _enrich_per_model_context(report: ServerReport, root: str, timeout: float) -> None: + """Fill in context length per model via Ollama ``/api/show`` when missing.""" + missing = [m for m in report.models if m.context_length is None][:_MAX_ENRICHED_MODELS] + for model in missing: + status, payload, _error = _post_json(root + "/api/show", {"model": model.id}, timeout) + if status != 200 or not isinstance(payload, dict): + continue + capabilities = payload.get("capabilities") + if isinstance(capabilities, list) and capabilities: + model.capabilities = [str(c) for c in capabilities] + info = payload.get("model_info") + if isinstance(info, dict): + for key, value in info.items(): + if key.endswith(".context_length") and isinstance(value, int) and value > 0: + model.context_length = value + break + + +#: ``provider -> enricher``. Enrichers read that server's own metadata API and +#: mutate the report in place; a failure only appends a note. +_ENRICHERS = { + "ollama": _enrich_ollama, + "llama-server": _enrich_llama_server, + "lmstudio": _enrich_lmstudio, + "apfel": lambda report, root, timeout: None, +} + + +# --------------------------------------------------------------------------- +# Probing +# --------------------------------------------------------------------------- + + +def probe_endpoint( + base_url: str, + provider: str = "", + timeout: float = DEFAULT_TIMEOUT, + enrich: bool = True, +) -> ServerReport: + """Probe one endpoint and return its report (never raises for I/O errors). + + Args: + base_url: Anything :func:`normalize_base_url` accepts. + provider: Expected provider name, used as a hint in ``notes``. The real + provider is inferred from the server's response. + timeout: Per-request timeout in seconds. + enrich: Read provider-specific capability metadata (an extra request or + two). Disable for the fastest possible liveness check. + + Raises: + ValueError: only for a malformed *base_url* argument. + """ + if ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not math.isfinite(timeout) + or timeout <= 0 + ): + raise ValueError("timeout must be a positive number of seconds.") + normalized = normalize_base_url(base_url) + root = _server_root(normalized) + report = ServerReport(base_url=normalized, provider=provider) + + started = time.perf_counter() + status, payload, error = _get_json(normalized + "/models", timeout) + report.latency_ms = round((time.perf_counter() - started) * 1000, 1) + report.status = status + + if status == 200 and isinstance(payload, dict): + report.live = True + report.models = _records_from_openai_models(payload) + report.provider = _identify_provider(normalized, payload, provider) + if not report.provider: + report.provider = _refine_provider(root, timeout) or provider or "unknown" + if report.provider != provider: + report.notes.append("provider identified as %s" % report.provider) + if not report.models: + report.notes.append("server is live but lists no models") + elif status is not None and status >= 500: + report.error = error + report.notes.append("server answered %s; it may still be loading a model" % status) + else: + report.error = error or ("HTTP %s" % status if status else "unreachable") + return report + + if enrich: + enricher = _ENRICHERS.get(report.provider) + if enricher is not None: + try: + enricher(report, root, timeout) + except Exception as exc: # noqa: BLE001 - enrichment is best-effort + report.notes.append("capability lookup failed: %s" % exc) + if report.provider == "ollama": + try: + _enrich_per_model_context(report, root, timeout) + except Exception as exc: # noqa: BLE001 - enrichment is best-effort + report.notes.append("context lookup failed: %s" % exc) + + if report.live and any(not m.local_verified and not m.remote for m in report.models): + report.notes.append( + "Execution locality is unknown for some models; a loopback endpoint can proxy a remote service." + ) + remote = report.remote_models + if remote: + hosts = sorted({m.remote_host or "remote" for m in remote}) + report.notes.append( + "%d of %d model(s) are routed off-device (%s)" + % (len(remote), len(report.models), ", ".join(hosts)) + ) + return report + + +def _probe_all( + endpoints: Sequence[Endpoint], timeout: float, enrich: bool, workers: int +) -> List[ServerReport]: + with concurrent.futures.ThreadPoolExecutor( + max_workers=max(1, min(workers, len(endpoints))) + ) as pool: + futures = [ + pool.submit(probe_endpoint, endpoint.base_url, endpoint.provider, timeout, enrich) + for endpoint in endpoints + ] + results = [] + for future in futures: + try: + results.append(future.result()) + except Exception as exc: # noqa: BLE001 - a probe must never break discovery + results.append(ServerReport(base_url="unknown", provider="unknown", error=str(exc))) + return results + + +def discover( + extra_urls: Optional[Sequence[str]] = None, + include_known: bool = True, + timeout: float = DEFAULT_TIMEOUT, + enrich: bool = True, + max_workers: int = 8, +) -> DiscoveryReport: + """Probe local LLM endpoints concurrently and report what is running. + + Args: + extra_urls: Additional base URLs to probe (not required to be in + :data:`ENDPOINTS`). + include_known: Probe the built-in :data:`ENDPOINTS` catalog. + timeout: Per-request timeout in seconds. + enrich: Also read each server's own capability metadata. + max_workers: Probe concurrency. + + Returns: + A :class:`DiscoveryReport`. Dead endpoints appear with ``live=False``, + so callers can show a full picture rather than only successes. + """ + if ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not math.isfinite(timeout) + or timeout <= 0 + ): + raise ValueError("timeout must be a positive number of seconds.") + if isinstance(max_workers, bool) or not isinstance(max_workers, int) or max_workers < 1: + raise ValueError("max_workers must be a positive integer.") + + endpoints: List[Endpoint] = [] + seen = set() + for endpoint in list(ENDPOINTS) if include_known else []: + normalized = normalize_base_url(endpoint.base_url) + if normalized in seen: + continue # several providers share a well-known port (11434, 8080) + seen.add(normalized) + endpoints.append(Endpoint(endpoint.provider, normalized)) + for url in extra_urls or []: + normalized = normalize_base_url(url) + if normalized not in seen: + seen.add(normalized) + endpoints.append(Endpoint("custom", normalized)) + + started = time.perf_counter() + if not endpoints: + return DiscoveryReport(servers=[], elapsed_ms=0.0, probed=0) + reports = _probe_all(endpoints, timeout, enrich, max_workers) + elapsed = round((time.perf_counter() - started) * 1000, 1) + return DiscoveryReport(servers=reports, elapsed_ms=elapsed, probed=len(endpoints)) + + +def find_local_server( + require_local: bool = True, + extra_urls: Optional[Sequence[str]] = None, + timeout: float = DEFAULT_TIMEOUT, + include_known: bool = True, +) -> Optional[ServerReport]: + """Return a live server that can serve an on-device model, or None. + + With *require_local* (the default) only servers offering at least one + on-device model qualify, so a caller cannot accidentally fall through to a + provider-routed model. + """ + report = discover( + extra_urls=extra_urls, include_known=include_known, timeout=timeout, enrich=True + ) + candidates = report.on_device() if require_local else report.live + return candidates[0] if candidates else None diff --git a/local_llm_kit/hardware.py b/local_llm_kit/hardware.py new file mode 100644 index 0000000..d0d59d8 --- /dev/null +++ b/local_llm_kit/hardware.py @@ -0,0 +1,220 @@ +"""Measured host memory and approximate model budgets (GiB). + +Estimates depend on architecture, backend, batch size and cache allocation. +They are planning guidance and cannot guarantee that a model will fit. +""" + +import math +import platform +import re +import subprocess +import sys +from typing import Any, Dict, Optional + +QUANT_BPW: Dict[str, float] = { + "FP16": 16.0, + "BF16": 16.0, + "Q8_0": 8.5, + "Q6_K": 6.56, + "Q5_K_M": 5.5, + "Q5_K_S": 5.0, + "Q5_0": 5.0, + "Q4_K_M": 4.5, + "Q4_K_S": 4.25, + "Q4_0": 4.5, + "Q3_K_M": 3.4, + "Q3_K_S": 3.0, + "Q2_K": 2.6, +} + + +def _command(*args: str) -> str: + return subprocess.run(args, capture_output=True, text=True, check=True, timeout=3).stdout + + +def get_system_memory() -> Dict[str, Any]: + """Return measured memory, with zero and notes for unavailable measurements. + + Dedicated GPUs are reported separately: their memory is never summed into + a fictitious single GPU. Apple unified memory uses reclaimable host RAM. + """ + total = available = gpu_total = gpu_available = 0.0 + apple = sys.platform == "darwin" and platform.machine() == "arm64" + notes = [] + gpus = [] + try: + if sys.platform == "darwin": + total = int(_command("sysctl", "-n", "hw.memsize").strip()) / 1024**3 + stats = _command("vm_stat") + page_size = int(re.search(r"page size of (\d+) bytes", stats).group(1)) + pages = sum( + int(value) + for value in re.findall(r"Pages (?:free|inactive|speculative):\s+(\d+)", stats) + ) + available = pages * page_size / 1024**3 + notes.append("macOS available RAM approximates free, inactive and speculative pages.") + elif sys.platform.startswith("linux"): + with open("/proc/meminfo", encoding="utf-8") as file: + info = dict(re.findall(r"^(MemTotal|MemAvailable):\s+(\d+)", file.read(), re.M)) + total = int(info["MemTotal"]) / 1024**2 + available = int(info.get("MemAvailable", 0)) / 1024**2 + elif sys.platform == "win32": + import ctypes + from ctypes import wintypes + + class MemoryStatus(ctypes.Structure): + _fields_ = [("length", wintypes.DWORD), ("load", wintypes.DWORD)] + [ + (name, ctypes.c_ulonglong) + for name in ( + "total", + "available", + "page_total", + "page_available", + "virtual_total", + "virtual_available", + "extended_available", + ) + ] + + status = MemoryStatus() + status.length = ctypes.sizeof(status) + if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)): + raise OSError("GlobalMemoryStatusEx failed") + total, available = status.total / 1024**3, status.available / 1024**3 + except (OSError, ValueError, KeyError, AttributeError, subprocess.SubprocessError) as exc: + notes.append("RAM measurement incomplete: %s" % type(exc).__name__) + if apple: + gpu_total, gpu_available = total, available + else: + try: + output = _command( + "nvidia-smi", + "--query-gpu=memory.total,memory.free", + "--format=csv,noheader,nounits", + ) + for line in output.strip().splitlines(): + size, free = (float(part.strip()) / 1024 for part in line.split(",")) + gpus.append({"total_gb": round(size, 2), "available_gb": round(free, 2)}) + if gpus: + largest = max(gpus, key=lambda gpu: gpu["available_gb"]) + gpu_total, gpu_available = largest["total_gb"], largest["available_gb"] + except (OSError, ValueError, subprocess.SubprocessError): + notes.append("Dedicated GPU memory unavailable; no supported nvidia-smi measurement.") + if available <= 0: + notes.append("Available RAM is unknown; provide available_memory_gb for a recommendation.") + return { + "total_ram_gb": round(total, 2), + "available_ram_gb": round(available, 2), + "gpu_vram_gb": round(gpu_total, 2), + "available_gpu_vram_gb": round(gpu_available, 2), + "gpus": gpus, + "platform": platform.platform(), + "is_apple_silicon": apple, + "notes": notes, + } + + +def _positive(value: Any, name: str, integer: bool = False) -> None: + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(value) + or value <= 0 + or (integer and not isinstance(value, int)) + ): + raise ValueError( + "%s must be a finite positive %s." % (name, "integer" if integer else "number") + ) + + +def estimate_model_vram( + params_b: float, + quant: str = "Q4_K_M", + context_length: int = 4096, + kv_quant: str = "fp16", + *, + num_layers: Optional[int] = None, + num_kv_heads: Optional[int] = None, + head_dim: Optional[int] = None, +) -> Dict[str, Any]: + """Estimate weights, KV cache and runtime overhead for one sequence. + + Supply all three architecture dimensions for the model's KV cache formula. + Otherwise a Llama-like geometry is assumed. Quantization metadata and runtime + overhead remain approximate even with the exact architecture dimensions. + """ + _positive(params_b, "params_b") + _positive(context_length, "context_length", integer=True) + if not isinstance(quant, str) or quant.upper() not in QUANT_BPW: + raise ValueError("Unknown weight quantization: %r" % quant) + precisions = {"fp16": 2.0, "q8_0": 1.0, "q4_0": 0.5} + if not isinstance(kv_quant, str) or kv_quant.lower() not in precisions: + raise ValueError("Unknown KV cache quantization: %r" % kv_quant) + geometry = (num_layers, num_kv_heads, head_dim) + heuristic = all(value is None for value in geometry) + if not heuristic: + for value, name in zip(geometry, ("num_layers", "num_kv_heads", "head_dim")): + _positive(value, name, integer=True) + else: + num_layers, num_kv_heads, head_dim = max(16, int(32 * params_b / 8)), 8, 128 + weights = params_b * 1e9 * QUANT_BPW[quant.upper()] / 8 / 1024**3 + kv = ( + 2 + * num_layers + * num_kv_heads + * head_dim + * precisions[kv_quant.lower()] + * context_length + / 1024**3 + ) + overhead = weights * 0.15 + 0.5 + return { + "weights_gb": round(weights, 2), + "kv_cache_gb": round(kv, 2), + "overhead_gb": round(overhead, 2), + "total_gb": round(weights + kv + overhead, 2), + "architecture_assumed": heuristic, + "assumptions": "One sequence; approximate weight sizes and runtime overhead. " + + ( + "Llama-like KV geometry inferred from parameter count." + if heuristic + else "KV geometry supplied by caller." + ), + } + + +def recommend_quantization( + params_b: float, + available_memory_gb: Optional[float] = None, + context_length: int = 4096, +) -> Dict[str, Any]: + """Suggest a quantization within 85% of measured or supplied available memory.""" + notes = [] + if available_memory_gb is None: + memory = get_system_memory() + notes = memory["notes"] + available_memory_gb = memory["available_gpu_vram_gb"] or memory["available_ram_gb"] + if available_memory_gb <= 0: + raise ValueError("Available memory is unknown. Pass available_memory_gb explicitly.") + _positive(available_memory_gb, "available_memory_gb") + candidates = ["FP16", "Q8_0", "Q6_K", "Q5_K_M", "Q4_K_M", "Q3_K_M", "Q2_K"] + best = None + for quant in candidates: + estimate = estimate_model_vram(params_b, quant, context_length) + if estimate["total_gb"] <= available_memory_gb * 0.85: + best = quant, estimate + break + quant, estimate = best or ("Q2_K", estimate_model_vram(params_b, "Q2_K", context_length)) + return { + "recommended_quant": quant if best else None, + "status": "fits_comfortably" if best else "exceeds_budget", + "available_memory_gb": round(available_memory_gb, 2), + "estimate": estimate, + "notes": notes, + "recommendation": ( + "Recommended estimate: %s" % quant + if best + else "Warning: no candidate fits the estimated budget" + ) + + ". Estimates cannot guarantee a fit; verify actual peak memory with your backend.", + } diff --git a/local_llm_kit/llm.py b/local_llm_kit/llm.py index 39ae93a..fc2163c 100644 --- a/local_llm_kit/llm.py +++ b/local_llm_kit/llm.py @@ -1,7 +1,7 @@ """ Core LLM class with an OpenAI-compatible API over local backends. -Backends: "auto" | "transformers" | "llamacpp" | "ollama" | "openai-compat" | "echo". +Backends: "auto" | "transformers" | "airllm" | "apple-fm" | "llamacpp" | "ollama" | "openai-compat" | "echo". Only the stdlib is imported at module load; heavy backends (transformers, llama.cpp, ...) are imported lazily inside ``_init_backend``. @@ -28,7 +28,6 @@ from __future__ import annotations import asyncio -import concurrent.futures import json import logging import threading @@ -44,6 +43,7 @@ from .tools import ( ToolCall, ToolRegistry, + _validate_tool_timeout, normalize_tools, parse_tool_calls, should_call_tools, @@ -57,6 +57,7 @@ "auto", "transformers", "airllm", + "apple-fm", "llamacpp", "ollama", "openai-compat", @@ -251,28 +252,23 @@ def _tool_names(tools_norm: List[Dict[str, Any]]) -> List[str]: return names -def _required_params(tool_spec: Dict[str, Any]) -> List[str]: - try: - fn = tool_spec.get("function", tool_spec) if isinstance(tool_spec, dict) else {} - params = fn.get("parameters", {}) if isinstance(fn, dict) else {} - required = params.get("required", []) if isinstance(params, dict) else [] - return [r for r in required if isinstance(r, str)] - except AttributeError: - return [] - - class LLM: """ OpenAI-like interface for local language models. :param model_path: path, HF id, Ollama tag, URL, or "echo". - :param backend: "auto" (default), "transformers", "llamacpp", "ollama", - "openai-compat", or "echo". + :param backend: "auto" (default), "transformers", "airllm", "apple-fm", + "llamacpp", "ollama", "openai-compat", or "echo". :param backend_instance: pre-built backend object (tests / DI). Skips the cache and auto-detection entirely. :param use_cache: reuse module-level cached backends for identical ``(model_path, backend, backend_kwargs)``. Set False in tests that need isolation. + :param require_local: require a known in-process engine or verified local + model metadata. Unknown or remote routes fail closed at construction + and before chat/completion; see :meth:`assert_local`. This trusts + server metadata rather than enforcing a network sandbox. + :param conversation_log: optional ConversationLog for completed chat snapshots. """ def __init__( @@ -288,12 +284,16 @@ def __init__( backend_kwargs: Optional[Dict[str, Any]] = None, backend_instance: Optional[BaseBackend] = None, use_cache: bool = True, + require_local: bool = False, + conversation_log: Optional[Any] = None, ): if not isinstance(model_path, str) or not model_path.strip(): raise ValueError("model_path must be a non-empty string.") if backend is not None and not isinstance(backend, str): raise TypeError("backend must be a string or None.") self.model_path = model_path + self.require_local = require_local + self.conversation_log = conversation_log self.max_new_tokens = max_new_tokens self.temperature = temperature self.top_p = top_p @@ -320,6 +320,11 @@ def __init__( with _CACHE_LOCK: _BACKEND_CACHE.setdefault(key, self.backend) + # Check locality metadata before reading the context window, so a + # detection triggered here also supplies the model's real window size. + if require_local: + self.assert_local() + if context_window: self.context_window = context_window else: @@ -334,6 +339,9 @@ def __init__( # ToolRegistry subclasses FunctionRegistry, so both APIs share one store. self.tool_registry = ToolRegistry() self.function_registry = self.tool_registry # backwards-compat alias + #: Open MCP server connections registered via :meth:`add_mcp_server`. + self._mcp_servers: Dict[str, Any] = {} + self._mcp_tool_names: Dict[str, List[str]] = {} # -- backend setup ---------------------------------------------------- def _init_backend(self, backend_name: Optional[str]) -> BaseBackend: @@ -385,6 +393,18 @@ def _init_backend(self, backend_name: Optional[str]) -> BaseBackend: from .backends.airllm import AirLLMBackend return AirLLMBackend(self.model_path, **self.backend_kwargs) + if name == "apple-fm": + try: + from .backends.apple_fm import AppleFMBackend + + return AppleFMBackend(self.model_path, **self.backend_kwargs) + except ImportError as exc: + raise RuntimeError( + "apple-fm backend needs Apple's Foundation Models SDK " + "(pip install 'local-llm-kit[apple-fm]'). Requires macOS 26+, " + "Xcode 26+ (SDK agreement accepted), Python 3.10+, and Apple " + "Intelligence turned on." + ) from exc if name == "ollama": try: from .backends.ollama import OllamaBackend # type: ignore @@ -410,6 +430,64 @@ def _init_backend(self, backend_name: Optional[str]) -> BaseBackend: ) from exc raise AssertionError("unreachable") # pragma: no cover + # -- local execution metadata ---------------------------------------------- + def detect_backend_capabilities(self) -> Dict[str, Any]: + """Ask the backend what the model can really do, when it can say. + + Backends that expose ``detect_capabilities()`` (currently Ollama) report + the model's true context length, capability list and whether the model + is routed off this machine. Backends without that concept are a no-op. + Never raises: an unreachable server leaves the backend's current values. + """ + detect = getattr(self.backend, "detect_capabilities", None) + if not callable(detect): + return {"supported": False, "reason": "backend does not report capabilities"} + try: + result = detect() + except Exception as exc: # noqa: BLE001 - detection is best-effort + return {"supported": True, "error": str(exc)} + if isinstance(result, dict): + return dict(result, supported=True) + return {"supported": True} + + def assert_local(self) -> bool: + """Require an in-process backend or verified local-server metadata. + + Unknown routing fails closed. Metadata is a report from the configured + server, not a security boundary against a dishonest server operator. + """ + from .discovery import is_loopback_url, probe_endpoint + + name = getattr(self.backend, "backend_name", "") + if name in ("echo", "transformers", "llamacpp", "airllm", "apple-fm"): + return True + if name == "ollama": + if not is_loopback_url(self.backend.host): + raise RuntimeError("require_local refuses a non-loopback Ollama endpoint.") + detection = self.detect_backend_capabilities() + if detection.get("remote"): + raise RuntimeError( + "Model %r is routed off-device to %s." + % (self.model_path, detection.get("remote_host") or "a remote host") + ) + if detection.get("error") or not detection.get("routing_verified"): + raise RuntimeError( + "Could not confirm that %r runs on this machine: routing metadata unavailable." + % self.model_path + ) + if not detection.get("remote"): + return True + elif name == "openai-compat": + if not is_loopback_url(self.backend.base_url): + raise RuntimeError("require_local refuses a non-loopback endpoint.") + report = probe_endpoint(self.backend.base_url, timeout=min(self.backend.timeout, 5.0)) + if any(m.id == self.model_path for m in report.local_models): + return True + raise RuntimeError( + "Could not confirm that %r runs on this machine; the model is remote or its execution locality is unknown." + % self.model_path + ) + # -- registration ----------------------------------------------------- def add_function(self, name: str, schema: Dict[str, Any], implementation: Callable) -> None: """Register a legacy function (also usable as a modern tool).""" @@ -423,6 +501,146 @@ def list_tools(self) -> List[Dict[str, Any]]: """Return registered tools in OpenAI ``tools`` format.""" return self.tool_registry.get_tool_list() + # -- MCP (Model Context Protocol) ------------------------------------- + @property + def mcp_servers(self) -> Dict[str, Any]: + """Mapping of name -> open :class:`local_llm_kit.mcp.MCPServer`.""" + return dict(self._mcp_servers) + + def add_mcp_server( + self, + server: Any = None, + name: Optional[str] = None, + command: Optional[str] = None, + args: Optional[List[str]] = None, + url: Optional[str] = None, + env: Optional[Dict[str, str]] = None, + cwd: Optional[str] = None, + headers: Optional[Dict[str, str]] = None, + timeout: float = 30.0, + prefix: Union[bool, str, None] = True, + include: Optional[List[str]] = None, + exclude: Optional[List[str]] = None, + ) -> List[str]: + """Connect an MCP server and register its tools on this client. + + Either pass an already-built/open :class:`~local_llm_kit.mcp.MCPServer` + as *server*, or the connection details (``command`` for stdio, ``url`` + for Streamable HTTP). Discovered tools become regular tools usable by + :meth:`chat` (including the auto-execution tool loop). + + :param name: server name (required when building from ``command``/``url``); + also used as the default tool namespace. + :param prefix: ``True`` (default) namespaces tools as ``__`` + to avoid collisions across servers; pass a string to choose the + namespace, or ``False``/``None`` to keep the raw MCP names. + :param include: when set, only these MCP tool names are registered. + :param exclude: MCP tool names to skip. + :returns: the registered (possibly namespaced) tool names. + """ + from .mcp import MCPServer, sanitize_tool_name + + if isinstance(server, str): + if name is not None and name != server: + raise ValueError("Conflicting MCP server names.") + name, server = server, None + if server is None: + if not name: + raise ValueError("add_mcp_server needs a server instance or a name.") + server = MCPServer( + name, + command=command, + args=args, + url=url, + env=env, + cwd=cwd, + headers=headers, + timeout=timeout, + ) + elif name is None: + name = getattr(server, "name", None) + server_name = name or getattr(server, "name", "mcp") + if server_name in self._mcp_servers: + raise ValueError("An MCP server with this name is already registered: %s" % server_name) + opened_here = getattr(server, "closed", False) or not getattr(server, "_opened", False) + try: + if getattr(server, "closed", False) or not getattr(server, "_opened", False): + server.open() + namespace = server_name if prefix is True else (prefix or None) + pending = [] + names = set(self.tool_registry.functions) + for tool in server.list_tools(): + if include is not None and tool.name not in include: + continue + if exclude is not None and tool.name in exclude: + continue + qualified = sanitize_tool_name( + "%s__%s" % (namespace, tool.name) if namespace else tool.name + ) + if qualified in names: + raise ValueError("MCP tool name collides with an existing tool: %s" % qualified) + names.add(qualified) + pending.append((qualified, tool)) + except Exception: + if opened_here: + server.close() + raise + registered = [] + for qualified, tool in pending: + self.tool_registry.add_function( + name=qualified, + schema=dict(tool.to_openai(qualified)["function"]), + implementation=self._mcp_tool_impl(server, tool.name), + ) + registered.append(qualified) + self._mcp_tool_names[server_name] = registered + self._mcp_servers[server_name] = server + logger.info( + "Registered %d MCP tool(s) from server %r: %s", + len(registered), + server_name, + ", ".join(registered) or "(none)", + ) + return registered + + @staticmethod + def _mcp_tool_impl(server: Any, tool_name: str) -> Callable[..., str]: + """Build the tool implementation that forwards to the MCP server.""" + + def _call(**kwargs: Any) -> str: + return server.call_tool(tool_name, kwargs) + + _call.__name__ = tool_name + return _call + + def close(self) -> None: + """Close MCP server connections and release backend resources.""" + for server in list(self._mcp_servers.values()): + try: + server.close() + except Exception: # noqa: BLE001 - teardown must not raise + logger.debug( + "Error closing MCP server %r", getattr(server, "name", "?"), exc_info=True + ) + self._mcp_servers.clear() + for names in self._mcp_tool_names.values(): + for name in names: + self.tool_registry.functions.pop(name, None) + self.tool_registry.implementations.pop(name, None) + self._mcp_tool_names.clear() + close_backend = getattr(self.backend, "close", None) + if callable(close_backend): + try: + close_backend() + except Exception: # noqa: BLE001 - teardown must not raise + logger.debug("Error closing backend", exc_info=True) + + def __enter__(self) -> "LLM": + return self + + def __exit__(self, *exc: Any) -> None: + self.close() + # -- internal plumbing ------------------------------------------------ def _now(self) -> int: try: @@ -533,57 +751,8 @@ def _execute_tool_call( timeout: Optional[float] = 10.0, registry: Optional[ToolRegistry] = None, ) -> str: - """Execute one tool call with scope check, arg validation and timeout. - - Failures are returned as tool-output strings (generic, truncated — - never tracebacks) so they can't leak secrets into chat history. - """ - if allowed_names is not None and call.name not in allowed_names: - return "Error: tool '%s' is not available for this request" % call.name registry = self.tool_registry if registry is None else registry - if not registry.has_function(call.name): - return "Error: tool '%s' is not registered" % call.name - if not isinstance(call.arguments, dict): - return "Error: tool '%s' received invalid arguments (must be an object)" % call.name - if spec is not None: - missing = [r for r in _required_params(spec) if r not in call.arguments] - if missing: - return "Error: tool '%s' missing required argument(s): %s" % ( - call.name, - ", ".join(missing), - ) - try: - impl = registry.implementations[call.name] - except (AttributeError, KeyError): - return "Error: tool '%s' has no implementation" % call.name - try: - if timeout is None: - result = impl(**call.arguments) - else: - # NOTE: deliberately not a `with` block -- ThreadPoolExecutor's - # __exit__ joins the worker, which would make a timed-out tool - # block until it finishes and defeat the timeout entirely. - pool = concurrent.futures.ThreadPoolExecutor(max_workers=1) - try: - future = pool.submit(impl, **call.arguments) - result = future.result(timeout=timeout) - finally: - pool.shutdown(wait=False) - except concurrent.futures.TimeoutError: - return "Error: tool '%s' timed out after %s seconds" % (call.name, timeout) - except Exception as exc: # noqa: BLE001 (tool errors become tool output) - logger.warning("Tool '%s' failed: %s", call.name, exc) - return "Error: tool '%s' failed (%s: %s)" % ( - call.name, - type(exc).__name__, - str(exc)[:200], - ) - if isinstance(result, str): - return result - try: - return json.dumps(result, default=str) - except (TypeError, ValueError): # e.g. circular references - return str(result) + return registry.execute_call(call, allowed_names, spec, timeout) def _ensure_json_output(self, text: str) -> str: try: @@ -669,6 +838,8 @@ def chat( (None = no timeout). :param max_iterations: maximum tool-execution rounds. """ + if self.require_local: + self.assert_local() if not isinstance(messages, list): raise TypeError("messages must be a list of message dicts.") for i, message in enumerate(messages): @@ -683,6 +854,7 @@ def chat( raise TypeError("functions must be a list or None.") if isinstance(max_iterations, bool) or not isinstance(max_iterations, int): raise TypeError("max_iterations must be an integer.") + _validate_tool_timeout(tool_timeout) # Per-call tools must not mutate a shared/cached client's registry. request_registry = ToolRegistry() request_registry.functions = dict(self.tool_registry.functions) @@ -807,8 +979,10 @@ def _chat_once( "content": text or None, "tool_calls": [c.to_dict() for c in calls], } - if isinstance(result, dict) and result.get("thinking"): - assistant_msg["thinking"] = result["thinking"] + if isinstance(result, dict): + for key in ("thinking", "reasoning_content"): + if result.get(key): + assistant_msg[key] = result[key] if len(calls) == 1: assistant_msg["function_call"] = { "name": calls[0].name, @@ -851,6 +1025,10 @@ def _chat_once( message = {"role": "assistant", "content": text} self.memory.add_messages([message]) + if isinstance(result, dict): + for key in ("thinking", "reasoning_content"): + if result.get(key): + message[key] = result[key] response: Dict[str, Any] = { "id": _new_id("chatcmpl"), "object": "chat.completion", @@ -861,8 +1039,23 @@ def _chat_once( if gen_params.get("logprobs"): response["choices"][0]["logprobs"] = {} response["usage"] = self._usage(prompt, "".join(completion_parts) if pending else text) + self._log_chat(working, response) return response + def _log_chat(self, history: List[Dict[str, Any]], response: Dict[str, Any]) -> None: + if self.conversation_log is not None: + response["conversation_id"] = self.conversation_log.log_interaction( + model=self.model_path, messages=history, response=response + ) + + def chat_structured( + self, messages: List[Dict[str, Any]], schema: Any = None, **kwargs: Any + ) -> Any: + """Generate and validate JSON; dictionary schemas need the structured extra.""" + from .structured import chat_structured + + return chat_structured(self, messages, schema=schema, **kwargs) + def _chat_streaming( self, history: List[Dict[str, Any]], @@ -893,6 +1086,7 @@ def _chat_streaming( accumulated = "" native_calls = [] thinking = "" + reasoning = "" finish = "stop" first = True if getattr(self.backend, "supports_native_chat", False): @@ -906,6 +1100,7 @@ def _chat_streaming( for chunk in chunk_iter: if isinstance(chunk, dict): thinking += chunk.get("thinking") or "" + reasoning += chunk.get("reasoning_content") or "" if chunk.get("tool_calls"): native_calls.extend(chunk["tool_calls"]) if chunk.get("finish_reason"): @@ -913,6 +1108,10 @@ def _chat_streaming( piece = chunk.get("text", "") if isinstance(chunk, dict) else str(chunk) accumulated += piece delta: Dict[str, Any] = {"content": piece} + if isinstance(chunk, dict): + for key in ("thinking", "reasoning_content"): + if chunk.get(key): + delta[key] = chunk[key] if first: delta["role"] = "assistant" first = False @@ -939,6 +1138,27 @@ def _chat_streaming( if forced_name: calls = [c for c in calls if c.name == forced_name] if not calls or not execute_tools or turn >= max_iterations: + final_message: Dict[str, Any] = { + "role": "assistant", + "content": accumulated or None, + } + if calls: + final_message["tool_calls"] = [call.to_dict() for call in calls] + if thinking: + final_message["thinking"] = thinking + if reasoning: + final_message["reasoning_content"] = reasoning + self.memory.add_messages([final_message]) + final_response = { + "choices": [ + { + "message": final_message, + "finish_reason": "tool_calls" if calls else finish, + } + ], + "usage": self._usage(prompt, accumulated), + } + self._log_chat(working, final_response) if calls: # surface the calls (unexecuted in server-safe mode) delta2: Dict[str, Any] = { "content": None, @@ -956,6 +1176,7 @@ def _chat_streaming( "object": "chat.completion.chunk", "created": created, "model": self.model_path, + "usage": final_response["usage"], "choices": [ { "index": 0, @@ -974,6 +1195,7 @@ def _chat_streaming( "object": "chat.completion.chunk", "created": created, "model": self.model_path, + "usage": final_response["usage"], "choices": [{"index": 0, "delta": {}, "finish_reason": finish}], } return @@ -985,6 +1207,8 @@ def _chat_streaming( } if thinking: assistant_msg["thinking"] = thinking + if reasoning: + assistant_msg["reasoning_content"] = reasoning working.append(assistant_msg) self.memory.add_messages([assistant_msg]) for call in calls: @@ -1022,6 +1246,8 @@ def complete( repetition_penalty: Optional[float] = None, **kwargs: Any, ) -> Union[Dict[str, Any], Iterator[Dict[str, Any]]]: + if self.require_local: + self.assert_local() if not isinstance(prompt, str): raise TypeError("prompt must be a string.") rf = _normalize_response_format(response_format, format) @@ -1173,3 +1399,20 @@ async def _acomplete_stream(self, *args: Any, **kwargs: Any): def __repr__(self) -> str: return "LLM(model_path=%r, backend=%s)" % (self.model_path, type(self.backend).__name__) + + # -- introspection ---------------------------------------------------- + def list_models(self) -> List[Dict[str, Any]]: + """List models reported by the backend. + + Server backends (Ollama, OpenAI-compatible) report their models; + single-model local backends return ``[]`` from the backend, in + which case this falls back to a single entry for ``model_path``. + Never raises: backend listing failures degrade to the fallback. + """ + try: + models = self.backend.list_models() + except Exception: + models = [] + if not models: + return [{"id": self.model_path, "object": "model", "owned_by": "local"}] + return list(models) diff --git a/local_llm_kit/mcp.py b/local_llm_kit/mcp.py new file mode 100644 index 0000000..c1a3e44 --- /dev/null +++ b/local_llm_kit/mcp.py @@ -0,0 +1,862 @@ +""" +Model Context Protocol (MCP) client for local-llm-kit. + +MCP lets a host discover and call tools exposed by *servers* (filesystem, +git, sqlite, fetch, browsers, company APIs, ...). This module is a small +**stdlib-only** client so ``local-llm-kit`` can act as an MCP host without +depending on the official ``mcp`` SDK or pulling anything into the light +core. Discovered tools are converted to OpenAI ``tools`` specs, so they +drop straight into :meth:`local_llm_kit.LLM.chat` / +:meth:`local_llm_kit.LLM.add_mcp_server`. + +Two transports are supported: + +``stdio`` + Launch a local server as a subprocess (``command`` + ``args``) and speak + newline-delimited JSON-RPC over its stdin/stdout. This is the transport + used by virtually every local MCP server (``npx @modelcontextprotocol/...``, + ``uvx mcp-server-...``, ``python -m my_server``). A local process may + itself use the network; transport alone does not establish offline use. + +``http`` + POST JSON-RPC to a Streamable HTTP endpoint (``url``). Responses may be + a plain JSON body or a request-scoped ``text/event-stream``. + +Example:: + + from local_llm_kit import LLM + from local_llm_kit.mcp import MCPServer + + with MCPServer("fs", command="npx", args=["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]) as srv: + print([t.name for t in srv.tools()]) + llm = LLM(model_path="...") + llm.add_mcp_server(srv) # registers srv's tools on the LLM + llm.chat([{"role": "user", "content": "List the files in /tmp"}]) + +Notes / compatibility: + + - The default uses a legacy initialize handshake. Explicit + protocol_version="2026-07-28" uses stateless server/discover and metadata. + Unsupported revisions fail clearly. + - Only the tools surface is exposed; resources/prompts, subscriptions, OAuth + and interactive multi-round requests are outside this client subset. + +""" + +from __future__ import annotations + +import base64 +import json +import logging +import math +import os +import queue +import re +import subprocess +import threading +import time +import urllib.error +import urllib.request +from typing import Any, Dict, Iterable, List, Optional, Sequence + +logger = logging.getLogger(__name__) + +__all__ = [ + "MCPError", + "MCPProtocolError", + "MCPToolError", + "MCPTool", + "MCPServer", + "DEFAULT_PROTOCOL_VERSION", + "SUPPORTED_PROTOCOL_VERSIONS", + "mcp_tools_to_openai", + "sanitize_tool_name", +] + +#: Protocol revision we ask for by default. Servers reply with the revision +#: they intend to use (older servers are widely deployed, so we request a +#: broadly supported revision and adapt to the answer). Override per server +#: with ``MCPServer(..., protocol_version="...")``. +DEFAULT_PROTOCOL_VERSION = "2025-06-18" + +#: Revisions this client understands (used only for a friendly log line). +SUPPORTED_PROTOCOL_VERSIONS = ("2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25", "2026-07-28") + +#: Sent as ``clientInfo`` during initialize. +CLIENT_NAME = "local-llm-kit" + +#: Default request timeout in seconds (per JSON-RPC round trip). +DEFAULT_TIMEOUT = 30.0 + +#: OpenAI function names must match this charset; MCP names are freer. +_NAME_ALLOWED = re.compile(r"[^A-Za-z0-9_-]") + + +class MCPError(Exception): + """Base class for all MCP client errors.""" + + +class MCPProtocolError(MCPError): + """Transport failed, the peer died, or a JSON-RPC error was returned.""" + + def __init__(self, message: str, code: Optional[int] = None, data: Any = None) -> None: + super().__init__(message) + self.code = code + self.data = data + + +class MCPToolError(MCPError): + """A ``tools/call`` returned ``isError: true`` or produced unusable output.""" + + +def sanitize_tool_name(name: str) -> str: + """Return *name* using only characters OpenAI function names allow. + + Invalid characters become ``_``; an empty result becomes ``"tool"``. + """ + cleaned = _NAME_ALLOWED.sub("_", str(name or "").strip()) + return cleaned or "tool" + + +class MCPTool: + """A tool advertised by an MCP server (already schema-normalized).""" + + def __init__( + self, + name: str, + description: str = "", + input_schema: Optional[Dict[str, Any]] = None, + server: Optional[str] = None, + ) -> None: + if not isinstance(name, str) or not name.strip(): + raise ValueError("MCP tool 'name' must be a non-empty string.") + self.name = name + self.description = description or "" + self.input_schema = input_schema if isinstance(input_schema, dict) else {} + self.server = server + + @classmethod + def from_wire(cls, data: Dict[str, Any], server: Optional[str] = None) -> "MCPTool": + """Build a tool from a ``tools/list`` entry.""" + if not isinstance(data, dict): + raise MCPProtocolError( + "tools/list entry must be an object, got %r" % type(data).__name__ + ) + name = data.get("name") + if not isinstance(name, str) or not name.strip(): + raise MCPProtocolError("tools/list entry is missing a valid 'name'.") + schema = data.get("inputSchema", data.get("input_schema", {})) + if not isinstance(schema, dict): + raise MCPProtocolError("MCP inputSchema must be an object.") + description = data.get("description") or data.get("title") or "" + return cls( + name=name, + description=str(description), + input_schema=schema if isinstance(schema, dict) else {}, + server=server, + ) + + def to_openai(self, name: Optional[str] = None) -> Dict[str, Any]: + """Convert to an OpenAI ``tools`` entry. + + ``parameters`` is the MCP ``inputSchema`` verbatim; when a server omits + it we emit an empty object schema so the model still sees the tool. + """ + params = self.input_schema or {"type": "object", "properties": {}} + return { + "type": "function", + "function": { + "name": sanitize_tool_name(name or self.name), + "description": self.description, + "parameters": params, + }, + } + + def __repr__(self) -> str: # pragma: no cover - debug helper + return "MCPTool(name=%r, server=%r)" % (self.name, self.server) + + +def mcp_tools_to_openai( + tools: Iterable[MCPTool], prefix: Optional[str] = None +) -> List[Dict[str, Any]]: + """Convert MCP tools to OpenAI specs, optionally namespacing ``prefix__name``.""" + specs: List[Dict[str, Any]] = [] + for t in tools: + qualified = "%s__%s" % (prefix, t.name) if prefix else t.name + specs.append(t.to_openai(qualified)) + return specs + + +class _StdioTransport: + """Newline-delimited JSON-RPC over a subprocess' stdin/stdout.""" + + def __init__( + self, + command: str, + args: Optional[Sequence[str]] = None, + env: Optional[Dict[str, str]] = None, + cwd: Optional[str] = None, + ) -> None: + if not isinstance(command, str) or not command.strip(): + raise ValueError("MCP stdio command must be a non-empty string.") + self.command = command + self.args = [str(a) for a in (args or [])] + self.cwd = cwd + merged_env = dict(os.environ) + if env: + merged_env.update({str(k): str(v) for k, v in env.items()}) + self.env = merged_env + self._proc: Optional[subprocess.Popen] = None + self._lines: "queue.Queue[Any]" = queue.Queue() + self._reader: Optional[threading.Thread] = None + self._stderr_tail: List[str] = [] + self._stderr_thread: Optional[threading.Thread] = None + + # -- lifecycle -------------------------------------------------------- + def start(self) -> None: + if self._proc is not None and self._proc.poll() is None: + return + try: + self._proc = subprocess.Popen( + [self.command] + self.args, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=self.env, + cwd=self.cwd, + text=True, + bufsize=1, + ) + except FileNotFoundError as exc: + raise MCPError("MCP server command not found: %r" % self.command) from exc + except OSError as exc: + raise MCPError("could not start MCP server %r: %s" % (self.command, exc)) from exc + # Ignore SIGPIPE-style BrokenPipeError on Windows/POSIX alike. + self._reader = threading.Thread(target=self._read_stdout, daemon=True) + self._reader.start() + self._stderr_thread = threading.Thread(target=self._read_stderr, daemon=True) + self._stderr_thread.start() + + def _read_stdout(self) -> None: + proc = self._proc + if proc is None or proc.stdout is None: + return + try: + for line in proc.stdout: + line = line.strip() + if not line: + continue + try: + self._lines.put(json.loads(line)) + except json.JSONDecodeError: + logger.debug("MCP server emitted non-JSON stdout: %r", line[:200]) + except (ValueError, OSError): # pipe closed + pass + finally: + self._lines.put(_EOF) + + def _read_stderr(self) -> None: + proc = self._proc + if proc is None or proc.stderr is None: + return + try: + for line in proc.stderr: + self._stderr_tail.append(line.rstrip("\n")) + if len(self._stderr_tail) > 50: + del self._stderr_tail[: len(self._stderr_tail) - 50] + except (ValueError, OSError): + pass + + def send(self, message: Dict[str, Any]) -> None: + proc = self._proc + if proc is None or proc.stdin is None or proc.poll() is not None: + raise MCPProtocolError( + "MCP server is not running (command=%r).%s" % (self.command, self._stderr_hint()) + ) + try: + proc.stdin.write(json.dumps(message) + "\n") + proc.stdin.flush() + except (BrokenPipeError, OSError, ValueError) as exc: + raise MCPProtocolError( + "MCP server closed its input (command=%r).%s" % (self.command, self._stderr_hint()) + ) from exc + + def recv(self, timeout: float) -> Optional[Dict[str, Any]]: + """Return the next message, or ``None`` on timeout.""" + try: + item = self._lines.get(timeout=timeout) + except queue.Empty: + return None + if item is _EOF: + raise MCPProtocolError( + "MCP server exited or closed stdout (command=%r).%s" + % (self.command, self._stderr_hint()) + ) + return item if isinstance(item, dict) else None + + def _stderr_hint(self) -> str: + tail = [ln for ln in self._stderr_tail if ln.strip()] + if not tail: + return "" + return " Server stderr (last %d lines):\n%s" % (len(tail), "\n".join(tail[-10:])) + + def close(self) -> None: + proc = self._proc + self._proc = None + if proc is None: + return + # Order matters: close stdin and stop the child first, then let the + # reader threads observe EOF before closing their pipes. Closing a + # pipe while another thread is blocked reading it can deadlock. + try: + if proc.stdin is not None: + proc.stdin.close() + except OSError: + pass + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: # pragma: no cover - defensive + pass + for thread in (self._reader, self._stderr_thread): + if thread is not None: + thread.join(timeout=2) + for stream in (proc.stdout, proc.stderr): + try: + if stream is not None: + stream.close() + except OSError: + pass + + @property + def session_id(self) -> Optional[str]: + return None + + def set_session_id(self, value: Optional[str]) -> None: # pragma: no cover - stdio ignores + pass + + +class _HttpTransport: + """Streamable HTTP JSON-RPC (JSON body or request-scoped SSE).""" + + def __init__( + self, + url: str, + headers: Optional[Dict[str, str]] = None, + timeout: float = DEFAULT_TIMEOUT, + ) -> None: + if not isinstance(url, str) or not url.strip(): + raise ValueError("MCP http url must be a non-empty string.") + if not url.startswith(("http://", "https://")): + raise ValueError("MCP http url must start with http:// or https://, got %r" % url) + self.url = url + self.headers = dict(headers or {}) + self.timeout = timeout + self._session_id: Optional[str] = None + + def start(self) -> None: # nothing to spawn + return None + + def send(self, message: Dict[str, Any]) -> None: + raise MCPProtocolError("HTTP transport does not use send(); use post().") + + def recv(self, timeout: float) -> Optional[Dict[str, Any]]: # pragma: no cover - unused + return None + + @property + def session_id(self) -> Optional[str]: + return self._session_id + + def set_session_id(self, value: Optional[str]) -> None: + self._session_id = value + + def post(self, message: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """Read only through the matching result; SSE connections may remain open.""" + headers = { + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + "User-Agent": "%s/%s" % (CLIENT_NAME, _version()), + "MCP-Protocol-Version": getattr(self, "protocol_version", DEFAULT_PROTOCOL_VERSION), + } + headers.update(self.headers) + if getattr(self, "protocol_version", "") == "2026-07-28": + headers["Mcp-Method"] = message["method"] + name = (message.get("params") or {}).get("name") + if isinstance(name, str): + safe = ( + name.strip() == name + and all(32 <= ord(char) <= 126 for char in name) + and not name.startswith("=?base64?") + ) + headers["Mcp-Name"] = ( + name + if safe + else "=?base64?%s?=" % base64.b64encode(name.encode()).decode("ascii") + ) + if self._session_id: + headers["Mcp-Session-Id"] = self._session_id + req = urllib.request.Request( + self.url, data=json.dumps(message).encode("utf-8"), headers=headers, method="POST" + ) + deadline = time.monotonic() + self.timeout + try: + with urllib.request.urlopen(req, timeout=self.timeout) as resp: + sid = resp.headers.get("Mcp-Session-Id") + if sid: + self._session_id = sid + content_type = (resp.headers.get("Content-Type") or "").lower() + if "text/event-stream" in content_type and "id" in message: + data_lines = [] + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("MCP HTTP request deadline expired.") + # urllib has no public response deadline API. Apply the remaining + # budget to its socket when available, in addition to the loop check. + socket = getattr( + getattr(getattr(resp, "fp", None), "raw", None), "_sock", None + ) + if socket is not None: + socket.settimeout(remaining) + raw = resp.readline() + if not raw: + return ( + _sse_match("\n".join(data_lines), message["id"]) + if data_lines + else None + ) + line = raw.decode("utf-8", "replace").rstrip("\r\n") + if not line: + found = _sse_match("\n".join(data_lines), message["id"]) + data_lines = [] + if found is not None: + return found + elif line.startswith("data:"): + data_lines.append(line[5:].lstrip(" ")) + payload = resp.read().decode("utf-8", "replace") + except urllib.error.HTTPError as exc: + try: + detail = exc.read(500).decode("utf-8", "replace") + finally: + exc.close() + raise MCPProtocolError( + "MCP HTTP request failed: HTTP %s %s" % (exc.code, detail) + ) from exc + except (urllib.error.URLError, OSError, TimeoutError) as exc: + raise MCPProtocolError("MCP HTTP request to %s failed: %s" % (self.url, exc)) from exc + if not payload.strip(): + return None + try: + parsed = json.loads(payload) + except json.JSONDecodeError as exc: + raise MCPProtocolError("MCP HTTP server returned invalid JSON.") from exc + selected = self._select(parsed, message.get("id")) + if selected is not None and "id" in message and selected.get("id") != message["id"]: + raise MCPProtocolError("MCP HTTP response id does not match the request.") + return selected + + @staticmethod + def _select(parsed: Any, want_id: Any) -> Optional[Dict[str, Any]]: + if isinstance(parsed, list): # batch + for item in parsed: + if isinstance(item, dict) and item.get("id") == want_id: + return item + return None + return parsed if isinstance(parsed, dict) else None + + def close(self) -> None: + if not self._session_id: + return + headers = { + "Accept": "application/json, text/event-stream", + "User-Agent": "%s/%s" % (CLIENT_NAME, _version()), + "Mcp-Session-Id": self._session_id, + "MCP-Protocol-Version": getattr(self, "protocol_version", DEFAULT_PROTOCOL_VERSION), + } + headers.update(self.headers) + request = urllib.request.Request(self.url, headers=headers, method="DELETE") + try: + urllib.request.urlopen(request, timeout=min(self.timeout, 5.0)).close() + except Exception: # Teardown is best-effort when the server has gone away. + pass + finally: + self._session_id = None + + +def _sse_match(blob: str, want_id: Any) -> Optional[Dict[str, Any]]: + try: + parsed = json.loads(blob) + except json.JSONDecodeError: + return None + if isinstance(parsed, dict) and parsed.get("id") == want_id: + return parsed + return None + + +class _EofSentinel: + """Sentinel pushed onto the stdio queue when the server's stdout closes.""" + + def __repr__(self) -> str: # pragma: no cover - debug helper + return "" + + +_EOF = _EofSentinel() + + +def _version() -> str: + try: + from . import __version__ + + return str(__version__) + except Exception: # pragma: no cover - always importable in practice + return "0" + + +class MCPServer: + """A connection to one MCP server plus the tools it advertises. + + Provide exactly one of ``command`` (stdio) or ``url`` (Streamable HTTP). + """ + + def __init__( + self, + name: str, + command: Optional[str] = None, + args: Optional[Sequence[str]] = None, + url: Optional[str] = None, + env: Optional[Dict[str, str]] = None, + cwd: Optional[str] = None, + headers: Optional[Dict[str, str]] = None, + timeout: float = DEFAULT_TIMEOUT, + protocol_version: str = DEFAULT_PROTOCOL_VERSION, + ) -> None: + if not isinstance(name, str) or not name.strip(): + raise ValueError("MCP server 'name' must be a non-empty string.") + if bool(command) == bool(url): + raise ValueError("Provide exactly one of 'command' (stdio) or 'url' (http).") + self.name = name.strip() + if ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not math.isfinite(timeout) + or timeout <= 0 + ): + raise ValueError("MCP timeout must be a finite positive number.") + self.timeout = float(timeout) + if protocol_version not in SUPPORTED_PROTOCOL_VERSIONS: + raise ValueError("Unsupported MCP protocol version: %r" % protocol_version) + self.protocol_version = protocol_version + self.server_info: Dict[str, Any] = {} + self.instructions: str = "" + self._tools: Optional[List[MCPTool]] = None + self._lock = threading.RLock() + self._opened = False + self._next_id = 0 + self._server_request_handler = None + if command: + self.transport: Any = _StdioTransport(command, args=args, env=env, cwd=cwd) + self.transport_kind = "stdio" + else: + self.transport = _HttpTransport(url or "", headers=headers, timeout=self.timeout) + self.transport_kind = "http" + self.transport.protocol_version = protocol_version + + # -- lifecycle -------------------------------------------------------- + def open(self) -> "MCPServer": + """Start the transport and perform the (best-effort) initialize.""" + if self._opened: + return self + self.transport.start() + self._opened = True + try: + self.initialize() + except MCPProtocolError: + self.close() + raise + return self + + def close(self) -> None: + if not self._opened: + return + self._opened = False + try: + self.transport.close() + finally: + self._tools = None + + def __enter__(self) -> "MCPServer": + return self.open() + + def __exit__(self, *exc: Any) -> None: + self.close() + + @property + def closed(self) -> bool: + return not self._opened + + # -- JSON-RPC --------------------------------------------------------- + def _rpc_id(self) -> int: + with self._lock: + self._next_id += 1 + return self._next_id + + def request(self, method: str, params: Optional[Dict[str, Any]] = None) -> Any: + """Send a JSON-RPC request and return its ``result`` (raises on error).""" + if not self._opened: + raise MCPProtocolError("MCP server %r is not open; call open() first." % self.name) + message: Dict[str, Any] = {"jsonrpc": "2.0", "id": self._rpc_id(), "method": method} + if self.protocol_version == "2026-07-28": + params = dict(params or {}) + meta = dict(params.get("_meta") or {}) + meta.update( + { + "io.modelcontextprotocol/protocolVersion": self.protocol_version, + "io.modelcontextprotocol/clientInfo": { + "name": CLIENT_NAME, + "version": _version(), + }, + "io.modelcontextprotocol/clientCapabilities": {}, + } + ) + params["_meta"] = meta + if params is not None: + message["params"] = params + with self._lock: + if self.transport_kind == "http": + response = self._http_roundtrip(message) + else: + self.transport.send(message) + response = self._await_response(message["id"]) + return self._result_of(method, response) + + def notify(self, method: str, params: Optional[Dict[str, Any]] = None) -> None: + """Send a JSON-RPC notification (no response expected).""" + if not self._opened: + raise MCPProtocolError("MCP server %r is not open; call open() first." % self.name) + message: Dict[str, Any] = {"jsonrpc": "2.0", "method": method} + if params is not None: + message["params"] = params + with self._lock: + if self.transport_kind == "http": + self.transport.post(message) + else: + self.transport.send(message) + + def _await_response(self, want_id: Any) -> Optional[Dict[str, Any]]: + deadline = time.monotonic() + self.timeout + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise MCPProtocolError("MCP request deadline expired for server %r." % self.name) + message = self.transport.recv(remaining) + if message is None: + raise MCPProtocolError( + "Timed out after %ss waiting for MCP server %r." % (self.timeout, self.name) + ) + if message.get("id") == want_id and ("result" in message or "error" in message): + return message + self._handle_unsolicited(message) + + def _http_roundtrip(self, message: Dict[str, Any]) -> Optional[Dict[str, Any]]: + if message.get("id") is None: + self.transport.post(message) + return None + response = self.transport.post(message) + if response is None: + raise MCPProtocolError( + "MCP HTTP server %r returned no response for %s." + % (self.name, message.get("method")) + ) + return response + + def _handle_unsolicited(self, message: Dict[str, Any]) -> None: + """Handle server->client requests / notifications we didn't ask for.""" + if "id" in message and "method" in message: + # A server-initiated request (e.g. sampling). Reply so it is not left hanging. + try: + self.transport.send( + { + "jsonrpc": "2.0", + "id": message.get("id"), + "error": {"code": -32601, "message": "Method not supported by client"}, + } + ) + except MCPProtocolError: + pass + # Notifications are ignored. + + @staticmethod + def _result_of(method: str, response: Optional[Dict[str, Any]]) -> Any: + if response is None: + return None + error = response.get("error") + if error: + if isinstance(error, dict): + message = error.get("message", "unknown error") + raise MCPProtocolError( + "MCP %s failed: %s" % (method, message), + code=error.get("code"), + data=error.get("data"), + ) + raise MCPProtocolError("MCP %s failed: %s" % (method, error)) + return response.get("result") + + # -- protocol operations ---------------------------------------------- + def initialize(self) -> Dict[str, Any]: + """Negotiate the selected legacy or stateless tools protocol.""" + if self.protocol_version == "2026-07-28": + result = self.request("server/discover") + if not isinstance(result, dict) or self.protocol_version not in result.get( + "supportedVersions", [] + ): + raise MCPProtocolError( + "Server did not advertise the requested stateless MCP revision." + ) + self.instructions = str(result.get("instructions") or "") + self.server_info = (result.get("_meta") or {}).get( + "io.modelcontextprotocol/serverInfo", {} + ) + return result + params = { + "protocolVersion": self.protocol_version, + "capabilities": {}, + "clientInfo": {"name": CLIENT_NAME, "version": _version()}, + } + try: + result = self.request("initialize", params) or {} + except MCPProtocolError as exc: + # Method-not-found (-32601) or a stateless server that answers with + # a bare error: continue, since tools/* may still work. + if exc.code == -32601: + logger.debug("MCP server %r has no initialize; continuing.", self.name) + return {} + raise + if isinstance(result, dict): + self.server_info = result.get("serverInfo") or {} + self.instructions = str(result.get("instructions") or "") + agreed = result.get("protocolVersion") + if isinstance(agreed, str) and self.transport_kind == "http": + self.transport.protocol_version = agreed + if agreed and (agreed not in SUPPORTED_PROTOCOL_VERSIONS or agreed == "2026-07-28"): + raise MCPProtocolError( + "Server negotiated an unsupported legacy revision: %s" % agreed + ) + try: + self.notify("notifications/initialized") + except MCPProtocolError: + pass + return result if isinstance(result, dict) else {} + + def list_tools(self) -> List[MCPTool]: + """Return the server's tools (cached until :meth:`refresh_tools`).""" + with self._lock: + if self._tools is not None: + return list(self._tools) + tools: List[MCPTool] = [] + cursor: Optional[str] = None + seen_cursors = set() + while True: + params: Dict[str, Any] = {} + if cursor: + params["cursor"] = cursor + result = self.request("tools/list", params or None) or {} + raw = result.get("tools") if isinstance(result, dict) else None + if not isinstance(raw, list): + raise MCPProtocolError( + "MCP server %r returned an invalid tools/list result." % self.name + ) + for entry in raw: + tools.append(MCPTool.from_wire(entry, server=self.name)) + cursor = result.get("nextCursor") if isinstance(result, dict) else None + if not cursor or cursor in seen_cursors: + break + seen_cursors.add(cursor) + with self._lock: + self._tools = tools + return list(tools) + + def refresh_tools(self) -> List[MCPTool]: + """Drop the cache and re-fetch ``tools/list``.""" + with self._lock: + self._tools = None + return self.list_tools() + + def tools(self) -> List[MCPTool]: + """Alias for :meth:`list_tools`.""" + return self.list_tools() + + def call_tool(self, name: str, arguments: Optional[Dict[str, Any]] = None) -> str: + """Call one tool and flatten its MCP content blocks to text. + + Raises: + MCPToolError: when the server reports ``isError`` or no usable + content is returned. + """ + if not isinstance(name, str) or not name.strip(): + raise ValueError("tool name must be a non-empty string.") + if arguments is not None and not isinstance(arguments, dict): + raise TypeError("MCP tool arguments must be a dictionary or None.") + args = {} if arguments is None else arguments + result = self.request("tools/call", {"name": name, "arguments": args}) or {} + if not isinstance(result, dict): + raise MCPToolError("MCP tool %r returned an unexpected result." % name) + text = _flatten_content(result.get("content"), result.get("structuredContent")) + if result.get("isError"): + raise MCPToolError(text or ("MCP tool %r reported an error." % name)) + if not text: + raise MCPToolError("MCP tool %r returned no content." % name) + return text + + def to_openai_tools(self, prefix: Optional[str] = None) -> List[Dict[str, Any]]: + """All of this server's tools as OpenAI ``tools`` specs.""" + return mcp_tools_to_openai(self.list_tools(), prefix=prefix) + + def to_dict(self) -> Dict[str, Any]: + base: Dict[str, Any] = {"name": self.name, "transport": self.transport_kind} + if self.transport_kind == "stdio": + base["command"] = self.transport.command + base["args"] = list(self.transport.args) + else: + base["url"] = self.transport.url + base["server_info"] = dict(self.server_info) + base["tools"] = [t.name for t in (self._tools or [])] + return base + + def __repr__(self) -> str: # pragma: no cover - debug helper + return "MCPServer(name=%r, transport=%s)" % (self.name, self.transport_kind) + + +def _flatten_content(content: Any, structured: Any = None) -> str: + """Flatten MCP ``content`` blocks into a single string.""" + parts: List[str] = [] + if isinstance(content, list): + for block in content: + if not isinstance(block, dict): + continue + btype = block.get("type") + if btype == "text": + text = block.get("text") + if isinstance(text, str): + parts.append(text) + elif btype in ("image", "audio"): + mime = block.get("mimeType") or block.get("mime_type") or "unknown" + parts.append("[%s: %s]" % (btype, mime)) + elif btype in ("resource", "resource_link"): + uri = block.get("uri") or (block.get("resource") or {}).get("uri") + parts.append("[resource: %s]" % (uri or "unknown")) + else: + # Unknown block type: keep something rather than dropping it. + parts.append(json.dumps(block, default=str)) + elif isinstance(content, str): + parts.append(content) + if not parts and structured is not None: + try: + return json.dumps(structured, default=str) + except (TypeError, ValueError): + return str(structured) + return "\n".join(part for part in parts if part) diff --git a/local_llm_kit/memory.py b/local_llm_kit/memory.py index c8170c8..ea128e4 100644 --- a/local_llm_kit/memory.py +++ b/local_llm_kit/memory.py @@ -84,26 +84,52 @@ def clear(self) -> None: self.messages = [] def _truncate_if_needed(self) -> None: - """Truncate message history if it exceeds the context window.""" + """Truncate message history if it exceeds the context window. + + Tool exchanges are removed atomically: an assistant message carrying + ``tool_calls``/``function_call`` is always dropped together with its + following ``tool`` result messages, so truncation never strands a + call without its results (or results without their call). + """ total_tokens = self._count_tokens(self.messages) if total_tokens <= self.context_window: return - # Keep removing oldest messages until we're under the token limit + # Keep removing oldest exchanges until we're under the token limit while total_tokens > self.context_window and len(self.messages) > 2: # Always keep the system message if present start_idx = 1 if self.messages and self.messages[0].get("role") == "system" else 0 - # Remove the oldest non-system message + # Remove the oldest non-system message plus any tool results + # that belong to the same exchange. if start_idx < len(self.messages): - removed_msg = self.messages.pop(start_idx) - total_tokens -= self._count_message_tokens(removed_msg) + end_idx = self._exchange_end(self.messages, start_idx) + removed = self.messages[start_idx:end_idx] + del self.messages[start_idx:end_idx] + total_tokens -= sum(self._count_message_tokens(msg) for msg in removed) # If still over limit, add a summary message and remove more if total_tokens > self.context_window: self._summarize_history() + @staticmethod + def _exchange_end(messages: List[Dict[str, Any]], start: int) -> int: + """Exclusive end of the tool exchange starting at ``start``. + + An assistant message with ``tool_calls``/``function_call`` owns the + consecutive ``tool``/``function`` result messages that follow it; + anything else is a single-message exchange. + """ + end = start + 1 + first = messages[start] + if first.get("role") == "assistant" and ( + first.get("tool_calls") or first.get("function_call") + ): + while end < len(messages) and messages[end].get("role") in ("tool", "function"): + end += 1 + return end + def _count_tokens(self, messages: List[Dict[str, Any]]) -> int: """ Count tokens in a list of messages. @@ -216,14 +242,19 @@ def _summarize_history(self) -> None: else: remaining_messages = self.messages - # Keep the most recent messages (last 4 turns = 8 messages) + # Keep the most recent messages (last 4 turns = 8 messages), but + # never start inside a tool exchange: expand backwards over leading + # tool results to include their owning assistant message. keep_count = min(8, max(2, len(remaining_messages) // 2)) - recent_messages = remaining_messages[-keep_count:] if keep_count > 0 else [] + start = max(0, len(remaining_messages) - keep_count) + while start > 0 and remaining_messages[start].get("role") in ("tool", "function"): + start -= 1 + recent_messages = remaining_messages[start:] # Create a simple summary message summary_message = { "role": "system", - "content": f"[Previous conversation history summarized: {len(remaining_messages) - keep_count} messages omitted]", + "content": f"[Previous conversation history summarized: {start} messages omitted]", } # Rebuild message list diff --git a/local_llm_kit/models.py b/local_llm_kit/models.py index 2b50f7c..dba3d10 100644 --- a/local_llm_kit/models.py +++ b/local_llm_kit/models.py @@ -23,6 +23,7 @@ import os import re import tempfile +import time from pathlib import Path from typing import Any, Dict, List, Optional, Tuple from urllib.parse import quote @@ -342,7 +343,15 @@ def _download_url(url: str, dest_path: str, chunk_size: int = 1024 * 1024) -> st raise RuntimeError( "Truncated download of %s: got %d of %d bytes" % (url, done, total_n) ) - os.replace(part, dest) + for attempt in range(4): + try: + os.replace(part, dest) + break + except PermissionError as exc: + # Windows can briefly lock a destination during competing renames. + if getattr(exc, "winerror", None) not in (5, 32, 33) or attempt == 3: + raise + time.sleep(0.05 * (attempt + 1)) except BaseException as exc: # Drop the partial file so a retry/cache scan never sees it as valid. if part is not None: diff --git a/local_llm_kit/prompt_templates.py b/local_llm_kit/prompt_templates.py new file mode 100644 index 0000000..f6a78fc --- /dev/null +++ b/local_llm_kit/prompt_templates.py @@ -0,0 +1,293 @@ +""" +Prompt template system for local_llm_kit. + +Provides: + * :class:`PromptTemplate` -- lightweight templates with ``{{variable}}`` + and ``{{variable|default}}`` plain-text substitution (only double-brace expressions are replaced). + Values are not escaped; use json.dumps for JSON data. + * :class:`TemplateRegistry` -- in-memory named-template registry with + YAML/JSON file loading. + * Module-level helpers (:func:`register_template`, :func:`get_template`, + :func:`render_template`) and a default registry. + +YAML/JSON loading uses only the standard library by default (``json``). +When the optional ``pyyaml`` package is installed, ``load_file`` also accepts +``.yaml``/``.yml`` files. Loading ``pyyaml`` is deferred to call time so the +light core install is never disturbed. + +Python 3.9 compatible (``typing.Dict``/``List``/``Optional`` house style). +""" + +import json +import re +from typing import Any, Dict, List, Optional + +__all__ = [ + "PromptTemplate", + "TemplateRegistry", + "register_template", + "get_template", + "render_template", + "DEFAULT_REGISTRY", +] + +# Matches {{name}} or {{name|default}}; name is a bare identifier, default is +# everything after the first | up to the closing }}. +_VAR_RE = re.compile(r"\{\{([a-zA-Z_]\w*(?:\|[^}]*)?)\}\}") + + +class PromptTemplate: + """A lightweight prompt template with ``{{variable}}`` substitution. + + Supports two placeholder forms: + + * ``{{name}}`` -- required variable (raises ``KeyError`` if absent). + * ``{{name|fallback}}`` -- optional variable with a default value. + + Unlike ``str.format``, only double-brace expressions are replaced; bare + single braces (common in JSON payloads) are left untouched. + + :param template_str: the raw template text. + :param name: optional human-readable name. + :param description: optional description. + """ + + def __init__( + self, + template_str: str, + name: Optional[str] = None, + description: str = "", + ) -> None: + if not isinstance(template_str, str): + raise TypeError("template_str must be a string.") + if name is not None and (not isinstance(name, str) or not name.strip()): + raise ValueError("Template name must be a non-empty string or None.") + if not isinstance(description, str): + raise TypeError("description must be a string.") + self.template_str = template_str + self.name = name + self.description = description + + def render(self, **kwargs: Any) -> str: + """Render the template, substituting every ``{{...}}`` placeholder.""" + + def _replace(match: "re.Match[str]") -> str: + expr = match.group(1).strip() + if "|" in expr: + name_part, default_part = expr.split("|", 1) + var_name = name_part.strip() + default_val = default_part.strip() + if not var_name: + raise ValueError( + "Empty variable name in template expression: {0!r}".format(match.group(0)) + ) + if var_name in kwargs: + return str(kwargs[var_name]) + return default_val + else: + var_name = expr + if not var_name: + raise ValueError( + "Empty variable name in template expression: {0!r}".format(match.group(0)) + ) + if var_name not in kwargs: + raise KeyError( + "Required template variable '{0}' was not provided".format(var_name) + ) + return str(kwargs[var_name]) + + return _VAR_RE.sub(_replace, self.template_str) + + @classmethod + def from_string( + cls, + template_str: str, + name: Optional[str] = None, + ) -> "PromptTemplate": + """Create a template from a string (alias for the constructor).""" + return cls(template_str, name=name) + + @classmethod + def from_file(cls, path: str, name: Optional[str] = None) -> "PromptTemplate": + """Load a template from a JSON or YAML file. + + The file may contain either a bare template string, or an object with + ``template`` / ``name`` / ``description`` keys. ``.yaml``/``.yml`` + files require the optional ``pyyaml`` extra. + """ + data = _load_template_file(path) + if isinstance(data, str): + return cls(data, name=name or _stem_name(path)) + if isinstance(data, dict): + return cls( + data.get("template", data.get("template_str")), + name=name or data.get("name") or _stem_name(path), + description=data.get("description", ""), + ) + raise ValueError("Template file {0!r} must contain a string or object".format(path)) + + def __repr__(self) -> str: + label = self.name or "" + return "PromptTemplate({0!r})".format(label) + + +class TemplateRegistry: + """In-memory registry mapping names to :class:`PromptTemplate` instances. + + Supports bulk-loading templates from a directory of JSON or YAML files via + :meth:`load_directory`. + """ + + def __init__(self) -> None: + self._templates: Dict[str, PromptTemplate] = {} + + def register( + self, + template_or_name: Any, + template_str: Optional[str] = None, + description: str = "", + ) -> PromptTemplate: + """Register a template. + + Accepts either a :class:`PromptTemplate` instance or a + ``(name, template_str)`` pair. + """ + if isinstance(template_or_name, PromptTemplate): + tmpl = template_or_name + if tmpl.name is None: + raise ValueError("Template must have a name when registered as an object") + self._templates[tmpl.name] = tmpl + else: + name = template_or_name + if not isinstance(name, str) or not name.strip(): + raise ValueError("template name must be a non-empty string") + if template_str is None: + raise ValueError("template_str is required when registering by name") + tmpl = PromptTemplate(template_str, name=name, description=description) + self._templates[name] = tmpl + return tmpl + + def get(self, name: str) -> PromptTemplate: + """Return the template registered under *name* (``KeyError`` if absent).""" + if name not in self._templates: + raise KeyError("Template not found: %s" % name) + return self._templates[name] + + def list_templates(self) -> Dict[str, PromptTemplate]: + """Return a shallow copy of the registered templates.""" + return dict(self._templates) + + def render(self, name: str, **kwargs: Any) -> str: + """Render the named template with *kwargs*.""" + return self.get(name).render(**kwargs) + + def register_from_file(self, path: str, name: Optional[str] = None) -> PromptTemplate: + """Load and register a template from a JSON/YAML file.""" + tmpl = PromptTemplate.from_file(path, name=name) + if tmpl.name is None: + raise ValueError("Template loaded from {0} has no name".format(path)) + self._templates[tmpl.name] = tmpl + return tmpl + + def load_directory(self, directory: str, recursive: bool = False) -> int: + """Load all ``.json``/``.yaml``/``.yml`` template files from a directory. + + Returns the number of templates registered. + """ + import os + + count = 0 + if not os.path.isdir(directory): + raise FileNotFoundError("Not a directory: {0}".format(directory)) + entries: List[str] = [] + if recursive: + for root, _dirs, files in os.walk(directory): + for fname in sorted(files): + entries.append(os.path.join(root, fname)) + else: + for fname in sorted(os.listdir(directory)): + full = os.path.join(directory, fname) + if os.path.isfile(full): + entries.append(full) + + for entry in entries: + if not entry.endswith((".json", ".yaml", ".yml")): + continue + self.register_from_file(entry) + count += 1 + return count + + def __contains__(self, name: str) -> bool: + return name in self._templates + + def __len__(self) -> int: + return len(self._templates) + + +# --------------------------------------------------------------------------- +# Module-level helpers +# --------------------------------------------------------------------------- + +DEFAULT_REGISTRY = TemplateRegistry() + + +def register_template( + name: str, + template_str: str, + description: str = "", +) -> PromptTemplate: + """Register a template in the default module-level registry.""" + return DEFAULT_REGISTRY.register(name, template_str, description=description) + + +def get_template(name: str) -> PromptTemplate: + """Retrieve a template from the default module-level registry.""" + return DEFAULT_REGISTRY.get(name) + + +def render_template(name: str, **kwargs: Any) -> str: + """Render a template from the default module-level registry.""" + return DEFAULT_REGISTRY.render(name, **kwargs) + + +# --------------------------------------------------------------------------- +# File loading helpers (optional-dep safe) +# --------------------------------------------------------------------------- + + +def _stem_name(path: str) -> str: + """Derive a bare template name from a file path's stem.""" + import os + + return os.path.splitext(os.path.basename(path))[0] + + +def _load_template_file(path: str) -> Any: + """Load template content from a JSON or YAML file. + + ``.json`` files always work (stdlib ``json``). ``.yaml`` / ``.yml`` + files require the optional ``pyyaml`` package. + """ + with open(path, "r", encoding="utf-8") as fh: + text = fh.read() + + if path.endswith(".json"): + try: + return json.loads(text) + except json.JSONDecodeError as exc: + raise ValueError("Invalid JSON in {0}: {1}".format(path, exc)) from exc + + if path.endswith((".yaml", ".yml")): + try: + import yaml # type: ignore[import-untyped] + except ImportError as exc: + raise ImportError( + "YAML support requires the optional 'pyyaml' package " + "(pip install 'local-llm-kit[yaml]' or pip install pyyaml)." + ) from exc + data = yaml.safe_load(text) + if data is None: + raise ValueError("Empty YAML file: {0}".format(path)) + return data + + return text diff --git a/local_llm_kit/rag.py b/local_llm_kit/rag.py index 398ab95..67343d2 100644 --- a/local_llm_kit/rag.py +++ b/local_llm_kit/rag.py @@ -51,9 +51,13 @@ def fake_embed(texts): "DEFAULT_SEPARATORS", "DEFAULT_SYSTEM_PROMPT", "chunk_text", + "mmr", "SimpleVectorStore", "retrieve", "build_rag_prompt", + "bm25_scores", + "reciprocal_rank_fusion", + "RAGPipeline", ] logger = logging.getLogger(__name__) @@ -109,6 +113,55 @@ def _cosine_matrix(query: List[float], matrix: List[List[float]]) -> List[float] return [_cosine(query, row) for row in matrix] +def mmr( + query_vec: Sequence[float], + doc_vecs: Sequence[Sequence[float]], + k: int = 4, + lambda_mult: float = 0.5, +) -> List[int]: + """Maximal Marginal Relevance selection: relevant *and* diverse hits. + + Greedily picks ``k`` document indexes balancing query similarity + against similarity to already-picked documents:: + + score(i) = lambda * sim(query, i) - (1 - lambda) * max sim(i, picked) + + Args: + query_vec: Query vector. + doc_vecs: Candidate document vectors. + k: Number of indexes to select (capped at the candidate count). + lambda_mult: Relevance/diversity trade-off in ``[0, 1]``. + ``1.0`` is pure relevance ranking; ``0.0`` is pure diversity. + + Returns: + Selected document indexes in selection order. Deterministic: ties + break towards the lower index. + """ + if isinstance(k, bool) or not isinstance(k, int) or k < 1: + raise ValueError("k must be a positive integer, got %r" % (k,)) + if not isinstance(lambda_mult, (int, float)) or not 0.0 <= lambda_mult <= 1.0: + raise ValueError("lambda_mult must be in [0, 1], got %r" % (lambda_mult,)) + query = _as_vector(list(query_vec), name="query_vec") + docs = [_as_vector(list(row), name="doc_vecs[%d]" % i) for i, row in enumerate(doc_vecs)] + if not docs: + return [] + relevance = [_cosine(query, row) for row in docs] + selected: List[int] = [] + remaining = set(range(len(docs))) + for _ in range(min(k, len(docs))): + best: Optional[int] = None + best_score = 0.0 + for i in sorted(remaining): + diversity = max((_cosine(docs[i], docs[j]) for j in selected), default=0.0) + score = lambda_mult * relevance[i] - (1.0 - lambda_mult) * diversity + if best is None or score > best_score: + best, best_score = i, score + assert best is not None + selected.append(best) + remaining.discard(best) + return selected + + def _as_vector(value: Any, name: str = "vector") -> List[float]: if HAS_NUMPY and np is not None and isinstance(value, np.ndarray): try: @@ -487,7 +540,6 @@ def add( if ids is None: new_ids = [self._next_id() for _ in items] - self.ids.extend([]) # no-op, keeps intent explicit else: new_ids = list(ids) if len(new_ids) != len(items): @@ -510,67 +562,153 @@ def _has_dense_vectors(self) -> bool: """True when every stored entry carries a non-empty vector.""" return bool(self.vectors) and all(len(v) > 0 for v in self.vectors) - def _ranked_hits(self, scores: Sequence[float], k: int) -> List[Dict[str, Any]]: - order = sorted(range(len(scores)), key=lambda i: (scores[i], -i), reverse=True) - hits = [] - for i in order[: min(k, len(order))]: - hits.append( - { - "index": i, - "id": self.ids[i], - "text": self.texts[i], - "metadata": dict(self.metadatas[i]), - "score": float(scores[i]), - } - ) - return hits - - def search( - self, - query: Union[str, Sequence[float]], - k: int = 4, - ) -> List[Dict[str, Any]]: - """Search the store for the ``k`` most similar entries. + def _hit(self, i: int, score: float) -> Dict[str, Any]: + return { + "index": i, + "id": self.ids[i], + "text": self.texts[i], + "metadata": dict(self.metadatas[i]), + "score": float(score), + } - Args: - query: A query string (embedded with the store's ``embed_fn``, - or ranked with TF-IDF when the store has no vectors) or a - raw query vector (dense mode only). - k: Number of hits to return (capped at the store size). + def search(self, query, k=4, lambda_mult=None, *, mode="auto", filter=None): + """Search dense or lexical vectors; opt into BM25, hybrid fusion or MMR. - Returns: - Hits ordered by decreasing score (ties broken by insertion - order, so results are deterministic). Each hit is a dict with - ``index``, ``id``, ``text``, ``metadata`` and ``score`` keys. - ``[]`` when the store is empty. + The default preserves the previous dense/TF-IDF ranking. ``mode`` is + ``auto``, ``dense``, ``lexical`` (BM25), or ``hybrid`` (weighted RRF). + ``filter`` is an exact metadata mapping or a predicate. MMR needs vectors. """ - if k < 1: - raise ValueError("k must be >= 1, got %r" % (k,)) - if not self.texts: + if isinstance(k, bool) or not isinstance(k, int) or k < 1: + raise ValueError("k must be a positive integer.") + if mode not in ("auto", "dense", "lexical", "hybrid"): + raise ValueError("mode must be auto, dense, lexical, or hybrid.") + if lambda_mult is not None and ( + isinstance(lambda_mult, bool) + or not isinstance(lambda_mult, (int, float)) + or not 0 <= lambda_mult <= 1 + ): + raise ValueError("lambda_mult must be in [0, 1].") + candidates = self._filter_candidates(filter) + if not candidates: return [] - if isinstance(query, str): - if self.embed_fn is None and not self._has_dense_vectors(): - # Lexical mode: TF-IDF over raw texts, no embeddings needed. - return self._ranked_hits(_lexical_scores(query, self.texts), k) - if self.embed_fn is None: + if mode == "hybrid": + return self.search_hybrid(query, k=k, lambda_mult=lambda_mult, filter=filter) + lexical = mode == "lexical" or (mode == "auto" and not self._has_dense_vectors()) + if lexical: + if not isinstance(query, str): raise ValueError( - "String queries need an embed_fn: pass a query vector " - "or construct the store with embed_fn=...." + "Lexical search requires a text query; vector queries need stored embeddings." ) + if lambda_mult is not None: + raise ValueError("lambda_mult needs dense vectors (lexical store).") + docs = [self.texts[i] for i in candidates] + scores = bm25_scores(query, docs) if mode == "lexical" else _lexical_scores(query, docs) + order = sorted(range(len(candidates)), key=lambda j: (-scores[j], candidates[j])) + return [self._hit(candidates[j], scores[j]) for j in order[:k]] + if not self._has_dense_vectors(): + raise ValueError("Vector queries need stored embeddings.") + if isinstance(query, str): + if self.embed_fn is None: + raise ValueError("String queries need an embed_fn; pass a query vector instead.") query_vec = _embed_one(self.embed_fn, query) else: query_vec = _as_vector(query, name="query") - if not self._has_dense_vectors(): - raise ValueError( - "Vector queries need stored embeddings: add entries with " - "embeddings=... or construct the store with embed_fn=...." - ) if self.dim is not None and len(query_vec) != self.dim: - raise ValueError( - "Query dimension %d does not match store dimension %d" % (len(query_vec), self.dim) - ) + raise ValueError("Query dimension does not match store dimension.") scores = _cosine_matrix(query_vec, self.vectors) - return self._ranked_hits(scores, k) + order = sorted(candidates, key=lambda i: (-scores[i], i)) + if lambda_mult is not None: + pool = order[: max(k * 5, 25)] + selected = mmr(query_vec, [self.vectors[i] for i in pool], k, lambda_mult) + order = [pool[j] for j in selected] + return [self._hit(i, scores[i]) for i in order[:k]] + + def search_hybrid(self, query, k=4, alpha=0.5, lambda_mult=None, *, filter=None): + """Fuse dense and BM25 ranks with weighted RRF; optionally diversify with MMR. + + ``alpha`` controls dense influence in [0, 1]. Rank fusion avoids mixing + incomparable cosine/BM25 score scales. Text queries need an embed_fn. + """ + if not isinstance(query, str): + raise ValueError("Hybrid search needs a text query.") + if isinstance(k, bool) or not isinstance(k, int) or k < 1: + raise ValueError("k must be a positive integer.") + for name, value in (("alpha", alpha), ("lambda_mult", lambda_mult)): + if value is not None and ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not 0 <= value <= 1 + ): + raise ValueError("%s must be in [0, 1]." % name) + if alpha is None: + raise ValueError("alpha must be in [0, 1].") + candidates = self._filter_candidates(filter) + if not candidates: + return [] + if self.embed_fn is None or not self._has_dense_vectors(): + raise ValueError("Hybrid search needs dense vectors and an embed_fn.") + query_vec = _embed_one(self.embed_fn, query) + if self.dim is not None and len(query_vec) != self.dim: + raise ValueError("Query dimension does not match store dimension.") + dense = _cosine_matrix(query_vec, self.vectors) + lexical = bm25_scores(query, [self.texts[i] for i in candidates]) + dense_order = sorted(candidates, key=lambda i: (-dense[i], i)) + lexical_order = sorted(range(len(candidates)), key=lambda j: (-lexical[j], candidates[j])) + fused = {i: 0.0 for i in candidates} + for weight, order in ( + (alpha, dense_order), + (1 - alpha, [candidates[j] for j in lexical_order]), + ): + for rank, i in enumerate(order, 1): + fused[i] += weight / (60 + rank) + order = sorted(candidates, key=lambda i: (-fused[i], i)) + if lambda_mult is not None: + pool = order[: max(k * 5, 25)] + selected = mmr(query_vec, [self.vectors[i] for i in pool], k, lambda_mult) + order = [pool[j] for j in selected] + return [self._hit(i, fused[i]) for i in order[:k]] + + def delete(self, ids: Sequence[str]) -> int: + """Remove entries matching the given ids. + + Args: + ids: Sequence of entry ids to delete. + + Returns: + Number of entries removed. + """ + if isinstance(ids, str) or any(not isinstance(item, str) for item in ids): + raise TypeError("ids must be a sequence of strings.") + to_delete = set(ids) + keep = [i for i, doc_id in enumerate(self.ids) if doc_id not in to_delete] + if len(keep) == len(self.ids): + return 0 + removed = len(self.ids) - len(keep) + self.texts = [self.texts[i] for i in keep] + self.metadatas = [self.metadatas[i] for i in keep] + self.ids = [self.ids[i] for i in keep] + self.vectors = [self.vectors[i] for i in keep] + return removed + + def _filter_candidates( + self, + filter_spec: Optional[Union[Dict[str, Any], Callable[[Dict[str, Any]], bool]]], + ) -> List[int]: + if filter_spec is None: + return list(range(len(self.texts))) + if not isinstance(filter_spec, dict) and not callable(filter_spec): + raise TypeError("filter must be a dict or callable predicate.") + candidates = [] + for i, meta in enumerate(self.metadatas): + if isinstance(filter_spec, dict): + match = all(meta.get(k) == v for k, v in filter_spec.items()) + elif callable(filter_spec): + match = bool(filter_spec(meta)) + else: + raise TypeError("filter must be a dict or a callable predicate") + if match: + candidates.append(i) + return candidates # -- persistence ---------------------------------------------------- def to_dict(self) -> Dict[str, Any]: @@ -672,6 +810,7 @@ def retrieve( store: SimpleVectorStore, embed_fn: Optional[EmbedFn] = None, k: int = 4, + lambda_mult: Optional[float] = None, ) -> List[Dict[str, Any]]: """Retrieve the ``k`` most relevant docs for ``query``. @@ -681,6 +820,8 @@ def retrieve( embed_fn: Embedding function for string queries. Defaults to the store's own ``embed_fn``. k: Number of hits to return. + lambda_mult: Optional MMR trade-off in ``[0, 1]``; ``None`` + (default) is pure relevance ranking. Returns: Ranked hits (see :meth:`SimpleVectorStore.search`). @@ -689,9 +830,9 @@ def retrieve( if isinstance(query, str): if fn is None: # Lexical mode: TF-IDF over raw texts, no embeddings needed. - return store.search(query, k=k) - return store.search(_embed_one(fn, query), k=k) - return store.search(query, k=k) + return store.search(query, k=k, lambda_mult=lambda_mult) + return store.search(_embed_one(fn, query), k=k, lambda_mult=lambda_mult) + return store.search(query, k=k, lambda_mult=lambda_mult) # --------------------------------------------------------------------------- @@ -775,3 +916,192 @@ def build_rag_prompt( {"role": "system", "content": system}, {"role": "user", "content": user}, ] + + +def bm25_scores( + query: str, + docs: Sequence[str], + k1: float = 1.5, + b: float = 0.75, +) -> List[float]: + """Calculate Okapi BM25 scores for a query across documents. + + Pure standard library, deterministic, zero external dependencies. + + Args: + query: Query string. + docs: List of document strings. + k1: Term frequency saturation parameter. Default: 1.5. + b: Document length normalization parameter. Default: 0.75. + + Returns: + List of float BM25 scores matching docs length. + """ + for name, value in (("k1", k1), ("b", b)): + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(value) + or value < 0 + ): + raise ValueError("%s must be a finite non-negative number." % name) + if b > 1: + raise ValueError("b must be in [0, 1].") + qtokens = _lexical_tokens(query) + if not qtokens or not docs: + return [0.0] * len(docs) + doc_tokens = [_lexical_tokens(d) for d in docs] + n = len(docs) + doc_lens = [len(toks) for toks in doc_tokens] + avgdl = sum(doc_lens) / float(n) if n > 0 else 1.0 + + df: Dict[str, int] = {} + for toks in doc_tokens: + for tok in set(toks): + df[tok] = df.get(tok, 0) + 1 + + scores = [0.0] * n + for q in qtokens: + if q not in df: + continue + nq = df[q] + idf = math.log((n - nq + 0.5) / (nq + 0.5) + 1.0) + for i, toks in enumerate(doc_tokens): + if not toks: + continue + tf = toks.count(q) + if tf <= 0: + continue + denom = tf + k1 * (1.0 - b + b * (doc_lens[i] / avgdl)) + scores[i] += idf * ((tf * (k1 + 1.0)) / denom) + return scores + + +def reciprocal_rank_fusion( + ranked_lists: Sequence[Sequence[int]], + rrf_k: int = 60, +) -> Dict[int, float]: + """Combine multiple ranked lists of document indices using Reciprocal Rank Fusion (RRF). + + Args: + ranked_lists: Sequence of ranked item lists (each item is an index or id). + rrf_k: Smoothing constant. Default: 60. + + Returns: + Dict mapping index/id to fused RRF score. + """ + if isinstance(rrf_k, bool) or not isinstance(rrf_k, int) or rrf_k < 0: + raise ValueError("rrf_k must be a non-negative integer.") + rrf_scores: Dict[int, float] = {} + for rlist in ranked_lists: + for rank, item in enumerate(dict.fromkeys(rlist)): + score = 1.0 / (rrf_k + rank + 1) + rrf_scores[item] = rrf_scores.get(item, 0.0) + score + return rrf_scores + + +class RAGPipeline: + """High-level Retrieval-Augmented Generation pipeline. + + Connects document chunking, indexing (vector/hybrid/BM25), retrieval, + and LLM grounded generation with source citations. + + Args: + llm: A :class:`local_llm_kit.LLM` instance. + store: Optional :class:`SimpleVectorStore`. If omitted, a new store is created. + embed_fn: Optional embedding function. + system_prompt: System prompt instructing citation and grounding. + """ + + def __init__( + self, + llm: Any, + store: Optional[SimpleVectorStore] = None, + embed_fn: Optional[EmbedFn] = None, + system_prompt: Optional[str] = None, + ): + self.llm = llm + self.store = store if store is not None else SimpleVectorStore(embed_fn=embed_fn) + self.system_prompt = system_prompt or DEFAULT_SYSTEM_PROMPT + + def add_documents( + self, + texts: Union[str, Sequence[str]], + metadatas: Optional[Sequence[Optional[Dict[str, Any]]]] = None, + chunk_size: int = 500, + chunk_overlap: int = 50, + ) -> List[str]: + """Chunk and index documents into the vector store. + + Args: + texts: Single text document or list of documents. + metadatas: Optional metadata dicts (one per document). + chunk_size: Character size per chunk. + chunk_overlap: Overlap between consecutive chunks. + + Returns: + List of generated chunk IDs added to the store. + """ + if metadatas is not None and len(metadatas) != ( + 1 if isinstance(texts, str) else len(texts) + ): + raise ValueError("metadatas must contain one entry per input document.") + raw_docs = [texts] if isinstance(texts, str) else list(texts) + if not raw_docs: + return [] + + all_chunks: List[str] = [] + all_metas: List[Dict[str, Any]] = [] + + for idx, doc in enumerate(raw_docs): + doc_meta = ( + dict(metadatas[idx]) + if metadatas and idx < len(metadatas) and metadatas[idx] + else {} + ) + chunks = chunk_text(doc, chunk_size=chunk_size, chunk_overlap=chunk_overlap) + for c_idx, chunk in enumerate(chunks): + all_chunks.append(chunk) + meta = dict(doc_meta) + meta["doc_index"] = idx + meta["chunk_index"] = c_idx + all_metas.append(meta) + + return self.store.add(all_chunks, metadatas=all_metas) + + def query( + self, + question: str, + k: int = 4, + mode: str = "auto", + filter: Optional[Union[Dict[str, Any], Callable[[Dict[str, Any]], bool]]] = None, + **chat_kwargs: Any, + ) -> Dict[str, Any]: + """Retrieve relevant context and generate a grounded, cited answer. + + Args: + question: User question string. + k: Number of chunks to retrieve. + mode: Search mode: ``"auto"`` (default), ``"dense"``, or ``"lexical"``. + filter: Optional metadata filter dict or callable. + **chat_kwargs: Additional kwargs passed to ``llm.chat()``. + + Returns: + Dict containing ``answer``, ``sources`` (retrieved hits), and ``raw_response``. + """ + hits = self.store.search(question, k=k, mode=mode, filter=filter) + messages = build_rag_prompt( + query=question, + docs=hits, + system_prompt=self.system_prompt, + ) + chat_kwargs.setdefault("execute_tools", False) + resp = self.llm.chat(messages=messages, **chat_kwargs) + choices = resp.get("choices", []) + answer = choices[0].get("message", {}).get("content", "") if choices else "" + + return { + "answer": answer, + "sources": hits, + "raw_response": resp, + } diff --git a/local_llm_kit/retry.py b/local_llm_kit/retry.py new file mode 100644 index 0000000..bf718af --- /dev/null +++ b/local_llm_kit/retry.py @@ -0,0 +1,166 @@ +""" +Retry policy for local LLM servers that are slow to become usable. + +The most common local-AI failure is not a rejected request — it is a request +sent too early. A desktop app has not finished binding its port, ``ollama +serve`` is still starting, a model is still being loaded (llama.cpp answers +``503 {"error": {"message": "Loading model"}}`` while it loads), or a server is +briefly overloaded. + +This module holds the shared policy for those cases. It is deliberately small +and dependency-free, and it mirrors the defaults the official OpenAI Python +client uses (two retries, 0.5s initial delay, 8s ceiling, honours +``Retry-After``), because that is the behaviour people already expect from an +OpenAI-shaped client. + +Only transient failures are retried: + +* the connection could not be established or was reset, +* the server answered ``429`` or ``5xx``, +* and, for streaming, nothing had been emitted yet — retrying after a partial + stream would duplicate output. + +Client errors such as ``400`` are never retried. +""" + +import math +import random +import time +import urllib.error +from dataclasses import dataclass +from typing import Optional, Tuple + +__all__ = ["RetryPolicy", "DEFAULT_RETRY", "is_retryable_status", "retry_after_seconds"] + +#: Status codes worth another attempt: rate limits and server-side failures. +RETRYABLE_STATUS = frozenset({408, 409, 425, 429, 500, 502, 503, 504}) + +#: Upper bound applied to a server-supplied ``Retry-After``. A server asking a +#: local client to sleep for minutes is more likely misconfigured than right. +MAX_RETRY_AFTER = 120.0 + + +@dataclass(frozen=True) +class RetryPolicy: + """How many times, and how long, to wait before giving up. + + Args: + max_retries: Additional attempts after the first one. ``0`` disables + retrying entirely and restores single-attempt behaviour. + initial_delay: Seconds before the second attempt. + max_delay: Ceiling for the computed backoff. + jitter: Randomise the delay within ``[delay/2, delay]`` so several + clients starting together do not retry in lockstep. + retry_on_status: Status codes to retry. Defaults to + :data:`RETRYABLE_STATUS`. + """ + + max_retries: int = 2 + initial_delay: float = 0.5 + max_delay: float = 8.0 + jitter: bool = True + retry_on_status: Tuple[int, ...] = tuple(sorted(RETRYABLE_STATUS)) + + def __post_init__(self) -> None: + if isinstance(self.max_retries, bool) or not isinstance(self.max_retries, int): + raise TypeError("max_retries must be an integer.") + if self.max_retries < 0: + raise ValueError("max_retries must be non-negative.") + for name in ("initial_delay", "max_delay"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise TypeError("%s must be a number." % name) + if not math.isfinite(value) or value < 0: + raise ValueError("%s must be non-negative." % name) + if self.max_delay < self.initial_delay: + raise ValueError("max_delay must be >= initial_delay.") + + @property + def enabled(self) -> bool: + return self.max_retries > 0 + + def should_retry_status(self, status: Optional[int]) -> bool: + return status is not None and status in self.retry_on_status + + def delay_for(self, attempt: int, retry_after: Optional[float] = None) -> float: + """Seconds to wait before retry number *attempt* (1-based). + + A server-supplied ``Retry-After`` wins over the computed backoff, + clamped to :data:`MAX_RETRY_AFTER`. + """ + if retry_after is not None and math.isfinite(retry_after) and retry_after >= 0: + return min(float(retry_after), MAX_RETRY_AFTER) + backoff = min(self.initial_delay * (2 ** max(0, attempt - 1)), self.max_delay) + if self.jitter and backoff > 0: + return backoff * (0.5 + random.random() * 0.5) + return backoff + + def sleep(self, attempt: int, retry_after: Optional[float] = None) -> float: + """Sleep as computed by :meth:`delay_for`; returns the delay used.""" + delay = self.delay_for(attempt, retry_after) + if delay > 0: + time.sleep(delay) + return delay + + +#: Default policy. Two retries matches the official OpenAI Python client. +DEFAULT_RETRY = RetryPolicy() + + +def is_retryable_status(status: Optional[int]) -> bool: + """True when *status* is a transient server-side condition.""" + return status is not None and status in RETRYABLE_STATUS + + +def retry_after_seconds(headers: object) -> Optional[float]: + """Parse a ``Retry-After`` header into seconds, or None. + + Only the delta-seconds form is honoured; an HTTP-date is ignored because + local servers do not use it and clock skew makes it unreliable. Accepts any + object with a ``get`` method (``email.message.Message`` from ``urllib``). + """ + getter = getattr(headers, "get", None) + if not callable(getter): + return None + raw = getter("Retry-After") + if raw is None: + return None + text = str(raw).strip() + if not text: + return None + try: + seconds = float(text) + except ValueError: + return None + if not math.isfinite(seconds) or seconds < 0: + return None + return min(seconds, MAX_RETRY_AFTER) + + +def coerce_policy(value: object) -> RetryPolicy: + """Accept a :class:`RetryPolicy`, an int retry count, or None. + + Lets backend constructors take the friendly ``max_retries=3`` form without + giving up the full policy object. + """ + if value is None: + return DEFAULT_RETRY + if isinstance(value, RetryPolicy): + return value + if isinstance(value, bool): + raise TypeError("retry policy must be a RetryPolicy or an int, not a bool.") + if isinstance(value, int): + return RetryPolicy(max_retries=value) + raise TypeError("retry policy must be a RetryPolicy or an int, got %r" % type(value).__name__) + + +def retryable_transport_error(exc: BaseException) -> bool: + """True when *exc* is a connection-level failure worth retrying. + + A refused connection is exactly the "server not up yet" case. Timeouts are + included because a local model's first token can legitimately take longer + than a short client timeout. + """ + if isinstance(exc, urllib.error.URLError): + return True + return isinstance(exc, (ConnectionError, TimeoutError, OSError)) diff --git a/local_llm_kit/server.py b/local_llm_kit/server.py index 8518b08..e354685 100644 --- a/local_llm_kit/server.py +++ b/local_llm_kit/server.py @@ -11,9 +11,11 @@ Endpoints: GET /health - GET /v1/models + GET /v1/models (upstream listing when the LLM exposes one, else the + configured model id) POST /v1/chat/completions (non-stream + SSE stream, tools + response_format) POST /v1/completions (non-stream + SSE stream) + POST /v1/responses (Responses-API subset over the chat engine) POST /v1/embeddings (native llm.embed if present, else offline fallback) Security defaults (see SECURITY review): @@ -33,11 +35,13 @@ """ import argparse +import asyncio import hashlib import inspect import json import math import time +import uuid from typing import Any, Dict, List, Optional __all__ = ["create_app", "run", "main"] @@ -248,6 +252,289 @@ def _coerce_vectors(result: Any, n: int) -> Optional[List[List[float]]]: return vectors +def _responses_content(content: Any) -> Any: + if isinstance(content, str) or content is None: + return content + if not isinstance(content, list): + raise ValueError("Message content must be text or a list of content parts.") + parts = [] + for part in content: + if not isinstance(part, dict): + raise ValueError("Content parts must be objects.") + kind = part.get("type") + if kind in ("input_text", "output_text", "text") and isinstance(part.get("text"), str): + parts.append({"type": "text", "text": part["text"]}) + elif kind == "input_image" and isinstance(part.get("image_url"), str): + parts.append( + { + "type": "image_url", + "image_url": {"url": part["image_url"], "detail": part.get("detail", "auto")}, + } + ) + elif kind == "image_url" and isinstance(part.get("image_url"), (str, dict)): + parts.append(part) + else: + raise ValueError("Unsupported content part: %r" % kind) + return parts + + +def _coerce_responses_input(raw: Any) -> List[Dict[str, Any]]: + """Convert stateless Responses messages and tool exchanges to chat input.""" + if isinstance(raw, str) and raw: + return [{"role": "user", "content": raw}] + if not isinstance(raw, list) or not raw: + raise ValueError("'input' must be a non-empty string or list.") + messages = [] + for item in raw: + if not isinstance(item, dict): + raise ValueError("Each input item must be an object.") + kind = item.get("type", "message") + if kind == "message": + role = item.get("role", "user") + if role not in ("user", "assistant", "system", "developer", "tool"): + raise ValueError("Unsupported input role: %r" % role) + message = {"role": role, "content": _responses_content(item.get("content"))} + for key in ("tool_calls", "tool_call_id", "name"): + if key in item: + message[key] = item[key] + messages.append(message) + elif kind in ("input_text", "input_image"): + messages.append({"role": "user", "content": _responses_content([item])}) + elif kind == "function_call": + if not all(isinstance(item.get(key), str) and item[key] for key in ("call_id", "name")): + raise ValueError("function_call requires name and call_id strings.") + arguments = item.get("arguments", "{}") + if not isinstance(arguments, str): + raise ValueError("function_call arguments must be a JSON string.") + messages.append( + { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": item["call_id"], + "type": "function", + "function": {"name": item["name"], "arguments": arguments}, + } + ], + } + ) + elif kind == "function_call_output": + if not isinstance(item.get("call_id"), str) or not isinstance(item.get("output"), str): + raise ValueError("function_call_output requires call_id and text output strings.") + messages.append( + {"role": "tool", "tool_call_id": item["call_id"], "content": item["output"]} + ) + else: + raise ValueError("Unsupported input item type: %r" % kind) + return messages + + +def _responses_usage(usage: Any) -> Any: + if not isinstance(usage, dict): + return None + return { + "input_tokens": usage.get("prompt_tokens", usage.get("input_tokens", 0)), + "output_tokens": usage.get("completion_tokens", usage.get("output_tokens", 0)), + "total_tokens": usage.get("total_tokens", 0), + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens_details": {"reasoning_tokens": 0}, + } + + +def _responses_object( + message: Dict[str, Any], model: str, status: str = "completed" +) -> Dict[str, Any]: + output = [] + text = message.get("content") + if text is not None: + output.append( + { + "id": "msg_" + uuid.uuid4().hex, + "type": "message", + "role": "assistant", + "status": status, + "content": [ + {"type": "output_text", "text": text, "annotations": [], "logprobs": []} + ], + } + ) + for call in message.get("tool_calls") or []: + function = call["function"] + output.append( + { + "id": "fc_" + uuid.uuid4().hex, + "type": "function_call", + "status": status, + "call_id": call["id"], + "name": function["name"], + "arguments": function["arguments"], + } + ) + return { + "id": "resp_" + uuid.uuid4().hex, + "object": "response", + "created_at": _now(), + "model": model, + "status": status, + "output": output, + "error": None, + "incomplete_details": None, + "usage": None, + "store": False, + "metadata": {}, + "parallel_tool_calls": True, + "tools": [], + "tool_choice": "auto", + } + + +def _responses_events(chunks: Any, model: str): + """Translate chat deltas to the SDK's Responses event and item lifecycle.""" + response = _responses_object({}, model, "in_progress") + output = [] + tools = {} + text_item = None + sequence = 0 + usage = None + finish = "stop" + + def event(kind, **fields): + nonlocal sequence + payload = dict(type=kind, sequence_number=sequence, **fields) + sequence += 1 + return "event: %s\ndata: %s\n\n" % (kind, json.dumps(payload)) + + yield event("response.created", response=dict(response)) + yield event("response.in_progress", response=dict(response)) + try: + if isinstance(chunks, dict): + chunks = [chunks] + for chunk in chunks: + if not isinstance(chunk, dict): + continue + usage = chunk.get("usage") or usage + choices = chunk.get("choices") or [] + if not choices: + continue + choice = choices[0] + finish = choice.get("finish_reason") or finish + delta = choice.get("delta") or choice.get("message") or {} + text = delta.get("content") + if text: + if text_item is None: + text_index = len(output) + text_item = { + "id": "msg_" + uuid.uuid4().hex, + "type": "message", + "role": "assistant", + "status": "in_progress", + "content": [], + } + yield event( + "response.output_item.added", output_index=text_index, item=dict(text_item) + ) + text_item["content"] = [ + {"type": "output_text", "text": "", "annotations": [], "logprobs": []} + ] + output.append(text_item) + yield event( + "response.content_part.added", + item_id=text_item["id"], + output_index=text_index, + content_index=0, + part=dict(text_item["content"][0]), + ) + text_item["content"][0]["text"] += text + yield event( + "response.output_text.delta", + item_id=text_item["id"], + output_index=text_index, + content_index=0, + delta=text, + logprobs=[], + ) + calls = delta.get("tool_calls") or [] + if not calls and delta.get("function_call"): + calls = [{"index": 0, "function": delta["function_call"]}] + for position, call in enumerate(calls): + index = call.get("index", position) + function = call.get("function") or {} + if index not in tools: + item = { + "id": "fc_" + uuid.uuid4().hex, + "type": "function_call", + "status": "in_progress", + "call_id": call.get("id") or "call_" + uuid.uuid4().hex, + "name": function.get("name", ""), + "arguments": "", + } + tools[index] = (len(output), item) + output.append(item) + yield event( + "response.output_item.added", output_index=len(output) - 1, item=dict(item) + ) + output_index, item = tools[index] + if call.get("id"): + item["call_id"] = call["id"] + if function.get("name"): + item["name"] = function["name"] + arguments = function.get("arguments", "") + if arguments: + item["arguments"] += arguments + yield event( + "response.function_call_arguments.delta", + item_id=item["id"], + output_index=output_index, + delta=arguments, + ) + for index, item in enumerate(output): + item["status"] = "incomplete" if finish == "length" else "completed" + if item["type"] == "message": + part = item["content"][0] + yield event( + "response.output_text.done", + item_id=item["id"], + output_index=index, + content_index=0, + text=part["text"], + logprobs=[], + ) + yield event( + "response.content_part.done", + item_id=item["id"], + output_index=index, + content_index=0, + part=part, + ) + else: + yield event( + "response.function_call_arguments.done", + item_id=item["id"], + output_index=index, + arguments=item["arguments"], + name=item["name"], + ) + yield event("response.output_item.done", output_index=index, item=item) + response.update( + output=output, + status="incomplete" if finish == "length" else "completed", + usage=_responses_usage(usage), + ) + if finish == "length": + response["incomplete_details"] = {"reason": "max_output_tokens"} + yield event("response." + response["status"], response=response) + except Exception as exc: + response.update( + output=output, status="failed", error={"code": "server_error", "message": str(exc)} + ) + yield event("response.failed", response=response) + finally: + close = getattr(chunks, "close", None) + if close: + close() + + def _generation_params(body: Dict[str, Any]) -> Dict[str, Any]: """Validate shared chat/completion options before calling the backend.""" from .llm import _normalize_response_format @@ -395,6 +682,40 @@ def _model_id() -> str: return _model_id_for(state["llm"], model_name or model_path) return model_name or model_path or "local-model" + def _model_entries() -> List[Dict[str, Any]]: + """All models for ``GET /v1/models``: upstream listing when an LLM + is already available (injected or previously constructed), else the + single configured model id. Never constructs a model just to answer + this route (previous behaviour for the lazy case, unchanged).""" + entries: List[Dict[str, Any]] = [] + llm_obj = state["llm"] + if llm_obj is not None: + lister = getattr(llm_obj, "list_models", None) + if callable(lister): + try: + listed = lister() + except Exception: + listed = [] + for entry in listed or []: + if isinstance(entry, dict) and entry.get("id"): + item = { + "id": entry["id"], + "object": entry.get("object", "model"), + "created": _now(), + "owned_by": entry.get("owned_by", "local"), + } + entries.append(item) + if not entries: + entries.append( + { + "id": _model_id(), + "object": "model", + "created": _now(), + "owned_by": "local", + } + ) + return entries + def _error(message: str, status: int = 400, err_type: str = "invalid_request_error"): return JSONResponse( status_code=status, @@ -424,17 +745,7 @@ def root(): @app.get("/v1/models") @app.get("/models") def list_models(): - return { - "object": "list", - "data": [ - { - "id": _model_id(), - "object": "model", - "created": _now(), - "owned_by": "local", - } - ], - } + return {"object": "list", "data": _model_entries()} # -- chat completions ---------------------------------------------- @app.post("/v1/chat/completions") @@ -614,6 +925,139 @@ def event_iter(): return StreamingResponse(event_iter(), media_type="text/event-stream") + # -- stateless Responses subset ---------------------------------------- + @app.post("/v1/responses") + @app.post("/responses") + async def responses(request: Request): + try: + body = await request.json() + if not isinstance(body, dict): + raise ValueError("JSON body must be an object.") + for key in ( + "previous_response_id", + "conversation", + "reasoning", + "include", + "truncation", + ): + if key in body and body[key] is not None: + raise ValueError("'%s' is not supported by this stateless server." % key) + for key in ("background", "store"): + if key in body and body[key] is not False: + raise ValueError("'%s' must be false; this server is stateless." % key) + for key in ("stream", "execute_tools", "parallel_tool_calls"): + if key in body and not isinstance(body[key], bool): + raise ValueError("'%s' must be a boolean." % key) + if body.get("execute_tools"): + raise ValueError( + "Responses returns tool calls for the caller to execute; execute_tools is unsupported here." + ) + messages = _coerce_responses_input(body.get("input")) + instructions = body.get("instructions") + if instructions is not None: + if not isinstance(instructions, str): + raise ValueError("'instructions' must be a string.") + messages.insert(0, {"role": "system", "content": instructions}) + tools = body.get("tools", []) + if not isinstance(tools, list): + raise ValueError("'tools' must be a list.") + normalized_tools = [] + for tool in tools: + if not isinstance(tool, dict) or tool.get("type") != "function": + raise ValueError("Only function tools are supported.") + function = tool.get( + "function", {key: value for key, value in tool.items() if key != "type"} + ) + if ( + not isinstance(function, dict) + or not isinstance(function.get("name"), str) + or not function["name"] + ): + raise ValueError("Function tools require a name.") + normalized_tools.append({"type": "function", "function": function}) + tool_choice = body.get("tool_choice", "auto") + if isinstance(tool_choice, dict): + if tool_choice.get("type") != "function" or not tool_choice.get("name"): + raise ValueError("tool_choice must name a function.") + tool_choice = {"type": "function", "function": {"name": tool_choice["name"]}} + elif tool_choice not in ("auto", "none", "required"): + raise ValueError("Unsupported tool_choice.") + converted = dict(body) + if "max_output_tokens" in body: + converted["max_tokens"] = body["max_output_tokens"] + if "text" in body: + text = body["text"] + if not isinstance(text, dict) or set(text) - {"format"}: + raise ValueError("Only text.format is supported.") + fmt = text.get("format", {"type": "text"}) + if not isinstance(fmt, dict): + raise ValueError("text.format must be an object.") + if fmt.get("type") == "json_schema": + if not isinstance(fmt.get("schema"), dict) or not isinstance( + fmt.get("name"), str + ): + raise ValueError("json_schema requires a schema object and name.") + converted["response_format"] = { + "type": "json_schema", + "json_schema": {key: value for key, value in fmt.items() if key != "type"}, + } + elif fmt.get("type") == "json_object": + converted["response_format"] = fmt + elif fmt.get("type") != "text": + raise ValueError("Unsupported text.format type.") + params = _generation_params(converted) + except (TypeError, ValueError) as exc: + return _error(str(exc)) + try: + llm_obj = _get_llm() + except RuntimeError as exc: + return _error(str(exc), status=503, err_type="server_error") + model = _model_id() + if body.get("model") is not None and body["model"] != model: + return _error( + "Model %r is not served here; use %r." % (body["model"], model), status=404 + ) + chat_kwargs = dict( + messages=_coerce_messages(messages), + tools=normalized_tools or None, + tool_choice=tool_choice, + execute_tools=False, + **params, + ) + for key in ("top_p", "seed", "parallel_tool_calls"): + if key in body: + chat_kwargs[key] = body[key] + if body.get("stream", False): + + def chunks(): + result = _call_llm_chat(llm_obj, dict(chat_kwargs, stream=True)) + if isinstance(result, dict): + yield result + else: + yield from result + + return StreamingResponse( + _responses_events(chunks(), model), media_type="text/event-stream" + ) + try: + result = await asyncio.to_thread( + _call_llm_chat, llm_obj, dict(chat_kwargs, stream=False) + ) + choice = result["choices"][0] + message = choice["message"] + _ensure_tool_calls(message) + obj = _responses_object( + message, + model, + "incomplete" if choice.get("finish_reason") == "length" else "completed", + ) + obj["usage"] = _responses_usage(result.get("usage")) + if obj["status"] == "incomplete": + obj["incomplete_details"] = {"reason": "max_output_tokens"} + return JSONResponse(content=obj) + except Exception as exc: + return _error("Response failed: %s" % exc, status=500, err_type="server_error") + # -- embeddings ------------------------------------------------------ @app.post("/v1/embeddings") @app.post("/embeddings") diff --git a/local_llm_kit/structured.py b/local_llm_kit/structured.py new file mode 100644 index 0000000..6295b86 --- /dev/null +++ b/local_llm_kit/structured.py @@ -0,0 +1,266 @@ +""" +Resilient structured JSON generation and zero-dependency JSON auto-repair. + +Local LLMs frequently emit 'almost valid' JSON: +- Markdown fences (`````json ... `````) +- Conversational prefaces and postscripts ('Here is the JSON you requested:') +- Unquoted property keys (``{name: "Alice"}``) +- Single-quoted strings (``{'key': 'value'}``) +- Python literals (``True``, ``False``, ``None``) instead of JSON standards +- Trailing commas (``{"a": 1, "b": 2,}``) +- Truncated braces/brackets at context window boundaries + +This module provides: +1. :func:`repair_json` -- pure standard-library parser/regex pipeline repairing + common local model syntax corruptions without external dependencies. +2. :func:`extract_json` -- robust extraction returning parsed Python dicts/lists. +3. :func:`chat_structured` -- multi-turn self-correcting structured chat loop + that combines native schema enforcement with error-feedback retries. + +Python 3.9+ compatible. +""" + +import ast +import json +import logging +import re +from typing import Any, Callable, Dict, Optional, Sequence, Type, Union + +logger = logging.getLogger(__name__) + +# Regular expressions for repair heuristics +_CODE_FENCE_RE = re.compile(r"```(?:json)?\s*([\s\S]*?)\s*```", re.IGNORECASE) +_TRAILING_COMMA_RE = re.compile(r",\s*([\]}])") +_PYTHON_LITERALS = [ + (re.compile(r"\bTrue\b"), "true"), + (re.compile(r"\bFalse\b"), "false"), + (re.compile(r"\bNone\b"), "null"), +] +_UNQUOTED_KEY_RE = re.compile(r"([,{]\s*)([a-zA-Z_][a-zA-Z0-9_]*)\s*:") + + +def repair_json(text: str) -> str: + """Repair JSON presentation errors without rewriting quoted string values. + + This opt-in output helper is never used to complete executable tool arguments. + It can close missing containers, but never invent an unfinished string/value. + """ + if not isinstance(text, str): + raise TypeError("repair_json expects a string.") + if len(text) > 1024 * 1024: + raise ValueError("JSON output exceeds the 1 MiB repair limit.") + s = text.strip() + if not s: + raise ValueError("JSON output is empty.") + try: + json.loads(s) + return s + except ValueError: + pass + fence = _CODE_FENCE_RE.search(s) + if fence: + s = fence.group(1).strip() + starts = [i for i in (s.find("{"), s.find("[")) if i >= 0] + if not starts: + raise ValueError("No JSON object or array was found.") + s = s[min(starts) :] + # Find the end of the first container, respecting both JSON and Python strings. + stack = [] + quote = None + escaped = False + for index, char in enumerate(s): + if quote: + if escaped: + escaped = False + elif char == "\\": + escaped = True + elif char == quote: + quote = None + elif char in ('"', "'"): + quote = char + elif char in "{[": + stack.append("}" if char == "{" else "]") + elif char in "}]": + if not stack or char != stack.pop(): + raise ValueError("Mismatched JSON containers.") + if not stack: + s = s[: index + 1] + break + if quote: + raise ValueError("Unterminated JSON string; regenerate the output.") + s = s.rstrip() + "".join(reversed(stack)) + try: + return json.dumps(ast.literal_eval(s), allow_nan=False) + except (ValueError, SyntaxError, TypeError, RecursionError): + pass + strings = [] + + def hold(match): + token = match.group() + value = json.loads(token) if token.startswith('"') else ast.literal_eval(token) + strings.append(json.dumps(value)) + return '"@llmk[%d]@"' % (len(strings) - 1) + + masked = re.sub(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^'\\]|\\.)*'", hold, s) + for pattern, replacement in _PYTHON_LITERALS: + masked = pattern.sub(replacement, masked) + masked = _TRAILING_COMMA_RE.sub(r"\1", masked) + masked = _UNQUOTED_KEY_RE.sub(r'\1"\2":', masked) + repaired = re.sub(r'"@llmk\[(\d+)\]@"', lambda match: strings[int(match.group(1))], masked) + json.loads(repaired) + return repaired + + +def extract_json(text: str) -> Any: + """Extract and parse a JSON object or array from raw LLM output. + + Attempts standard ``json.loads()`` first. If decoding fails, applies + :func:`repair_json` heuristics before retrying. + + Args: + text: Raw response string from the model. + + Returns: + Parsed Python dictionary, list, or primitive. + + Raises: + json.JSONDecodeError: If JSON cannot be parsed even after repair attempts. + """ + if not isinstance(text, str): + raise TypeError(f"extract_json expects string, got {type(text).__name__}") + + # Direct fast-path + try: + return json.loads(text.strip()) + except json.JSONDecodeError: + pass + + # Heuristic repair path + repaired = repair_json(text) + return json.loads(repaired) + + +def validate_schema(data: Any, schema: Union[Dict[str, Any], Type, Callable]) -> None: + """Validate all JSON Schema constraints, or a Pydantic v1/v2 model. + + Dictionary schemas require the optional ``structured`` extra. Unsupported + validators are rejected rather than reported as successful validation. + """ + if schema is None: + return + if isinstance(schema, dict): + try: + from jsonschema import validators + except ImportError as exc: + raise ImportError( + 'JSON Schema validation needs pip install "local-llm-kit[structured]".' + ) from exc + validator_class = validators.validator_for(schema) + validator_class.check_schema(schema) + from referencing import Registry + + # No automatic remote schema retrieval in an offline helper. + error = next(validator_class(schema, registry=Registry()).iter_errors(data), None) + if error: + raise ValueError("Schema validation failed: %s" % error.message) + return + validate = getattr(schema, "model_validate", None) or getattr(schema, "parse_obj", None) + if not callable(validate): + raise TypeError("schema must be a JSON Schema dictionary or a Pydantic model class.") + try: + validate(data) + except Exception as exc: + raise ValueError("Schema validation failed: %s" % exc) from exc + + +def chat_structured( + llm: Any, + messages: Sequence[Dict[str, Any]], + schema: Optional[Union[Dict[str, Any], Type, Any]] = None, + max_retries: int = 2, + **kwargs: Any, +) -> Dict[str, Any]: + """Execute a chat completion requiring structured JSON output with self-correction. + + Combines native backend grammar/schema enforcement with automatic JSON repair + and multi-turn validation retries. + + Args: + llm: An :class:`local_llm_kit.LLM` instance. + messages: Conversation messages. + schema: Optional JSON schema dict or Pydantic model for validation. + max_retries: Maximum number of correction turns if the model produces invalid JSON. + **kwargs: Additional options forwarded to ``llm.chat()``. + + Returns: + Parsed and validated JSON data (dict or list). + + Raises: + ValueError: If the model fails to produce valid structured JSON after retries. + """ + if isinstance(max_retries, bool) or not isinstance(max_retries, int) or max_retries < 0: + raise ValueError("max_retries must be a non-negative integer.") + if kwargs.get("stream"): + raise ValueError("chat_structured requires stream=False.") + if not isinstance(messages, (list, tuple)) or any(not isinstance(m, dict) for m in messages): + raise TypeError("messages must be a sequence of message dictionaries.") + if schema is not None: + # Check validator availability/schema validity before running inference. + if isinstance(schema, dict): + try: + from jsonschema import validators + except ImportError as exc: + raise ImportError( + 'Install "local-llm-kit[structured]" for JSON Schema validation.' + ) from exc + validators.validator_for(schema).check_schema(schema) + elif not callable( + getattr(schema, "model_validate", None) or getattr(schema, "parse_obj", None) + ): + raise TypeError("Unsupported schema validator.") + active_messages = [dict(m) for m in messages] + + # Configure response_format + req_kwargs = dict(kwargs) + req_kwargs.setdefault("execute_tools", False) + if "response_format" not in req_kwargs: + if isinstance(schema, dict): + req_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": {"name": "output_schema", "schema": schema}, + } + else: + req_kwargs["response_format"] = {"type": "json_object"} + + last_error: Optional[str] = None + for attempt in range(max_retries + 1): + resp = llm.chat(messages=active_messages, **req_kwargs) + choices = resp.get("choices", []) + if not choices: + raise ValueError("LLM returned empty choices in chat_structured.") + raw_text = choices[0].get("message", {}).get("content", "") + + try: + parsed = extract_json(raw_text) + if schema: + validate_schema(parsed, schema) + return parsed + except (ValueError, TypeError) as exc: + last_error = str(exc) + logger.warning("Structured output attempt %d failed: %s", attempt + 1, last_error) + if attempt < max_retries: + # Append assistant output and user correction request + active_messages.append({"role": "assistant", "content": raw_text}) + active_messages.append( + { + "role": "user", + "content": ( + f"Your previous response produced an error: {last_error}.\n" + "Please output ONLY valid, well-formed JSON matching the required structure." + ), + } + ) + + raise ValueError( + f"Failed to obtain valid structured JSON after {max_retries + 1} attempts. Last error: {last_error}" + ) diff --git a/local_llm_kit/tools.py b/local_llm_kit/tools.py index 2cc5b52..0fbedae 100644 --- a/local_llm_kit/tools.py +++ b/local_llm_kit/tools.py @@ -22,15 +22,28 @@ def get_weather(location: str, unit: str = "celsius") -> dict: ) """ +import concurrent.futures import inspect import json import logging +import math from typing import Any, Callable, Dict, List, Optional, Union from .function_calling import FunctionCall, FunctionRegistry, parse_function_calls logger = logging.getLogger(__name__) + +def _validate_tool_timeout(timeout: Optional[float]) -> None: + if timeout is not None and ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not math.isfinite(timeout) + or timeout <= 0 + ): + raise ValueError("tool_timeout must be a finite positive number or None.") + + _PYTHON_TO_JSON = { "str": "string", "int": "integer", @@ -218,6 +231,61 @@ def get_tool_list(self) -> List[Dict[str, Any]]: """Return registered functions as OpenAI-style ``tools`` list.""" return [{"type": "function", "function": dict(schema)} for schema in self.get_schema_list()] + def execute_call( + self, + call: ToolCall, + allowed_names: Optional[List[str]] = None, + spec: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = 10.0, + ) -> str: + """Execute a scoped call; tool failures become bounded error messages.""" + _validate_tool_timeout(timeout) + if allowed_names is not None and call.name not in allowed_names: + return "Error: tool '%s' is not available for this request" % call.name + if not self.has_function(call.name): + return "Error: tool '%s' is not registered" % call.name + if not isinstance(call.arguments, dict): + return "Error: tool '%s' received invalid arguments (must be an object)" % call.name + if spec is not None: + params = spec.get("function", spec).get("parameters", {}) + missing = [r for r in params.get("required", []) if r not in call.arguments] + if missing: + return "Error: tool '%s' missing required argument(s): %s" % ( + call.name, + ", ".join(missing), + ) + try: + impl = self.implementations[call.name] + except (AttributeError, KeyError): + return "Error: tool '%s' has no implementation" % call.name + try: + if timeout is None: + result = impl(**call.arguments) + else: + # shortcut: timeout bounds waiting, not side effects; use a subprocess + # for tools that must be forcibly terminated. + pool = concurrent.futures.ThreadPoolExecutor(max_workers=1) + try: + future = pool.submit(impl, **call.arguments) + result = future.result(timeout=timeout) + finally: + pool.shutdown(wait=False) + except concurrent.futures.TimeoutError: + return "Error: tool '%s' timed out after %s seconds" % (call.name, timeout) + except Exception as exc: # noqa: BLE001 (tool errors become tool output) + logger.warning("Tool '%s' failed: %s", call.name, exc) + return "Error: tool '%s' failed (%s: %s)" % ( + call.name, + type(exc).__name__, + str(exc)[:200], + ) + if isinstance(result, str): + return result + try: + return json.dumps(result, default=str) + except (TypeError, ValueError): # e.g. circular references + return str(result) + def normalize_tools( tools: Optional[List[Any]] = None, diff --git a/pyproject.toml b/pyproject.toml index 71aa742..9cba0c2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["setuptools>=68", "wheel"] +requires = ["setuptools>=77", "wheel"] build-backend = "setuptools.build_meta" [project] @@ -10,18 +10,18 @@ dynamic = ["version"] description = "One Python API for offline LLMs and local servers: Ollama, AirLLM, SGLang, vLLM, LM Studio and llama.cpp" readme = "README.md" requires-python = ">=3.9" -license = { text = "MIT" } +license = "MIT" +license-files = ["LICENSE"] authors = [ { name = "Utkarsh Rajput", email = "utkarshrajput815@gmail.com" }, ] maintainers = [ { name = "Utkarsh Rajput", email = "utkarshrajput815@gmail.com" }, ] -keywords = ["llm", "local-llm", "offline-ai", "openai-compatible", "transformers", "llama.cpp", "ollama", "airllm", "sglang", "vllm", "lm-studio", "tool-calling", "structured-output", "rag", "embeddings"] +keywords = ['llm', 'local-llm', 'offline-ai', 'openai-compatible', 'transformers', 'llama.cpp', 'ollama', 'airllm', 'apple-foundation-models', 'apfel', 'sglang', 'vllm', 'lm-studio', 'tool-calling', 'structured-output', 'rag', 'embeddings', 'mcp', 'model-context-protocol'] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", @@ -41,11 +41,19 @@ dependencies = [ ] [project.optional-dependencies] +structured = ["jsonschema>=4.18,<5"] +yaml = ["PyYAML>=6.0,<7"] airllm = [ "airllm>=2.11,<5", "numpy>=1.24.0", "mlx>=0.12.0; sys_platform == 'darwin' and platform_machine == 'arm64'", ] +# Apple on-device Foundation Models (lazy: local_llm_kit.backends.apple_fm). +# macOS 26+, Apple Intelligence-capable Mac, Xcode 26+ (SDK agreement +# accepted), Python 3.10+. The marker keeps resolvers off it elsewhere. +apple-fm = [ + "apple-fm-sdk>=0.2.1; sys_platform == 'darwin' and python_version >= '3.10'", +] # HF transformers backend (lazy: local_llm_kit.backends.transformers) transformers = [ "torch>=2.0.0", @@ -85,7 +93,10 @@ rag = [ ] # Everything runnable (all runtime extras, excludes dev tooling) all = [ + "jsonschema>=4.18,<5", + "PyYAML>=6.0,<7", "airllm>=2.11,<5", + "apple-fm-sdk>=0.2.1; sys_platform == 'darwin' and python_version >= '3.10'", "mlx>=0.12.0; sys_platform == 'darwin' and platform_machine == 'arm64'", "torch>=2.0.0", "transformers>=4.41.0", @@ -107,6 +118,7 @@ all = [ ] # Contributor tooling (lint + format + test + packaging checks) dev = [ + "jsonschema>=4.18,<5", "pytest>=7.4.0", "pytest-cov>=4.1.0", "ruff>=0.4.0", diff --git a/tests/_fake_mcp_server.py b/tests/_fake_mcp_server.py new file mode 100644 index 0000000..6b6c843 --- /dev/null +++ b/tests/_fake_mcp_server.py @@ -0,0 +1,112 @@ +"""A tiny Model Context Protocol server over stdio, for tests only. + +Speaks newline-delimited JSON-RPC 2.0 on stdin/stdout. Stdlib only; it is +launched as a subprocess by ``tests/test_mcp.py``. + +Modes (argv): + --paginate paginate ``tools/list`` (2 tools per page) with nextCursor + --sleep never answer ``tools/list`` (used to test timeouts) +""" + +import json +import sys +import time + +TOOLS = [ + { + "name": "add", + "description": "Add two integers.", + "inputSchema": { + "type": "object", + "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, + "required": ["a", "b"], + }, + }, + { + "name": "boom", + "description": "Always reports an error.", + "inputSchema": {"type": "object", "properties": {}}, + }, + { + "name": "weird/name", + "description": "Tool whose name is not a valid OpenAI function name.", + "inputSchema": {"type": "object", "properties": {}}, + }, +] + + +def _respond(mid, result=None, error=None): + msg = {"jsonrpc": "2.0", "id": mid} + if error is not None: + msg["error"] = error + else: + msg["result"] = result + sys.stdout.write(json.dumps(msg) + "\n") + sys.stdout.flush() + + +def _handle(msg, paginate, sleep): + method = msg.get("method") + mid = msg.get("id") + params = msg.get("params") or {} + if mid is None: + return # notification (e.g. notifications/initialized) + if method == "initialize": + _respond( + mid, + result={ + "protocolVersion": "2025-06-18", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "fake-stdio", "version": "1.0"}, + }, + ) + elif method == "tools/list": + if sleep: + time.sleep(3600) + return + if not paginate: + _respond(mid, result={"tools": TOOLS}) + return + cursor = params.get("cursor") + if cursor in (None, "0"): + _respond(mid, result={"tools": TOOLS[:2], "nextCursor": "1"}) + else: + _respond(mid, result={"tools": TOOLS[2:]}) + elif method == "tools/call": + name = params.get("name") + args = params.get("arguments") or {} + if name == "add": + _respond( + mid, + result={ + "content": [ + {"type": "text", "text": str(int(args.get("a", 0)) + int(args.get("b", 0)))} + ] + }, + ) + elif name == "boom": + _respond(mid, result={"content": [{"type": "text", "text": "kaboom"}], "isError": True}) + elif name == "weird/name": + _respond(mid, result={"content": [{"type": "text", "text": "weird ok"}]}) + else: + _respond(mid, error={"code": -32602, "message": "unknown tool: %s" % name}) + else: + _respond(mid, error={"code": -32601, "message": "method not found: %s" % method}) + + +def main(argv): + paginate = "--paginate" in argv + sleep = "--sleep" in argv + for line in sys.stdin: + line = line.strip() + if not line: + continue + try: + msg = json.loads(line) + except json.JSONDecodeError: + continue + _handle(msg, paginate, sleep) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/tests/_interop_mcp_server.py b/tests/_interop_mcp_server.py new file mode 100644 index 0000000..0748bc7 --- /dev/null +++ b/tests/_interop_mcp_server.py @@ -0,0 +1,44 @@ +"""Opt-in interop fixture: an MCP server built with the official ``mcp`` SDK. + +Used only by ``tests/test_mcp_interop.py`` on Python >= 3.10 with the +``mcp`` package installed. It is a standalone subprocess script (never +imported by the normal test run), so it may safely depend on the SDK that +the light core deliberately avoids. + +The SDK renamed FastMCP -> MCPServer in v2; this targets v2 and is skipped +whenever the official package is unavailable. +""" + +import sys + + +def main() -> None: + from mcp.server.mcpserver import MCPServer # type: ignore + + server = MCPServer("interop-demo") + + @server.tool() + def add(a: int, b: int) -> int: + """Add two integers.""" + return a + b + + @server.tool() + def greet(name: str) -> str: + """Greet someone by name.""" + return "Hello, %s!" % name + + if len(sys.argv) > 1: + server.run( + transport="streamable-http", + host="127.0.0.1", + port=int(sys.argv[1]), + stateless_http=True, + json_response=len(sys.argv) > 2, + ) + else: + server.run(transport="stdio") + + +if __name__ == "__main__": + main() + sys.exit(0) diff --git a/tests/test_agent.py b/tests/test_agent.py new file mode 100644 index 0000000..faadd65 --- /dev/null +++ b/tests/test_agent.py @@ -0,0 +1,185 @@ +"""Unit and integration tests for autonomous Agent and self-correcting tool loops.""" + +import unittest +from unittest.mock import MagicMock + +from local_llm_kit.agent import Agent, AgentResult +from local_llm_kit.tools import tool + + +@tool +def calculate_sum(a: int, b: int) -> int: + """Calculate sum of two integers.""" + return a + b + + +@tool +def flaky_db_query(table: str) -> str: + """Query a table.""" + if table != "users": + raise ValueError(f"Table '{table}' does not exist. Available tables: 'users'") + return "User: Alice" + + +class TestAgent(unittest.TestCase): + def test_single_turn_no_tools(self): + mock_llm = MagicMock() + mock_llm.chat.return_value = { + "choices": [{"message": {"role": "assistant", "content": "The sky is blue."}}] + } + + agent = Agent(llm=mock_llm) + result = agent.run("What color is the sky?") + + self.assertIsInstance(result, AgentResult) + self.assertEqual(result.content, "The sky is blue.") + self.assertTrue(result.success) + self.assertEqual(result.tool_calls_executed, 0) + self.assertEqual(result.iterations, 1) + + def test_multi_turn_tool_execution(self): + mock_llm = MagicMock() + # Turn 1: Model requests calculate_sum(a=10, b=25) + # Turn 2: Model outputs final answer + mock_llm.chat.side_effect = [ + { + "choices": [ + { + "message": { + "role": "assistant", + "tool_calls": [ + { + "id": "call_1", + "function": { + "name": "calculate_sum", + "arguments": '{"a": 10, "b": 25}', + }, + } + ], + } + } + ] + }, + { + "choices": [ + { + "message": { + "role": "assistant", + "content": "The sum of 10 and 25 is 35.", + } + } + ] + }, + ] + + agent = Agent(llm=mock_llm, tools=[calculate_sum]) + result = agent.run("What is 10 + 25?") + + self.assertEqual(result.content, "The sum of 10 and 25 is 35.") + self.assertTrue(result.success) + self.assertEqual(result.tool_calls_executed, 1) + self.assertEqual(result.iterations, 2) + # Verify tool output was fed into conversation history + history = result.steps + self.assertTrue( + any(msg.get("role") == "tool" and msg.get("content") == "35" for msg in history) + ) + + def test_self_correcting_error_feedback(self): + mock_llm = MagicMock() + # Turn 1: Model calls flaky_db_query with invalid table 'accounts' -> raises ValueError + # Turn 2: Model receives error feedback, self-corrects to 'users' + # Turn 3: Model receives 'User: Alice' and gives final answer + mock_llm.chat.side_effect = [ + { + "choices": [ + { + "message": { + "role": "assistant", + "tool_calls": [ + { + "id": "call_err", + "function": { + "name": "flaky_db_query", + "arguments": '{"table": "accounts"}', + }, + } + ], + } + } + ] + }, + { + "choices": [ + { + "message": { + "role": "assistant", + "tool_calls": [ + { + "id": "call_fix", + "function": { + "name": "flaky_db_query", + "arguments": '{"table": "users"}', + }, + } + ], + } + } + ] + }, + { + "choices": [ + { + "message": { + "role": "assistant", + "content": "Found user Alice in the users table.", + } + } + ] + }, + ] + + agent = Agent(llm=mock_llm, tools=[flaky_db_query]) + result = agent.run("Query accounts") + + self.assertTrue(result.success) + self.assertEqual(result.tool_calls_executed, 2) + self.assertIn("Found user Alice", result.content) + + # Confirm the error was captured in history + history = result.steps + tool_err_msg = [m for m in history if m.get("tool_call_id") == "call_err"][0] + self.assertIn("Table 'accounts' does not exist", tool_err_msg["content"]) + + def test_max_steps_guard(self): + mock_llm = MagicMock() + # Model keeps calling tools forever + mock_llm.chat.return_value = { + "choices": [ + { + "message": { + "role": "assistant", + "tool_calls": [ + { + "id": "loop", + "function": { + "name": "calculate_sum", + "arguments": '{"a": 1, "b": 1}', + }, + } + ], + } + } + ] + } + + agent = Agent(llm=mock_llm, tools=[calculate_sum], max_steps=3) + result = agent.run("Loop forever") + + self.assertFalse(result.success) + self.assertEqual(result.iterations, 3) + self.assertEqual(result.tool_calls_executed, 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_apple_fm.py b/tests/test_apple_fm.py new file mode 100644 index 0000000..b57ccd6 --- /dev/null +++ b/tests/test_apple_fm.py @@ -0,0 +1,657 @@ +"""Apple Foundation Models backend + apfel bridge contracts. + +All tests run offline with a fake ``apple_fm_sdk`` module (no macOS, Xcode, +or on-device model needed). They verify the adapter contract against the +real SDK surface (``apple/apple-fm-sdk``, PyPI ``apple-fm-sdk`` 0.2.1): + +* platform / interpreter / SDK / availability guards with actionable errors +* generate / chat / streaming delta conversion / stop truncation +* native ``json_schema`` guided generation via ``GeneratedContent.to_json()`` +* sampling mapping (temperature 0 -> greedy, seed -> random) +* per-request session isolation (backends are shared via the LLM cache) +* tool specs travel in the prompt; no automatic in-framework execution +* apfel bridge profile: no top_k/penalty fields, chat-only, no embeddings + +A live on-device test runs only with +``LOCAL_LLM_KIT_APPLE_FM_LIVE=1`` on an eligible Mac; it is skipped +everywhere else (including CI). +""" + +import asyncio +import enum +import os +import sys +import types +import unittest +from unittest import mock + +from local_llm_kit import LLM +from local_llm_kit.backends import BACKEND_ALIASES, BACKENDS, OPENAI_SERVER_URLS, get_backend +from local_llm_kit.backends.apple_fm import APPLE_MODEL_ID, AppleFMBackend +from local_llm_kit.backends.openai_compat import OpenAICompatBackend + +# --------------------------------------------------------------------------- +# Fake apple_fm_sdk mirroring the real package surface +# (SystemLanguageModel / LanguageModelSession / GenerationOptions / +# SamplingMode / GeneratedContent.to_json / enums). +# --------------------------------------------------------------------------- + + +class FakeUseCase(enum.Enum): + GENERAL = 0 + CONTENT_TAGGING = 1 + + +class FakeGuardrails(enum.Enum): + DEFAULT = 0 + PERMISSIVE_CONTENT_TRANSFORMATIONS = 1 + + +class FakeReason(enum.Enum): + APPLE_INTELLIGENCE_NOT_ENABLED = 0 + DEVICE_NOT_ELIGIBLE = 1 + MODEL_NOT_READY = 2 + UNKNOWN = 255 + + +class FakeSampling: + def __init__(self, mode, top=None, probability_threshold=None, seed=None): + self.mode = mode + self.top = top + self.probability_threshold = probability_threshold + self.seed = seed + + +class FakeSamplingMode: + @classmethod + def greedy(cls): + return FakeSampling("greedy") + + @classmethod + def random(cls, top=None, probability_threshold=None, seed=None): + return FakeSampling("random", top, probability_threshold, seed) + + +class FakeOptions: + def __init__(self, temperature=None, sampling=None, maximum_response_tokens=None): + self.temperature = temperature + self.sampling = sampling + self.maximum_response_tokens = maximum_response_tokens + + +class FakeGeneratedContent: + def __init__(self, payload): + self.payload = payload + + def to_json(self): + import json + + return json.dumps(self.payload) + + +class FakeSystemModel: + available = True + reason = None + window = 4096 + variant_name = None + token_count_calls = [] + + def __init__(self, use_case=None, guardrails=None): + self.use_case = use_case + self.guardrails = guardrails + + def is_available(self): + return FakeSystemModel.available, FakeSystemModel.reason + + @property + def context_size(self): + return FakeSystemModel.window + + @property + def variant(self): + if FakeSystemModel.variant_name is None: + return None + return types.SimpleNamespace(display_name=FakeSystemModel.variant_name) + + async def token_count(self, value=None, *, instructions=None): + FakeSystemModel.token_count_calls.append((value, instructions)) + text = instructions if instructions is not None else value + return max(1, len(str(text)) // 4) + + +class FakeImageAttachment: + def __init__(self, path): + self.path = str(path) + with open(self.path, "rb") as fh: + self.data = fh.read() + + +class FakeSession: + instances = [] + snapshots = ["Hello", "Hello, world", "Hello, world!"] + fail_with = None + + def __init__(self, instructions=None, model=None, tools=None, _ptr=None): + self.instructions = instructions + self.model = model + self.tools = tools + self.calls = [] + FakeSession.instances.append(self) + + async def respond( + self, prompt, generating=None, *, schema=None, json_schema=None, options=None + ): + self.calls.append( + {"prompt": prompt, "schema": schema, "json_schema": json_schema, "options": options} + ) + if FakeSession.fail_with is not None: + raise FakeSession.fail_with + if json_schema is not None: + return FakeGeneratedContent({"ok": True, "echo": str(prompt)[:24]}) + if isinstance(prompt, list): + texts = [p for p in prompt if isinstance(p, str)] + images = [p for p in prompt if not isinstance(p, str)] + return "Echo: %s [%d image(s)]" % (" ".join(texts), len(images)) + return "Echo: %s" % prompt + + async def stream_response(self, prompt, options=None): + self.calls.append({"prompt": prompt, "options": options, "stream": True}) + for snapshot in FakeSession.snapshots: + yield snapshot + + +def make_fake_sdk(): + module = types.ModuleType("apple_fm_sdk") + module.SystemLanguageModel = FakeSystemModel + module.SystemLanguageModelUseCase = FakeUseCase + module.SystemLanguageModelGuardrails = FakeGuardrails + module.LanguageModelSession = FakeSession + module.ImageAttachment = FakeImageAttachment + module.GenerationOptions = FakeOptions + module.SamplingMode = FakeSamplingMode + module.GeneratedContent = FakeGeneratedContent + return module + + +def install_fake_sdk(): + return mock.patch.dict(sys.modules, {"apple_fm_sdk": make_fake_sdk()}) + + +def mac_only(): + return mock.patch.object(sys, "platform", "darwin"), mock.patch.object( + sys, "version_info", (3, 10, 0, "final", 0) + ) + + +class AppleFMBackendTest(unittest.TestCase): + def setUp(self): + FakeSystemModel.available = True + FakeSystemModel.reason = None + FakeSystemModel.window = 4096 + FakeSystemModel.variant_name = None + FakeSystemModel.token_count_calls = [] + FakeSession.instances = [] + FakeSession.fail_with = None + self._patches = [] + + def tearDown(self): + for patcher in self._patches: + patcher.stop() + + def _mac(self): + for patcher in mac_only(): + patcher.start() + self._patches.append(patcher) + sdk = install_fake_sdk() + sdk.start() + self._patches.append(sdk) + + def test_registry_and_aliases(self): + self.assertEqual(BACKEND_ALIASES["apple"], "apple-fm") + self.assertEqual(BACKEND_ALIASES["apfel"], "openai-compat") + for alias in ("apple-foundation", "foundation-models", "foundationmodels"): + self.assertEqual(BACKEND_ALIASES[alias], "apple-fm") + self.assertIn("apple-fm", BACKENDS) + self.assertIn("apfel", OPENAI_SERVER_URLS) + # Every preset (incl. apfel) is accepted by the registry + LLM routing. + backend = get_backend("apfel", model="apple-foundationmodel") + self.assertEqual(backend.base_url, OPENAI_SERVER_URLS["apfel"]) + self.assertEqual(backend.provider, "apfel") + + def test_platform_guard_fires_before_sdk_import(self): + with mock.patch.object(sys, "platform", "linux"): + with self.assertRaisesRegex(RuntimeError, "only on macOS"): + AppleFMBackend("apple-foundationmodel") + + def test_missing_sdk_gives_install_hint(self): + self._mac() + with mock.patch.dict(sys.modules, {"apple_fm_sdk": None}): + with self.assertRaisesRegex(ImportError, "local-llm-kit\\[apple-fm\\]"): + AppleFMBackend("apple-foundationmodel") + + def test_llm_wraps_missing_sdk_as_runtime_error(self): + self._mac() + with mock.patch.dict(sys.modules, {"apple_fm_sdk": None}): + with self.assertRaisesRegex(RuntimeError, "apple-fm backend needs"): + LLM("apple-foundationmodel", backend="apple-fm", use_cache=False) + + def test_unavailable_model_reports_actionable_reason(self): + self._mac() + FakeSystemModel.available = False + FakeSystemModel.reason = FakeReason.MODEL_NOT_READY + with self.assertRaisesRegex(RuntimeError, "still downloading"): + AppleFMBackend("apple-foundationmodel") + + def test_is_available_preflight_never_raises(self): + self._mac() + ok, reason = AppleFMBackend.is_available() + self.assertTrue(ok) + self.assertIsNone(reason) + FakeSystemModel.available = False + FakeSystemModel.reason = FakeReason.DEVICE_NOT_ELIGIBLE + ok, reason = AppleFMBackend.is_available() + self.assertFalse(ok) + self.assertIn("not eligible", reason) + + def test_generate_roundtrip_and_model_id(self): + self._mac() + backend = AppleFMBackend("apple-foundationmodel") + result = backend.generate("hi there", max_new_tokens=32) + self.assertEqual(result["text"], "Echo: hi there") + self.assertEqual(result["finish_reason"], "stop") + self.assertEqual(result["model"], APPLE_MODEL_ID) + + def test_invalid_options_rejected(self): + self._mac() + with self.assertRaisesRegex(ValueError, "use_case"): + AppleFMBackend("m", use_case="summarize-everything") + with self.assertRaisesRegex(ValueError, "guardrails"): + AppleFMBackend("m", guardrails="none") + + def test_sampling_mapping(self): + self._mac() + backend = AppleFMBackend("m") + greedy = backend._options(0, 64) + self.assertEqual(greedy.sampling.mode, "greedy") + self.assertEqual(greedy.maximum_response_tokens, 64) + seeded = backend._options(0.7, 64, seed=42) + self.assertEqual(seeded.sampling.mode, "random") + self.assertEqual(seeded.sampling.seed, 42) + plain = backend._options(0.7, 64) + self.assertEqual(plain.temperature, 0.7) + self.assertIsNone(plain.sampling) + + def test_chat_splits_system_into_instructions(self): + self._mac() + backend = AppleFMBackend("m") + out = backend.chat( + [ + {"role": "system", "content": "Be terse."}, + {"role": "user", "content": "Say hi."}, + ] + ) + self.assertIn("Say hi.", out["text"]) + session = FakeSession.instances[-1] + self.assertEqual(session.instructions, "Be terse.") + self.assertIn("Say hi.", session.calls[0]["prompt"]) + + def test_each_request_gets_a_fresh_session(self): + self._mac() + backend = AppleFMBackend("m") + backend.generate("one") + backend.generate("two") + self.assertEqual(len(FakeSession.instances), 2) + prompts = [s.calls[0]["prompt"] for s in FakeSession.instances] + self.assertEqual(prompts, ["one", "two"]) + + def test_native_json_schema_guided_generation(self): + self._mac() + backend = AppleFMBackend("m") + out = backend.chat( + [{"role": "user", "content": "hi"}], + response_format={ + "type": "json_schema", + "json_schema": { + "name": "reply", + "schema": {"type": "object", "properties": {}}, + }, + }, + ) + import json + + self.assertEqual(json.loads(out["text"])["ok"], True) + session = FakeSession.instances[-1] + self.assertEqual(session.calls[0]["json_schema"], {"type": "object", "properties": {}}) + + def test_streaming_yields_deltas_not_snapshots(self): + self._mac() + backend = AppleFMBackend("m") + chunks = list(backend.generate_stream("hi")) + self.assertEqual([c["text"] for c in chunks], ["Hello", ", world", "!"]) + self.assertEqual("".join(c["text"] for c in chunks), "Hello, world!") + + def test_stop_sequences_truncate(self): + self._mac() + backend = AppleFMBackend("m") + out = backend.generate("say world hello", stop=["world"]) + self.assertEqual(out["text"], "Echo: say ") + + def test_tools_documented_in_prompt_without_auto_execution(self): + self._mac() + backend = AppleFMBackend("m") + tools = [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "City weather", + "parameters": {"type": "object", "properties": {}}, + }, + } + ] + out = backend.chat([{"role": "user", "content": "weather?"}], tools=tools) + session = FakeSession.instances[-1] + self.assertIsNone(session.tools) + self.assertIn("get_weather", session.calls[0]["prompt"]) + self.assertIn("weather?", out["text"]) + + def test_full_llm_tool_loop_parses_text_calls(self): + self._mac() + + class Scripted(AppleFMBackend): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.turn = 0 + + def chat(self, *args, **kwargs): + self.turn += 1 + if self.turn == 1: + return { + "text": 'Let me check. {"name": "add", ' + '"arguments": {"a": 2, "b": 3}}', + "finish_reason": "stop", + "model": self.model, + } + return {"text": "5", "finish_reason": "stop", "model": self.model} + + llm = LLM("m", backend_instance=Scripted("m"), use_cache=False) + llm.add_tool(lambda a, b: a + b, name="add") + out = llm.chat( + [{"role": "user", "content": "add 2 and 3"}], + tools=[{"type": "function", "function": {"name": "add"}}], + ) + self.assertIn("5", out["choices"][0]["message"]["content"]) + + def test_sync_bridge_inside_a_running_loop(self): + self._mac() + backend = AppleFMBackend("m") + + async def _main(): + return backend.generate("from-loop") + + self.assertEqual(asyncio.run(_main())["text"], "Echo: from-loop") + + def test_embeddings_unsupported(self): + self._mac() + backend = AppleFMBackend("m") + self.assertFalse(backend.supports_embeddings) + with self.assertRaises(NotImplementedError): + backend.embed(["hello"]) + + def test_model_info_and_list_models(self): + self._mac() + FakeSystemModel.variant_name = "AFM 3 Core" + backend = AppleFMBackend("m") + info = backend.model_info() + self.assertEqual(info["backend"], "apple-fm") + self.assertTrue(info["on_device"]) + self.assertFalse(info["requires_network"]) + self.assertEqual(info["variant"], "AFM 3 Core") + self.assertEqual(info["context_window"], 4096) + models = backend.list_models() + self.assertEqual(models[0]["owned_by"], "apple") + + def test_context_window_override(self): + self._mac() + FakeSystemModel.window = 8192 + self.assertEqual(AppleFMBackend("m").get_context_window(), 8192) + self.assertEqual(AppleFMBackend("m", context_window=2048).get_context_window(), 2048) + + def test_close_is_safe(self): + self._mac() + backend = AppleFMBackend("m") + backend.generate("hi") + backend.close() + self.assertTrue(backend._closed) + + def test_text_only_prompt_stays_a_plain_string(self): + self._mac() + backend = AppleFMBackend("m") + backend.chat([{"role": "user", "content": "hello"}]) + prompt = FakeSession.instances[-1].calls[0]["prompt"] + self.assertIsInstance(prompt, str) + self.assertIn("User: hello", prompt) + + def test_vision_data_url_materialized_and_cleaned_up(self): + import base64 as _b64 + + self._mac() + backend = AppleFMBackend("m") + self.assertTrue(backend.supports_vision) + raw = _b64.b64encode(b"\x89PNG-fake-bytes").decode() + out = backend.chat( + [ + { + "role": "user", + "content": [ + {"type": "text", "text": "what is this?"}, + { + "type": "image_url", + "image_url": {"url": "data:image/png;base64," + raw}, + }, + ], + } + ] + ) + self.assertIn("[1 image(s)]", out["text"]) + session = FakeSession.instances[-1] + prompt = session.calls[0]["prompt"] + self.assertIsInstance(prompt, list) + attachments = [p for p in prompt if isinstance(p, FakeImageAttachment)] + self.assertEqual(len(attachments), 1) + self.assertEqual(attachments[0].data, b"\x89PNG-fake-bytes") + # Temp files are removed after the request completes. + self.assertFalse(os.path.exists(attachments[0].path)) + + def test_vision_remote_url_rejected_without_download(self): + self._mac() + backend = AppleFMBackend("m") + with self.assertRaisesRegex(ValueError, "never downloaded"): + backend.chat( + [ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": {"url": "https://example.com/a.png"}, + } + ], + } + ] + ) + self.assertEqual(FakeSession.instances, []) + + def test_vision_oversize_image_rejected(self): + import base64 as _b64 + + self._mac() + backend = AppleFMBackend("m") + with mock.patch.object(backend._fm, "ImageAttachment", FakeImageAttachment): + import local_llm_kit.backends.apple_fm as apple_mod + + with mock.patch.object(apple_mod, "_MAX_IMAGE_BYTES", 4): + with self.assertRaisesRegex(ValueError, "limit"): + backend.chat( + [ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64," + + _b64.b64encode(b"12345").decode() + }, + } + ], + } + ] + ) + + def test_exact_token_count_uses_sdk(self): + self._mac() + backend = AppleFMBackend("m") + self.assertEqual(backend.count_tokens_exact("hello world, this is a test"), 6) + self.assertEqual( + FakeSystemModel.token_count_calls[-1], ("hello world, this is a test", None) + ) + self.assertEqual(backend.count_tokens_exact(instructions="be terse"), 2) + self.assertEqual(FakeSystemModel.token_count_calls[-1], (None, "be terse")) + with self.assertRaisesRegex(ValueError, "exactly one"): + backend.count_tokens_exact() + with self.assertRaisesRegex(ValueError, "exactly one"): + backend.count_tokens_exact("a", instructions="b") + + def test_serve_end_to_end_with_apple_backend(self): + try: + from fastapi.testclient import TestClient + + from local_llm_kit.server import create_app + except ImportError: + self.skipTest("fastapi not installed") + sdk = install_fake_sdk() + sdk.start() + self._patches.append(sdk) + # Platform/interpreter patches apply only to backend construction: + # FastAPI inspects the real interpreter version at route setup. + with ( + mock.patch.object(sys, "platform", "darwin"), + mock.patch.object(sys, "version_info", (3, 10, 0, "final", 0)), + ): + llm = LLM("apple-foundationmodel", backend="apple-fm", use_cache=False) + client = TestClient(create_app(llm=llm)) + resp = client.post( + "/v1/chat/completions", + json={ + "model": "apple-foundationmodel", + "messages": [{"role": "user", "content": "hi"}], + }, + ) + self.assertEqual(resp.status_code, 200) + self.assertIn("Echo:", resp.json()["choices"][0]["message"]["content"]) + + +class ApfelBridgeTest(unittest.TestCase): + def test_chat_payload_omits_rejected_fields(self): + backend = OpenAICompatBackend("apple-foundationmodel", provider="apfel") + payload = backend._chat_payload( + [{"role": "user", "content": "hi"}], + 0.7, + 128, + 0.95, + 40, + 1.1, + False, + None, + None, + None, + None, + None, + ) + for banned in ("top_k", "repeat_penalty", "repetition_penalty"): + self.assertNotIn(banned, payload) + self.assertEqual(payload["temperature"], 0.7) + self.assertEqual(payload["max_tokens"], 128) + + def test_completion_payload_omits_rejected_fields(self): + backend = OpenAICompatBackend("apple-foundationmodel", provider="apfel") + payload = backend._completion_payload("hi", 0.7, 64, 0.95, 40, 1.1, False) + for banned in ("top_k", "repeat_penalty", "repetition_penalty"): + self.assertNotIn(banned, payload) + + def test_other_providers_keep_sampling_fields(self): + backend = OpenAICompatBackend("m", provider="vllm") + payload = backend._chat_payload( + [{"role": "user", "content": "hi"}], + 0.7, + 128, + 0.95, + 40, + 1.1, + False, + None, + None, + None, + None, + None, + ) + self.assertEqual(payload["repetition_penalty"], 1.1) + + def test_prompt_completion_maps_to_chat(self): + backend = OpenAICompatBackend("apple-foundationmodel", provider="apfel") + with mock.patch.object( + backend, "_post_json", return_value={"choices": [{"message": {"content": "mapped"}}]} + ) as post: + self.assertEqual(backend.generate("hi")["text"], "mapped") + self.assertEqual(post.call_args.args[0], "/chat/completions") + with mock.patch.object(backend, "chat_stream", return_value=iter([{"text": "mapped"}])): + self.assertEqual(list(backend.generate_stream("hi")), [{"text": "mapped"}]) + + def test_apfel_has_no_embeddings_endpoint(self): + backend = OpenAICompatBackend("apple-foundationmodel", provider="apfel") + self.assertFalse(backend.supports_embeddings) + with self.assertRaisesRegex(NotImplementedError, "embeddings"): + backend.embed(["hello"]) + + def test_apfel_preset_routes_through_llm(self): + llm = LLM("apple-foundationmodel", backend="apfel", use_cache=False) + self.assertIsInstance(llm.backend, OpenAICompatBackend) + self.assertEqual(llm.backend.base_url, OPENAI_SERVER_URLS["apfel"]) + with mock.patch.object( + llm.backend, + "_post_json", + return_value={"choices": [{"message": {"content": "served"}}]}, + ) as post: + out = llm.chat([{"role": "user", "content": "hi"}]) + self.assertEqual(out["choices"][0]["message"]["content"], "served") + sent = post.call_args.args[1] + for banned in ("top_k", "repeat_penalty", "repetition_penalty"): + self.assertNotIn(banned, sent) + + def test_apfel_complete_maps_to_chat_end_to_end(self): + llm = LLM("apple-foundationmodel", backend="apfel", use_cache=False) + with mock.patch.object( + llm.backend, + "_post_json", + return_value={"choices": [{"message": {"content": "mapped"}}]}, + ) as post: + self.assertEqual(llm.complete("hi")["choices"][0]["text"], "mapped") + self.assertEqual(post.call_args.args[0], "/chat/completions") + + +@unittest.skipUnless( + os.environ.get("LOCAL_LLM_KIT_APPLE_FM_LIVE") == "1", + "opt-in live test: needs an eligible Mac (macOS 26+, Xcode 26+, " + "Apple Intelligence on). Not run in CI.", +) +class AppleFMLiveTest(unittest.TestCase): + def test_live_generate(self): + backend = AppleFMBackend("apple-foundationmodel") + result = backend.generate("Reply with the single word: ready", max_new_tokens=16) + self.assertIsInstance(result["text"], str) + self.assertTrue(result["text"].strip()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cli.py b/tests/test_cli.py index c0bb469..fc36c65 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -138,7 +138,7 @@ def test_repo_and_filename_shorthand_reaches_the_download_helper(self): ) self.assertEqual(code, 0, msg=out[-500:]) self.assertNotIn("unrecognised signature", out) - self.assertIn("/cache/m.gguf", out) + self.assertIn(os.path.abspath("/cache/m.gguf"), out) repo_id, filename, cache_dir, revision = dl.call_args[0][:4] self.assertEqual(repo_id, "owner/name") self.assertEqual(filename, "file.gguf") @@ -184,3 +184,126 @@ def test_simple_chat_example_runs_offline_as_documented(self): if __name__ == "__main__": unittest.main() + + +class TestDoctorCommand(unittest.TestCase): + """``doctor`` rendering and exit codes, with discovery stubbed (no network).""" + + @staticmethod + def _report(): + from local_llm_kit.discovery import DiscoveryReport, ModelRecord, ServerReport + + server = ServerReport( + base_url="http://127.0.0.1:11434/v1", + provider="ollama", + live=True, + latency_ms=3.2, + models=[ + ModelRecord( + id="qwen2.5:0.5b", + local_verified=True, + capabilities=["completion", "tools"], + context_length=32768, + ), + ModelRecord( + id="big:cloud", + capabilities=["completion"], + context_length=1000000, + remote=True, + remote_host="https://ollama.com:443", + ), + ], + notes=["capabilities read from ollama /api/tags"], + ) + dead = ServerReport( + base_url="http://127.0.0.1:1234/v1", + provider="lmstudio", + live=False, + error="Connection refused", + ) + return DiscoveryReport(servers=[server, dead], elapsed_ms=4.0, probed=2) + + @staticmethod + def _empty_report(): + from local_llm_kit.discovery import DiscoveryReport, ServerReport + + return DiscoveryReport( + servers=[ + ServerReport( + base_url="http://127.0.0.1:1234/v1", + provider="lmstudio", + live=False, + error="Connection refused", + ) + ], + elapsed_ms=1.0, + probed=1, + ) + + def _run_with(self, report, argv): + with mock.patch("local_llm_kit.discovery.discover", return_value=report): + return _run_main(argv) + + def test_live_server_exits_zero_and_names_the_on_device_model(self): + code, output = self._run_with(self._report(), ["doctor"]) + self.assertEqual(code, 0) + self.assertIn("qwen2.5:0.5b", output) + self.assertIn("ctx 32768", output) + self.assertIn('LLM("qwen2.5:0.5b", backend="ollama")', output) + + def test_off_device_models_are_flagged_with_their_remote_host(self): + _code, output = self._run_with(self._report(), ["doctor"]) + self.assertIn("OFF-DEVICE", output) + self.assertIn("ollama.com", output) + + def test_nothing_running_exits_one(self): + code, output = self._run_with(self._empty_report(), ["doctor"]) + self.assertEqual(code, 1) + self.assertIn("No local LLM server responded", output) + + def test_require_local_exits_zero_when_a_local_model_exists(self): + code, _output = self._run_with(self._report(), ["doctor", "--require-local"]) + self.assertEqual(code, 0) + + def test_require_local_exits_one_when_only_remote_models_exist(self): + from local_llm_kit.discovery import DiscoveryReport, ModelRecord, ServerReport + + report = DiscoveryReport( + servers=[ + ServerReport( + base_url="http://127.0.0.1:11434/v1", + provider="ollama", + live=True, + models=[ModelRecord(id="big:cloud", remote=True, remote_host="h")], + ) + ], + probed=1, + ) + code, output = self._run_with(report, ["doctor", "--require-local"]) + self.assertEqual(code, 1) + self.assertIn("No server offering an on-device model", output) + + def test_json_output_is_machine_readable_and_includes_failures(self): + code, output = self._run_with(self._report(), ["doctor", "--json"]) + self.assertEqual(code, 0) + payload = json.loads(output) + self.assertEqual(payload["live_count"], 1) + self.assertEqual(payload["probed"], 2) + self.assertEqual(len(payload["servers"]), 2) + self.assertTrue(payload["servers"][0]["all_local"] is False) + self.assertTrue(payload["servers"][1]["error"]) + + def test_quiet_mode_prints_nothing_but_keeps_the_exit_code(self): + code, output = self._run_with(self._report(), ["doctor", "--quiet"]) + self.assertEqual(code, 0) + self.assertEqual(output.strip(), "") + + def test_aliases_are_wired_up(self): + for alias in ("discover", "probe"): + with self.subTest(alias=alias): + code, _output = self._run_with(self._report(), [alias]) + self.assertEqual(code, 0) + + def test_non_numeric_timeout_is_rejected_by_argparse(self): + with self.assertRaises(SystemExit): + build_parser().parse_args(["doctor", "--timeout", "soon"]) diff --git a/tests/test_consolidated_regressions.py b/tests/test_consolidated_regressions.py new file mode 100644 index 0000000..5426b57 --- /dev/null +++ b/tests/test_consolidated_regressions.py @@ -0,0 +1,491 @@ +"""Regression cases found by reviewing the community PRs together.""" + +import asyncio +import json +import threading +from concurrent.futures import ThreadPoolExecutor +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest import mock + +import pytest + +from local_llm_kit import LLM, Agent, ConversationLog, PromptTemplate, TemplateRegistry, tool +from local_llm_kit.backends.apple_fm import AppleFMBackend, _stop_deltas +from local_llm_kit.backends.echo import EchoBackend +from local_llm_kit.discovery import ModelRecord, ServerReport, normalize_base_url +from local_llm_kit.hardware import estimate_model_vram, recommend_quantization +from local_llm_kit.mcp import MCPTool, _HttpTransport +from local_llm_kit.rag import RAGPipeline, SimpleVectorStore, bm25_scores, reciprocal_rank_fusion +from local_llm_kit.retry import RetryPolicy, retry_after_seconds +from local_llm_kit.structured import extract_json, validate_schema +from tests.test_apple_fm import FakeSession, FakeSystemModel, install_fake_sdk, mac_only + + +class ToolBackend(EchoBackend): + supports_native_chat = True + + def __init__(self): + super().__init__() + self.requests = [] + + def chat(self, messages, **kwargs): + self.requests.append([dict(message) for message in messages]) + if messages[-1]["role"] == "tool": + return {"text": "done"} + return { + "text": "", + "tool_calls": [ + {"id": "original-id", "function": {"name": "renamed", "arguments": '{"value": 4}'}} + ], + } + + +def test_agent_real_llm_executes_only_once_and_preserves_decorator_name(): + seen = [] + + @tool(name="renamed") + def action(value: int): + seen.append(value) + return value * 2 + + backend = ToolBackend() + llm = LLM("fixture", backend_instance=backend) + result = Agent(llm, tools=[action]).run("call it") + assert result.success and result.content == "done" + assert seen == [4] and result.tool_calls_executed == 1 + assert backend.requests[-1][-1]["tool_call_id"] == "original-id" + assert backend.requests[-1][-1]["content"] == "8" + assert not llm.list_tools() + + +def test_agent_does_not_repair_truncated_executable_arguments(): + seen = [] + llm = mock.Mock() + llm.chat.side_effect = [ + { + "choices": [ + { + "message": { + "tool_calls": [ + { + "id": "bad", + "function": {"name": "action", "arguments": '{"value":"unfinished'}, + } + ] + } + } + ] + }, + {"choices": [{"message": {"content": "ask for a correction"}}]}, + ] + + def action(value): + seen.append(value) + + result = Agent(llm, tools=[action]).run("test") + assert seen == [] + assert "Error" in result.steps[2]["content"] + + +def test_schema_types_and_nested_constraints_are_enforced(): + pytest.importorskip("jsonschema") + schema = { + "type": "object", + "properties": {"age": {"type": "integer", "minimum": 0}}, + "required": ["age"], + } + for age in ("not-an-integer", -1, True): + with pytest.raises(ValueError): + validate_schema({"age": age}, schema) + validate_schema({"age": 3}, schema) + + +def test_json_repair_preserves_quoted_literals_and_delimiters(): + assert extract_json('{"text":"True, None, } and False",}') == { + "text": "True, None, } and False" + } + assert extract_json("{'text': 'True, None', 'flag': True}") == { + "text": "True, None", + "flag": True, + } + with pytest.raises(ValueError): + extract_json('{"path":"/unfinished') + + +def test_missing_schema_validator_fails_before_inference(): + llm = mock.Mock() + with mock.patch.dict("sys.modules", {"jsonschema": None}): + from local_llm_kit import chat_structured + + with pytest.raises(ImportError, match="structured"): + chat_structured(llm, [{"role": "user", "content": "test"}], schema={"type": "object"}) + llm.chat.assert_not_called() + + +def test_locality_rejects_remote_and_unknown_compat_endpoints(): + with pytest.raises(RuntimeError, match="non-loopback"): + LLM( + "remote-model", + backend="openai-compat", + use_cache=False, + backend_kwargs={"base_url": "https://example.com/v1"}, + require_local=True, + ) + unknown = ServerReport( + "http://127.0.0.1:1/v1", "generic", live=True, models=[ModelRecord("local-sounding-model")] + ) + assert not unknown.local_models + with mock.patch("local_llm_kit.discovery.probe_endpoint", return_value=unknown): + with pytest.raises(RuntimeError, match="unknown"): + LLM( + "local-sounding-model", backend="openai-compat", use_cache=False, require_local=True + ) + assert normalize_base_url("http://[::1]:1234/v1/models") == "http://[::1]:1234/v1" + + +def test_http_mcp_returns_result_before_sse_connection_closes(): + release = threading.Event() + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def do_POST(self): + request = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + self.wfile.write( + ( + "data: " + + json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": {"ok": True}}) + + "\n\n" + ).encode() + ) + self.wfile.flush() + release.wait(2) + self.close_connection = True + + def log_message(self, *_args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + try: + transport = _HttpTransport("http://127.0.0.1:%s/mcp" % server.server_port, timeout=0.3) + assert transport.post({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})["result"] == { + "ok": True + } + assert not release.is_set() + finally: + release.set() + server.shutdown() + server.server_close() + worker.join() + + +def test_mcp_collision_is_atomic_and_closes_new_connection(): + llm = LLM("echo", backend="echo", use_cache=False) + + @tool(name="files__read") + def read(): + return "local" + + llm.add_tool(read) + server = mock.Mock(name="server", _opened=False, closed=True) + server.name = "files" + server.list_tools.return_value = [MCPTool("write"), MCPTool("read")] + with pytest.raises(ValueError, match="collides"): + llm.add_mcp_server(server) + server.close.assert_called_once() + assert [item["function"]["name"] for item in llm.list_tools()] == ["files__read"] + + +def test_in_memory_logging_is_shared_and_interaction_is_atomic(): + with ConversationLog(":memory:") as log: + with ThreadPoolExecutor(max_workers=3) as pool: + ids = list( + pool.map( + lambda i: log.log_interaction( + "echo", [{"role": "user", "content": str(i)}], "ok" + ), + range(8), + ) + ) + assert len(log.get_conversations()) == 8 + assert all(len(log.get_messages(cid)) == 2 for cid in ids) + before = log.get_conversations() + with pytest.raises(ValueError): + log.log_interaction("echo", [{"content": "invalid role"}], "bad") + assert log.get_conversations() == before + + +def test_logging_preserves_tool_ids_usage_and_complete_multimodal_payload(): + call = { + "id": "stable-call-id", + "type": "function", + "function": {"name": "read", "arguments": "{}"}, + } + messages = [ + {"role": "user", "content": [{"type": "text", "text": "hello"}]}, + {"role": "assistant", "content": None, "tool_calls": [call]}, + {"role": "tool", "tool_call_id": "stable-call-id", "name": "read", "content": "file"}, + ] + response = { + "choices": [ + {"message": {"role": "assistant", "content": "done"}, "finish_reason": "length"} + ], + "usage": {"prompt_tokens": 12, "completion_tokens": 3}, + } + with ConversationLog(":memory:") as log: + cid = log.log_interaction("fixture", messages, response) + saved = log.get_messages(cid) + exported = json.loads(log.export_conversation(cid, "openai"))["messages"] + assert exported[:3] == messages + assert saved[-1]["finish_reason"] == "length" + assert saved[-1]["prompt_tokens"] == 12 and saved[-1]["completion_tokens"] == 3 + assert log.get_tool_calls(saved[1]["id"])[0]["call_id"] == "stable-call-id" + + +@pytest.mark.parametrize("stream", [False, True]) +def test_llm_logging_is_opt_in_and_handles_completed_streams(stream): + with ConversationLog(":memory:") as log: + llm = LLM("echo", backend="echo", use_cache=False, conversation_log=log) + result = llm.chat([{"role": "user", "content": "hi"}], stream=stream) + if stream: + list(result) + cid = log.get_conversations()[0]["id"] + assert len(log.get_messages(cid)) == 2 + assert ( + json.loads(log.export_conversation(cid, "openai"))["messages"][-1]["role"] + == "assistant" + ) + + +def test_plain_templates_work_without_yaml_and_directory_errors_are_visible(tmp_path): + text = tmp_path / "plain.txt" + text.write_text('Hello {{name}} {"json":true}', encoding="utf-8") + with mock.patch.dict("sys.modules", {"yaml": None}): + assert ( + PromptTemplate.from_file(str(text)).render(name="World") == 'Hello World {"json":true}' + ) + (tmp_path / "bad.json").write_text("invalid", encoding="utf-8") + with pytest.raises(ValueError, match="bad.json"): + TemplateRegistry().load_directory(str(tmp_path)) + + +def test_hardware_rejects_unknown_measurements_and_invalid_assumptions(): + with mock.patch( + "local_llm_kit.hardware.get_system_memory", + return_value={"available_gpu_vram_gb": 0, "available_ram_gb": 0, "notes": []}, + ): + with pytest.raises(ValueError, match="unknown"): + recommend_quantization(8) + for kwargs in ( + {"params_b": float("nan")}, + {"params_b": 8, "quant": "made-up"}, + {"params_b": 8, "kv_quant": "unknown"}, + {"params_b": 8, "context_length": 2.5}, + ): + with pytest.raises(ValueError): + estimate_model_vram(**kwargs) + exact = estimate_model_vram(8, num_layers=32, num_kv_heads=8, head_dim=128) + assert not exact["architecture_assumed"] + + +def test_retrieval_filter_delete_hybrid_mmr_and_pipeline(): + def embed(text): + return [1.0, 0.0] if "alpha" in text else [0.0, 1.0] + + store = SimpleVectorStore(embed_fn=embed) + ids = store.add( + ["alpha one", "alpha two", "beta only"], + metadatas=[{"group": "a"}, {"group": "a"}, {"group": "b"}], + ) + hits = store.search("alpha", mode="hybrid", lambda_mult=0.4, filter={"group": "a"}) + assert len(hits) == 2 and all(hit["metadata"]["group"] == "a" for hit in hits) + assert store.delete([ids[0]]) == 1 + assert store.search("beta", mode="lexical", filter={"group": "b"})[0]["id"] == ids[2] + pipeline = RAGPipeline(LLM("echo", backend="echo")) + pipeline.add_documents("small offline alpha document", chunk_size=100, chunk_overlap=0) + assert pipeline.query("alpha")["sources"] + assert reciprocal_rank_fusion([[1, 1]])[1] == reciprocal_rank_fusion([[1]])[1] + with pytest.raises(ValueError): + bm25_scores("x", ["x"], k1=float("nan")) + + +def test_retry_policy_rejects_nonfinite_delays_and_headers(): + for value in (float("nan"), float("inf")): + with pytest.raises(ValueError): + RetryPolicy(initial_delay=value) + assert retry_after_seconds({"Retry-After": str(value)}) is None + + +def test_apple_sync_and_stream_timeouts_cancel_cooperative_sdk(): + FakeSystemModel.available, FakeSystemModel.window = True, 4096 + cancelled = threading.Event() + + async def respond(self, *_args, **_kwargs): + try: + await asyncio.sleep(60) + finally: + cancelled.set() + + async def stream(self, *_args, **_kwargs): + try: + await asyncio.sleep(60) + yield "never" + finally: + cancelled.set() + + platform_patch, version_patch = mac_only() + with platform_patch, version_patch, install_fake_sdk(): + backend = AppleFMBackend(timeout=0.05) + with mock.patch.object(FakeSession, "respond", respond): + with pytest.raises((TimeoutError, asyncio.TimeoutError)): + backend.generate("hi") + assert cancelled.is_set() + cancelled.clear() + with mock.patch.object(FakeSession, "stream_response", stream): + with pytest.raises(TimeoutError): + list(backend.generate_stream("hi")) + assert cancelled.wait(0.5) + assert "".join(_stop_deltas(iter(["ok ST", "OP leak"]), ["STOP"])) == "ok " + + +def test_mcp_documented_positional_name_constructs_and_registers_server(): + llm = LLM("echo", backend="echo", use_cache=False) + server = mock.Mock(_opened=True, closed=False) + server.list_tools.return_value = [MCPTool("read")] + with mock.patch("local_llm_kit.mcp.MCPServer", return_value=server) as constructor: + assert llm.add_mcp_server("files", command="fixture") == ["files__read"] + assert constructor.call_args.args[0] == "files" + llm.close() + assert llm.list_tools() == [] + + +def test_logging_deduplicates_full_history_and_tool_calls(): + call = {"id": "same", "type": "function", "function": {"name": "read", "arguments": "{}"}} + user = {"role": "user", "content": "hello"} + assistant = {"role": "assistant", "content": None, "tool_calls": [call]} + with ConversationLog(":memory:") as log: + cid = log.log_interaction( + "fixture", [user], {"choices": [{"message": assistant}]}, tools_used=[call] + ) + messages = log.get_messages(cid) + assert len(log.get_tool_calls(messages[-1]["id"])) == 1 + log.log_interaction( + "fixture", + [user, assistant, {"role": "tool", "tool_call_id": "same", "content": "result"}], + "done", + conversation_id=cid, + ) + assert len(log.get_messages(cid)) == 4 + + +def test_hardware_does_not_invent_ram_or_pool_gpu_capacity(): + from local_llm_kit.hardware import get_system_memory + + def command(*args): + if args[0] == "nvidia-smi": + return "8192,4096\n8192,3072\n" + raise OSError("unavailable") + + with ( + mock.patch("local_llm_kit.hardware.sys.platform", "linux"), + mock.patch("local_llm_kit.hardware.open", side_effect=OSError("no meminfo"), create=True), + mock.patch("local_llm_kit.hardware._command", side_effect=command), + ): + measured = get_system_memory() + assert measured["total_ram_gb"] == 0 + assert measured["gpu_vram_gb"] == 8 and measured["available_gpu_vram_gb"] == 4 + assert len(measured["gpus"]) == 2 + + +def test_reasoning_metadata_survives_nonstream_and_stream_native_chat(): + from local_llm_kit.backends.openai_compat import OpenAICompatBackend + + backend = OpenAICompatBackend("fixture", max_retries=0) + llm = LLM("fixture", backend_instance=backend) + with mock.patch.object( + backend, + "_post_json", + return_value={ + "choices": [{"message": {"content": "answer", "reasoning_content": "metadata"}}] + }, + ): + response = llm.chat([{"role": "user", "content": "hello"}]) + assert response["choices"][0]["message"]["reasoning_content"] == "metadata" + with mock.patch.object( + backend, + "_post_sse", + return_value=iter( + [ + {"choices": [{"delta": {"reasoning_content": "metadata"}}]}, + {"choices": [{"delta": {"content": "answer"}, "finish_reason": "stop"}]}, + ] + ), + ): + chunks = list(llm.chat([{"role": "user", "content": "hello"}], stream=True)) + assert ( + "".join(chunk["choices"][0]["delta"].get("reasoning_content", "") for chunk in chunks) + == "metadata" + ) + + +@pytest.mark.parametrize("timeout", [-1, float("nan"), float("inf"), True]) +def test_invalid_tool_timeout_fails_before_inference_or_execution(timeout): + backend = ToolBackend() + llm = LLM("fixture", backend_instance=backend) + with pytest.raises(ValueError, match="tool_timeout"): + llm.chat([{"role": "user", "content": "hello"}], tool_timeout=timeout) + assert backend.requests == [] + + +@pytest.mark.parametrize("code", [5, 32, 33]) +def test_download_publication_retries_transient_windows_file_locks(tmp_path, code): + from local_llm_kit import models + from tests.test_models import FakeResponse + + destination = tmp_path / "model.gguf" + destination.write_bytes(b"OLD") + error = PermissionError("Windows file temporarily locked") + error.winerror = code + replace = models.os.replace + attempts = [] + + def locked_once(source, target): + attempts.append(source) + if len(attempts) == 1: + assert destination.read_bytes() == b"OLD" + raise error + replace(source, target) + + with ( + mock.patch("urllib.request.urlopen", return_value=FakeResponse(b"COMPLETE")), + mock.patch.object(models.os, "replace", side_effect=locked_once), + mock.patch.object(models.time, "sleep"), + ): + models._download_url("https://huggingface.co/fixture", str(destination)) + assert destination.read_bytes() == b"COMPLETE" and len(attempts) == 2 + assert list(tmp_path.glob("*.part")) == [] + + +def test_download_permanent_publication_failure_preserves_existing_model(tmp_path): + from local_llm_kit import models + from tests.test_models import FakeResponse + + destination = tmp_path / "model.gguf" + destination.write_bytes(b"OLD") + error = PermissionError("permanently inaccessible") + error.winerror = 5 + with ( + mock.patch("urllib.request.urlopen", return_value=FakeResponse(b"NEW")), + mock.patch.object(models.os, "replace", side_effect=error) as replace, + mock.patch.object(models.time, "sleep"), + ): + with pytest.raises(RuntimeError, match="inaccessible"): + models._download_url("https://huggingface.co/fixture", str(destination)) + assert replace.call_count == 4 + assert destination.read_bytes() == b"OLD" + assert list(tmp_path.glob("*.part")) == [] diff --git a/tests/test_conversation_log.py b/tests/test_conversation_log.py new file mode 100644 index 0000000..38ea144 --- /dev/null +++ b/tests/test_conversation_log.py @@ -0,0 +1,254 @@ +"""Offline tests for the SQLite conversation logging module. + +Uses a temporary database file (never the real XDG default path) so tests +are hermetic. Stdlib unittest + sqlite3 only; no model downloads. Python 3.9 +compatible. + +Run: python -m pytest tests/test_conversation_log.py -q +""" + +import json +import os +import tempfile +import unittest +from unittest import mock + +from local_llm_kit.conversation_log import ( + DEFAULT_LOG_PATH, + ConversationLog, + get_conversation_log, +) + + +def _tmp_db(): + fd, path = tempfile.mkstemp(suffix=".db") + os.close(fd) + return path + + +class TestConversationLogCRUD(unittest.TestCase): + def setUp(self): + self.db_path = _tmp_db() + self.addCleanup(os.unlink, self.db_path) + self.log = ConversationLog(self.db_path) + self.addCleanup(self.log.close) + + def test_create_and_get_conversation(self): + conv_id = self.log.create(model="echo", system_prompt="be helpful") + self.assertEqual(len(conv_id), 32) + conv = self.log.get_conversation(conv_id) + self.assertEqual(conv["model"], "echo") + self.assertEqual(conv["system_prompt"], "be helpful") + self.assertIsNone(conv["metadata"]) + + def test_get_conversation_missing_raises(self): + with self.assertRaises(KeyError): + self.log.get_conversation("nope") + + def test_create_with_metadata(self): + conv_id = self.log.create(model="gpt-4o", metadata={"user": "abc"}) + conv = self.log.get_conversation(conv_id) + self.assertEqual(conv["metadata"], {"user": "abc"}) + + def test_delete_conversation_cascade(self): + conv_id = self.log.create(model="echo") + mid = self.log.add_message(conv_id, "user", "hello") + _tid = self.log.add_tool_call(mid, "weather", {"city": "Paris"}) + self.assertEqual(self.log.delete(conv_id), 1) + self.assertEqual(self.log.get_conversations(), []) + self.assertEqual(self.log.get_messages(conv_id), []) + + def test_clear_removes_all(self): + a = self.log.create(model="echo") + self.log.create(model="echo") + self.log.add_message(a, "user", "hi") + self.log.clear() + self.assertEqual(self.log.get_conversations(), []) + + +class TestMessagesAndTools(unittest.TestCase): + def setUp(self): + self.db_path = _tmp_db() + self.addCleanup(os.unlink, self.db_path) + self.log = ConversationLog(self.db_path) + self.addCleanup(self.log.close) + self.conv_id = self.log.create(model="echo") + + def test_add_and_retrieve_messages(self): + self.log.add_message(self.conv_id, "user", "hello") + self.log.add_message( + self.conv_id, "assistant", "hi there", model="echo", finish_reason="stop" + ) + msgs = self.log.get_messages(self.conv_id) + self.assertEqual(len(msgs), 2) + self.assertEqual(msgs[0]["content"], "hello") + self.assertEqual(msgs[1]["role"], "assistant") + self.assertEqual(msgs[1]["finish_reason"], "stop") + self.assertEqual(msgs[1]["model"], "echo") + self.assertEqual(msgs[1]["prompt_tokens"], None) + + def test_add_tool_call_arguments_dict_and_str(self): + mid = self.log.add_message(self.conv_id, "assistant", None) + self.log.add_tool_call(mid, "weather", {"city": "Paris"}, result="sunny") + self.log.add_tool_call(mid, "search", '{"q": "cats"}', result=None) + calls = self.log.get_tool_calls(mid) + self.assertEqual(len(calls), 2) + self.assertEqual(calls[0]["name"], "weather") + self.assertEqual(calls[0]["arguments"], {"city": "Paris"}) + self.assertEqual(calls[0]["result"], "sunny") + self.assertEqual(calls[1]["name"], "search") + self.assertEqual(calls[1]["arguments"], {"q": "cats"}) + + def test_get_conversation_history_enriched(self): + mid = self.log.add_message(self.conv_id, "assistant", "call") + self.log.add_tool_call(mid, "weather", {"city": "Paris"}) + history = self.log.get_conversation_history(self.conv_id) + self.assertEqual(len(history), 1) + self.assertEqual(history[0]["tool_calls"][0]["name"], "weather") + + def test_get_conversation_history_no_tool_details(self): + self.log.add_message(self.conv_id, "user", "hi") + history = self.log.get_conversation_history(self.conv_id, include_tool_details=False) + self.assertNotIn("tool_calls", history[0]) + + def test_search_like(self): + self.log.add_message(self.conv_id, "user", "tell me about cats") + self.log.add_message(self.conv_id, "user", "something else") + results = self.log.search("cats") + self.assertEqual(len(results), 1) + self.assertEqual(results[0]["content"], "tell me about cats") + + +class TestLogInteraction(unittest.TestCase): + def setUp(self): + self.db_path = _tmp_db() + self.addCleanup(os.unlink, self.db_path) + self.log = ConversationLog(self.db_path) + self.addCleanup(self.log.close) + + def test_log_interaction_creates_conversation(self): + conv_id = self.log.log_interaction( + model="echo", + messages=[{"role": "user", "content": "hello"}], + response={"choices": [{"message": {"content": "hi", "role": "assistant"}}]}, + ) + history = self.log.get_conversation_history(conv_id) + self.assertEqual(len(history), 2) # user + assistant + + def test_log_interaction_with_tool_calls(self): + resp = { + "choices": [ + { + "message": { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": {"name": "weather", "arguments": '{"city": "Paris"}'}, + } + ], + } + } + ] + } + conv_id = self.log.log_interaction( + model="echo", + messages=[{"role": "user", "content": "weather?"}], + response=resp, + ) + history = self.log.get_conversation_history(conv_id) + assistant_msg = history[1] + self.assertEqual(assistant_msg["tool_calls"][0]["name"], "weather") + self.assertEqual(assistant_msg["tool_calls"][0]["arguments"], {"city": "Paris"}) + + def test_log_interaction_reuses_conversation_id(self): + conv_id = self.log.log_interaction( + model="echo", + messages=[{"role": "user", "content": "first"}], + response={"choices": [{"message": {"content": "one"}}]}, + ) + self.log.log_interaction( + model="echo", + messages=[{"role": "user", "content": "second"}], + response={"choices": [{"message": {"content": "two"}}]}, + conversation_id=conv_id, + ) + msgs = self.log.get_messages(conv_id) + self.assertEqual(len(msgs), 4) + + def test_log_interaction_plain_string_response(self): + conv_id = self.log.log_interaction( + model="echo", + messages=[{"role": "user", "content": "hi"}], + response="hello back", + ) + msgs = self.log.get_messages(conv_id) + self.assertEqual(msgs[-1]["content"], "hello back") + + +class TestExportConversation(unittest.TestCase): + def setUp(self): + self.db_path = _tmp_db() + self.addCleanup(os.unlink, self.db_path) + self.log = ConversationLog(self.db_path) + self.addCleanup(self.log.close) + self.conv_id = self.log.log_interaction( + model="echo", + messages=[ + {"role": "user", "content": "hello"}, + {"role": "system", "content": "be nice"}, + ], + response={"choices": [{"message": {"content": "hi"}}]}, + ) + + def test_export_json(self): + out = self.log.export_conversation(self.conv_id, "json") + data = json.loads(out) + self.assertIn("conversation", data) + self.assertIn("history", data) + + def test_export_text(self): + out = self.log.export_conversation(self.conv_id, "text") + self.assertIn("Conversation", out) + self.assertIn("Assistant: hi", out) + + def test_export_openai_format(self): + out = self.log.export_conversation(self.conv_id, "openai") + data = json.loads(out) + self.assertIn("messages", data) + self.assertEqual(data["model"], "echo") + + def test_export_invalid_format(self): + with self.assertRaises(ValueError): + self.log.export_conversation(self.conv_id, "xml") + + +class TestDefaultLogPath(unittest.TestCase): + def test_default_log_path_constant(self): + self.assertTrue(DEFAULT_LOG_PATH.endswith("conversation_logs.db")) + + def test_get_conversation_log_explicit_not_cached(self): + path = _tmp_db() + self.addCleanup(os.unlink, path) + log = get_conversation_log(path) + self.addCleanup(log.close) + self.assertIsInstance(log, ConversationLog) + self.assertEqual(log._path, path) + + def test_get_conversation_log_none_uses_default_and_caches(self): + # When path is None, the module-level cached instance is returned. + # We patch DEFAULT_LOG_PATH to a temp file so we don't touch ~/.local. + fd, tmp = tempfile.mkstemp(suffix=".db") + os.close(fd) + self.addCleanup(os.unlink, tmp) + with mock.patch("local_llm_kit.conversation_log.DEFAULT_LOG_PATH", tmp): + first = get_conversation_log(None) + self.addCleanup(first.close) + second = get_conversation_log(None) + self.assertIs(first, second) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_discovery.py b/tests/test_discovery.py new file mode 100644 index 0000000..51ad542 --- /dev/null +++ b/tests/test_discovery.py @@ -0,0 +1,624 @@ +"""Offline tests for local server discovery and capability reporting. + +Everything here runs against a local stdlib HTTP fixture or a closed port, so +the suite stays offline and deterministic. The fixture reproduces the response +shapes of Ollama, llama.cpp's llama-server, LM Studio and apfel as their own +documentation/source describes them. + +Real-server checks live in ``tests/test_live_servers.py`` and are opt-in. +""" + +import json +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from local_llm_kit import LLM, discover, find_local_server, probe_endpoint +from local_llm_kit.backends import OPENAI_SERVER_URLS +from local_llm_kit.backends.ollama import OllamaBackend +from local_llm_kit.discovery import ( + DEFAULT_TIMEOUT, + ENDPOINTS, + DiscoveryReport, + ModelRecord, + ServerReport, + normalize_base_url, +) + +# Profile names the fixture understands. +OLLAMA = "ollama" +LLAMA_SERVER = "llama-server" +LMSTUDIO = "lmstudio" +APFEL = "apfel" +NOT_JSON = "not-json" +BROKEN = "broken" +NO_MODELS = "no-models" + + +class Handler(BaseHTTPRequestHandler): + """Protocol fixture: serves the documented shape for ``profile``.""" + + profile = OLLAMA + requests = [] + + def log_message(self, *args): + pass + + # -- responses ----------------------------------------------------- + + def _json(self, payload, status=200): + encoded = json.dumps(payload).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + def _text(self, body, status=200): + encoded = body.encode() + self.send_response(status) + self.send_header("Content-Type", "text/plain; charset=utf-8") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + def do_GET(self): + Handler.requests.append(("GET", self.path)) + path = self.path.split("?")[0] + profile = Handler.profile + + if path == "/": + if profile == NOT_JSON: + return self._text("Ollama is running") + return self._json({"status": "ok"}) + + if path in ("/api/v1/models", "/api/v0/models"): + if profile == LMSTUDIO and path == "/api/v1/models": + return self._json( + { + "models": [ + { + "type": "llm", + "key": "google/gemma-3-4b", + "capabilities": { + "vision": True, + "trained_for_tool_use": True, + }, + "max_context_length": 131072, + "format": "gguf", + } + ] + } + ) + return self._json({"error": "not found"}, status=404) + + if path.endswith("/models"): + if profile == BROKEN: + return self._json({"error": "boom"}, status=500) + if profile == NOT_JSON: + # A web server or proxy squatting on the port: HTTP 200, not JSON. + return self._text("AirPlay") + return self._json(self._models_payload()) + + if path == "/api/tags": + if profile == OLLAMA: + return self._json(self._ollama_tags()) + return self._json({"error": "not found"}, status=404) + + if path == "/props": + if profile == LLAMA_SERVER: + return self._json( + { + "model_path": "/models/tiny.gguf", + "total_slots": 1, + "default_generation_settings": {"n_ctx": 8192}, + "modalities": {"vision": False}, + } + ) + return self._json({"error": "not found"}, status=404) + + return self._json({"error": "not found"}, status=404) + + def do_POST(self): + Handler.requests.append(("POST", self.path)) + length = int(self.headers.get("Content-Length") or 0) + body = json.loads(self.rfile.read(length)) if length else {} + if self.path == "/api/show": + if Handler.profile != OLLAMA: + return self._json({"error": "not found"}, status=404) + if body.get("model") == "broken:latest": + return self._json({"error": "server exploded"}, status=500) + return self._json( + { + "capabilities": ["completion", "tools"], + "model_info": {"qwen2.context_length": 32768}, + } + ) + return self._json({"error": "not found"}, status=404) + + # -- payloads ------------------------------------------------------ + + def _models_payload(self): + profile = Handler.profile + if profile == OLLAMA: + return { + "object": "list", + "data": [ + { + "id": "qwen2.5:0.5b", + "object": "model", + "owned_by": "library", + "details": {"family": "qwen2", "context_length": 32768}, + } + ], + } + if profile == LLAMA_SERVER: + return { + "object": "list", + "data": [ + { + "id": "/models/tiny.gguf", + "object": "model", + "owned_by": "llamacpp", + "meta": {"n_ctx_train": 131072, "n_params": 8030261312}, + } + ], + } + if profile == LMSTUDIO: + return { + "object": "list", + "data": [ + {"id": "google/gemma-3-4b", "object": "model", "owned_by": "organization_owner"} + ], + } + if profile == APFEL: + return { + "object": "list", + "data": [ + { + "id": "apple-foundationmodel", + "object": "model", + "owned_by": "apple", + "context_window": 4096, + "capabilities": ["tool_calling", "guided_generation"], + } + ], + } + if profile == NO_MODELS: + # text-generation-webui answers 200 with an empty list until a + # model is loaded; a probe must not call that "ready". + return {"object": "list", "data": []} + return {"object": "list", "data": [{"id": "custom-model", "object": "model"}]} + + def _ollama_tags(self): + return { + "models": [ + { + "name": "qwen2.5:0.5b", + "model": "qwen2.5:0.5b", + "details": {"family": "qwen2", "context_length": 32768}, + "capabilities": ["completion", "tools"], + }, + { + "name": "big:cloud", + "model": "big:cloud", + "remote_model": "big", + "remote_host": "https://ollama.com:443", + "details": {"family": "big"}, + "capabilities": ["completion", "tools", "thinking"], + }, + ] + } + + +class Fixture: + """Run the fixture server with one profile at a time.""" + + def __init__(self): + self.server = None + self.thread = None + + def __enter__(self): + Handler.requests.clear() + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.url = "http://127.0.0.1:%d" % self.server.server_port + return self + + def __exit__(self, *exc): + self.server.shutdown() + self.server.server_close() + self.thread.join(timeout=5) + + +def profile(name): + """Context manager selecting the fixture's response profile.""" + + class _Profile: + def __enter__(self): + Handler.profile = name + return self + + def __exit__(self, *exc): + Handler.profile = OLLAMA + + return _Profile() + + +def dead_url(): + """A loopback port that is bound then released, so nothing is listening.""" + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + port = server.server_port + server.server_close() + return "http://127.0.0.1:%d/v1" % port + + +class TestNormalizeBaseUrl(unittest.TestCase): + def test_accepts_what_users_actually_paste(self): + cases = { + "localhost:11434": "http://localhost:11434/v1", + "127.0.0.1:1234": "http://127.0.0.1:1234/v1", + "http://localhost:8000": "http://localhost:8000/v1", + "http://localhost:8000/v1": "http://localhost:8000/v1", + "http://localhost:8000/v1/": "http://localhost:8000/v1", + "http://localhost:8000/v1/chat/completions": "http://localhost:8000/v1", + "http://localhost:8000/v1/models": "http://localhost:8000/v1", + "https://box.local:8443/v1": "https://box.local:8443/v1", + "http://h:8080/v1/models?x=1": "http://h:8080/v1", + } + for raw, expected in cases.items(): + with self.subTest(raw=raw): + self.assertEqual(normalize_base_url(raw), expected) + + def test_rejects_empty_and_hostless_input(self): + for bad in ("", " ", "http://"): + with self.subTest(bad=bad): + with self.assertRaises(ValueError): + normalize_base_url(bad) + with self.assertRaises(ValueError): + normalize_base_url(None) + + +class TestProviderFingerprinting(unittest.TestCase): + def test_each_profile_is_identified_from_its_own_payload(self): + cases = [ + (OLLAMA, "ollama"), + (LLAMA_SERVER, "llama-server"), + (LMSTUDIO, "lmstudio"), + (APFEL, "apfel"), + ] + with Fixture() as fixture: + for name, expected in cases: + with self.subTest(profile=name), profile(name): + report = probe_endpoint(fixture.url + "/v1", timeout=2.0) + self.assertTrue(report.live, report.error) + self.assertEqual(report.provider, expected) + + def test_a_non_json_200_is_not_mistaken_for_a_model_listing(self): + # Ports in the probe range are often taken by other software (macOS + # AirPlay answers 200 on :5000), so a 200 alone must not mean "server". + with Fixture() as fixture, profile(NOT_JSON): + report = probe_endpoint(fixture.url + "/v1", timeout=2.0) + self.assertFalse(report.live) + self.assertEqual(report.models, []) + self.assertIn("invalid JSON", report.error or "") + + +class TestCapabilityEnrichment(unittest.TestCase): + def test_ollama_context_length_and_capabilities_come_from_the_server(self): + with Fixture() as fixture, profile(OLLAMA): + report = probe_endpoint(fixture.url + "/v1", timeout=2.0) + model = next(m for m in report.models if m.id == "qwen2.5:0.5b") + self.assertEqual(model.context_length, 32768) + self.assertEqual(model.capabilities, ["completion", "tools"]) + self.assertTrue(model.supports_tools) + self.assertFalse(model.supports_vision) + + def test_llama_server_context_comes_from_props(self): + with Fixture() as fixture, profile(LLAMA_SERVER): + report = probe_endpoint(fixture.url + "/v1", timeout=2.0) + self.assertEqual(report.context_window, 8192) + self.assertIs(report.vision, False) + self.assertTrue(any("tiny.gguf" in note for note in report.notes)) + + def test_lmstudio_native_api_supplies_vision_and_tool_capabilities(self): + with Fixture() as fixture, profile(LMSTUDIO): + report = probe_endpoint(fixture.url + "/v1", timeout=2.0) + model = report.models[0] + self.assertIn("vision", model.capabilities) + self.assertIn("tools", model.capabilities) + self.assertEqual(model.context_length, 131072) + + def test_apfel_capabilities_come_from_its_own_model_payload(self): + with Fixture() as fixture, profile(APFEL): + report = probe_endpoint(fixture.url + "/v1", timeout=2.0) + self.assertEqual(report.context_window, None) + self.assertEqual(report.models[0].context_length, 4096) + self.assertEqual(report.models[0].capabilities, ["tool_calling", "guided_generation"]) + + def test_enrichment_failure_degrades_to_a_note_not_an_exception(self): + with Fixture() as fixture, profile(BROKEN): + report = probe_endpoint(fixture.url + "/v1", timeout=2.0) + self.assertFalse(report.live) + self.assertIsNotNone(report.error) + self.assertIsInstance(report.notes, list) + + +class TestOffDeviceDetection(unittest.TestCase): + def test_remote_host_marks_a_model_as_off_device(self): + with Fixture() as fixture, profile(OLLAMA): + report = probe_endpoint(fixture.url + "/v1", timeout=2.0) + remote = [m for m in report.models if m.remote] + self.assertEqual([m.id for m in remote], ["big:cloud"]) + self.assertEqual(remote[0].remote_host, "https://ollama.com:443") + self.assertTrue(any("off-device" in note for note in report.notes)) + + def test_a_mixed_server_still_offers_on_device_models(self): + with Fixture() as fixture, profile(OLLAMA): + report = probe_endpoint(fixture.url + "/v1", timeout=2.0) + self.assertTrue(report.has_local_models) + self.assertFalse(report.all_local) + self.assertEqual([m.id for m in report.local_models], ["qwen2.5:0.5b"]) + + def test_cloud_tag_without_remote_host_is_still_off_device(self): + record = ModelRecord(id="x:cloud", capabilities=[]) + self.assertFalse(record.remote) + from local_llm_kit.discovery import _looks_remote + + self.assertTrue(_looks_remote("x:cloud", {})[0]) + self.assertFalse(_looks_remote("x:latest", {})[0]) + + +class TestReportSemantics(unittest.TestCase): + def _report(self): + local_only = ServerReport( + base_url="http://127.0.0.1:10001/v1", + provider="ollama", + live=True, + models=[ModelRecord(id="small", local_verified=True)], + ) + mixed = ServerReport( + base_url="http://127.0.0.1:10002/v1", + provider="ollama", + live=True, + models=[ + ModelRecord(id="small", local_verified=True), + ModelRecord(id="big:cloud", remote=True, remote_host="h"), + ], + ) + remote_only = ServerReport( + base_url="http://127.0.0.1:10003/v1", + provider="ollama", + live=True, + models=[ModelRecord(id="big:cloud", remote=True, remote_host="h")], + ) + return DiscoveryReport(servers=[remote_only, mixed, local_only], probed=3) + + def test_all_local_requires_models_and_no_remote_ones(self): + report = self._report() + self.assertEqual([s.base_url for s in report.local_only()], ["http://127.0.0.1:10001/v1"]) + self.assertEqual( + [s.base_url for s in report.on_device()], + ["http://127.0.0.1:10002/v1", "http://127.0.0.1:10001/v1"], + ) + + def test_require_local_skips_remote_only_servers(self): + report = self._report() + self.assertEqual( + report.first_live(require_local=True).base_url, "http://127.0.0.1:10002/v1" + ) + self.assertEqual(report.first_live().base_url, "http://127.0.0.1:10002/v1") + + def test_report_is_json_serialisable(self): + payload = json.dumps(self._report().to_dict()) + self.assertIn("servers", json.loads(payload)) + + +class TestDiscover(unittest.TestCase): + def test_probes_extra_urls_only_when_asked(self): + with Fixture() as fixture, profile(OLLAMA): + report = discover(include_known=False, extra_urls=[fixture.url], timeout=2.0) + self.assertEqual(report.probed, 1) + self.assertTrue(report.servers[0].live) + + def test_duplicate_endpoints_are_probed_once(self): + # Ollama (11434) and apfel (11434) share a port, as do llama-server, + # LocalAI, mlx-lm and llamafile (8080) - each must be probed once. + report = discover(include_known=True, extra_urls=[], timeout=0.05) + urls = [s.base_url for s in report.servers] + self.assertEqual(len(urls), len(set(urls))) + self.assertEqual(report.probed, len(set(normalize_base_url(e.base_url) for e in ENDPOINTS))) + + def test_unreachable_endpoints_are_reported_not_raised(self): + report = discover(include_known=False, extra_urls=[dead_url()], timeout=0.5) + self.assertEqual(len(report.offline), 1) + self.assertTrue(report.offline[0].error) + self.assertIsNone(report.offline[0].status) + + def test_find_local_server_returns_none_when_nothing_answers(self): + self.assertIsNone( + find_local_server(include_known=False, extra_urls=[dead_url()], timeout=0.3) + ) + + def test_find_local_server_returns_the_on_device_one(self): + with Fixture() as fixture, profile(OLLAMA): + found = find_local_server(include_known=False, extra_urls=[fixture.url], timeout=2.0) + self.assertIsNotNone(found) + self.assertEqual(found.provider, "ollama") + self.assertTrue(found.has_local_models) + + def test_invalid_arguments_are_rejected(self): + with self.assertRaises(ValueError): + discover(timeout=0) + with self.assertRaises(ValueError): + discover(max_workers=0) + with self.assertRaises(ValueError): + probe_endpoint("http://127.0.0.1:1/v1", timeout=-1) + with self.assertRaises(ValueError): + discover(include_known=False, extra_urls=[""]) + + def test_default_timeout_is_short_enough_for_interactive_use(self): + self.assertLessEqual(DEFAULT_TIMEOUT, 1.0) + + +class TestOllamaTruthfulCapabilities(unittest.TestCase): + def test_list_models_exposes_capabilities_context_and_remote(self): + with Fixture() as fixture, profile(OLLAMA): + models = OllamaBackend("qwen2.5:0.5b", host=fixture.url).list_models() + by_id = {m["id"]: m for m in models} + self.assertEqual(by_id["qwen2.5:0.5b"]["capabilities"], ["completion", "tools"]) + self.assertEqual(by_id["qwen2.5:0.5b"]["context_length"], 32768) + self.assertNotIn("remote", by_id["qwen2.5:0.5b"]) + self.assertTrue(by_id["big:cloud"]["remote"]) + self.assertEqual(by_id["big:cloud"]["remote_host"], "https://ollama.com:443") + + def test_detect_capabilities_reports_the_real_context_window(self): + with Fixture() as fixture, profile(OLLAMA): + backend = OllamaBackend("qwen2.5:0.5b", host=fixture.url) + before = backend.get_context_window() + result = backend.detect_capabilities() + self.assertEqual(before, 4096) + self.assertTrue(result["detected"]) + self.assertEqual(result["context_window"], 32768) + self.assertEqual(backend.get_context_window(), 32768) + self.assertFalse(backend.remote) + + def test_supports_vision_follows_the_server_not_the_adapter(self): + with Fixture() as fixture, profile(OLLAMA): + backend = OllamaBackend("qwen2.5:0.5b", host=fixture.url) + self.assertTrue(backend.supports_vision) # optimistic before detection + backend.detect_capabilities() + self.assertFalse(backend.supports_vision) # server says text only + + def test_detection_failure_keeps_the_fallback_and_reports_the_error(self): + backend = OllamaBackend("qwen2.5:0.5b", host=dead_url(), timeout=0.4) + result = backend.detect_capabilities(timeout=0.4) + self.assertFalse(result["detected"]) + self.assertIsNotNone(result["error"]) + self.assertEqual(backend.get_context_window(), 4096) + + def test_auto_detect_makes_the_llm_report_the_real_window(self): + with Fixture() as fixture, profile(OLLAMA): + llm = LLM( + "qwen2.5:0.5b", + backend="ollama", + use_cache=False, + backend_kwargs={"host": fixture.url, "auto_detect_capabilities": True}, + ) + self.assertEqual(llm.context_window, 32768) + self.assertEqual(llm.memory.context_window, 32768) + + def test_model_info_reports_capabilities_once_detected(self): + with Fixture() as fixture, profile(OLLAMA): + backend = OllamaBackend("qwen2.5:0.5b", host=fixture.url) + backend.detect_capabilities() + info = backend.model_info() + self.assertEqual(info["capabilities"], ["completion", "tools"]) + self.assertFalse(info["supports_vision"]) + + +class TestRequireLocal(unittest.TestCase): + def test_on_device_model_is_accepted(self): + with Fixture() as fixture, profile(OLLAMA): + llm = LLM( + "qwen2.5:0.5b", + backend="ollama", + use_cache=False, + require_local=True, + backend_kwargs={"host": fixture.url}, + ) + self.assertTrue(llm.assert_local()) + self.assertEqual(llm.context_window, 32768) + + def test_off_device_model_is_refused_with_the_remote_host(self): + with Fixture() as fixture, profile(OLLAMA): + with self.assertRaises(RuntimeError) as ctx: + LLM( + "big:cloud", + backend="ollama", + use_cache=False, + require_local=True, + backend_kwargs={"host": fixture.url}, + ) + self.assertIn("ollama.com", str(ctx.exception)) + + def test_unverifiable_guarantee_is_refused_not_assumed(self): + with self.assertRaises(RuntimeError) as ctx: + LLM( + "qwen2.5:0.5b", + backend="ollama", + use_cache=False, + require_local=True, + backend_kwargs={"host": dead_url(), "timeout": 0.4}, + ) + self.assertIn("Could not confirm", str(ctx.exception)) + + def test_backends_without_a_remote_concept_are_a_no_op(self): + llm = LLM("echo", backend="echo", use_cache=False, require_local=True) + self.assertTrue(llm.assert_local()) + self.assertFalse(llm.detect_backend_capabilities()["supported"]) + + +class TestLlamaServerPresetPort(unittest.TestCase): + def test_preset_matches_the_current_upstream_default(self): + # llama.cpp moved its default port from 8080 to 9931 (PR #30159, + # merged 2026-10-09). The Docker image still binds 8080. + self.assertEqual(OPENAI_SERVER_URLS["llama-server"], "http://localhost:9931/v1") + + def test_both_historical_ports_are_probed(self): + ports = {normalize_base_url(e.base_url) for e in ENDPOINTS} + self.assertIn("http://127.0.0.1:9931/v1", ports) + self.assertIn("http://127.0.0.1:8080/v1", ports) + + +if __name__ == "__main__": + unittest.main() + + +class TestEndpointCatalog(unittest.TestCase): + def test_docker_model_runner_keeps_its_engines_prefix(self): + # OpenAI compatibility lives under /engines, not at the root + # (Docker model-runner API reference), so the prefix must survive + # normalisation rather than being rewritten to /v1. + normalized = normalize_base_url("http://127.0.0.1:12434/engines/v1") + self.assertEqual(normalized, "http://127.0.0.1:12434/engines/v1") + self.assertIn(normalized, {normalize_base_url(e.base_url) for e in ENDPOINTS}) + + def test_fm_serve_port_is_probed(self): + ports = {normalize_base_url(e.base_url) for e in ENDPOINTS} + self.assertIn("http://127.0.0.1:1976/v1", ports) + + def test_shared_ports_do_not_break_identification(self): + # 11434 is both Ollama's and apfel's default; 8080 is llama.cpp's old + # default, LocalAI's, MLX-LM's and llamafile's. + by_url = {} + for endpoint in ENDPOINTS: + by_url.setdefault(normalize_base_url(endpoint.base_url), []).append(endpoint.provider) + self.assertGreater(len(by_url["http://127.0.0.1:11434/v1"]), 1) + self.assertGreater(len(by_url["http://127.0.0.1:8080/v1"]), 1) + + +class TestNotReadyServers(unittest.TestCase): + def test_an_empty_model_list_is_live_but_not_usable(self): + with Fixture() as fixture, profile(NO_MODELS): + report = probe_endpoint(fixture.url + "/v1", timeout=2.0) + self.assertTrue(report.live) + self.assertEqual(report.models, []) + self.assertFalse(report.has_local_models) + self.assertFalse(report.all_local) + self.assertTrue(any("lists no models" in note for note in report.notes)) + + def test_a_server_that_is_still_loading_reports_the_status(self): + with Fixture() as fixture, profile(BROKEN): + report = probe_endpoint(fixture.url + "/v1", timeout=2.0) + self.assertFalse(report.live) + self.assertEqual(report.status, 500) + self.assertTrue(any("still be loading" in note for note in report.notes)) + + def test_loading_servers_are_kept_out_of_the_on_device_set(self): + with Fixture() as fixture, profile(NO_MODELS): + report = discover(include_known=False, extra_urls=[fixture.url], timeout=2.0) + self.assertEqual(len(report.live), 1) + self.assertEqual(report.on_device(), []) + self.assertIsNone(report.first_live(require_local=True)) diff --git a/tests/test_hardware.py b/tests/test_hardware.py new file mode 100644 index 0000000..fd57261 --- /dev/null +++ b/tests/test_hardware.py @@ -0,0 +1,48 @@ +"""Tests for hardware inspection and VRAM estimation.""" + +import unittest + +from local_llm_kit.hardware import estimate_model_vram, get_system_memory, recommend_quantization + + +class TestHardware(unittest.TestCase): + def test_get_system_memory(self): + mem = get_system_memory() + self.assertIn("total_ram_gb", mem) + self.assertIn("available_ram_gb", mem) + self.assertIn("gpu_vram_gb", mem) + self.assertGreater(mem["total_ram_gb"], 0.0) + + def test_estimate_model_vram_formula(self): + # 8B model at Q4_K_M (4.5 bpw) @ 4096 context + est = estimate_model_vram(params_b=8.0, quant="Q4_K_M", context_length=4096) + self.assertGreater(est["weights_gb"], 3.5) + self.assertLess(est["weights_gb"], 5.0) + self.assertGreater(est["kv_cache_gb"], 0.1) + self.assertGreater(est["total_gb"], est["weights_gb"]) + + def test_estimate_model_vram_quant_scaling(self): + # Q8_0 weights must be larger than Q4_K_M + est_q4 = estimate_model_vram(params_b=7.0, quant="Q4_K_M", context_length=4096) + est_q8 = estimate_model_vram(params_b=7.0, quant="Q8_0", context_length=4096) + est_fp16 = estimate_model_vram(params_b=7.0, quant="FP16", context_length=4096) + + self.assertLess(est_q4["weights_gb"], est_q8["weights_gb"]) + self.assertLess(est_q8["weights_gb"], est_fp16["weights_gb"]) + + def test_recommend_quantization_fit(self): + # With 24GB available, an 8B model should comfortably fit Q8_0 or FP16 + rec = recommend_quantization(params_b=8.0, available_memory_gb=24.0, context_length=4096) + self.assertEqual(rec["status"], "fits_comfortably") + self.assertIn("Recommended", rec["recommendation"]) + + # With only 3GB available, an 8B model will exceed budget + rec_tight = recommend_quantization( + params_b=8.0, available_memory_gb=3.0, context_length=4096 + ) + self.assertEqual(rec_tight["status"], "exceeds_budget") + self.assertIn("Warning", rec_tight["recommendation"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hybrid_rag.py b/tests/test_hybrid_rag.py new file mode 100644 index 0000000..48fe2bd --- /dev/null +++ b/tests/test_hybrid_rag.py @@ -0,0 +1,119 @@ +"""Tests for BM25, Reciprocal Rank Fusion, Hybrid Search, and RAGPipeline.""" + +import unittest +from unittest.mock import MagicMock + +from local_llm_kit.embeddings import hash_embed +from local_llm_kit.rag import ( + RAGPipeline, + SimpleVectorStore, + bm25_scores, + reciprocal_rank_fusion, +) + + +def fake_embed(texts): + if isinstance(texts, str): + texts = [texts] + return hash_embed(list(texts), dim=32) + + +class TestHybridRAG(unittest.TestCase): + def test_bm25_scores_computation(self): + docs = [ + "the quick brown fox jumps over the lazy dog", + "the dog chased the cat up the tree", + "python programming with local models and rag", + ] + scores = bm25_scores("python rag", docs) + self.assertEqual(len(scores), 3) + # Doc 2 must score highest for "python rag" + self.assertGreater(scores[2], scores[0]) + self.assertGreater(scores[2], scores[1]) + + def test_reciprocal_rank_fusion(self): + # Two ranking lists + rank_a = [0, 1, 2] + rank_b = [1, 0, 2] + fused = reciprocal_rank_fusion([rank_a, rank_b], rrf_k=60) + self.assertIn(0, fused) + self.assertIn(1, fused) + self.assertIn(2, fused) + # Item 0 and 1 have same fused score, both higher than 2 + self.assertAlmostEqual(fused[0], fused[1]) + self.assertGreater(fused[0], fused[2]) + + def test_simple_vector_store_delete(self): + store = SimpleVectorStore(embed_fn=fake_embed) + store.add(["doc a", "doc b", "doc c"], ids=["a", "b", "c"]) + self.assertEqual(len(store), 3) + + deleted = store.delete(["b"]) + self.assertEqual(deleted, 1) + self.assertEqual(len(store), 2) + self.assertEqual(store.ids, ["a", "c"]) + self.assertEqual(store.texts, ["doc a", "doc c"]) + + def test_simple_vector_store_metadata_filtering(self): + store = SimpleVectorStore(embed_fn=fake_embed) + store.add( + ["report 2024", "report 2025", "internal wiki"], + metadatas=[ + {"year": 2024, "dept": "finance"}, + {"year": 2025, "dept": "finance"}, + {"year": 2025, "dept": "engineering"}, + ], + ids=["r1", "r2", "w1"], + ) + + # Filter by dict exact match + hits = store.search("report", k=5, filter={"dept": "finance", "year": 2024}) + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0]["id"], "r1") + + # Filter by callable predicate + hits_fn = store.search("report", k=5, filter=lambda m: m.get("year", 0) >= 2025) + self.assertEqual(len(hits_fn), 2) + ids_returned = {h["id"] for h in hits_fn} + self.assertEqual(ids_returned, {"r2", "w1"}) + + def test_simple_vector_store_hybrid_mode(self): + store = SimpleVectorStore(embed_fn=fake_embed) + store.add( + [ + "PostgreSQL database query optimization and indexes", + "Deep learning neural networks and transformer backends", + "Kubernetes container deployment and helm charts", + ], + ids=["sql", "ml", "k8s"], + ) + + # Hybrid search combining semantic embedding and BM25 lexical token match + hits = store.search("PostgreSQL indexes", k=2, mode="hybrid") + self.assertGreaterEqual(len(hits), 1) + self.assertEqual(hits[0]["id"], "sql") + + def test_rag_pipeline_end_to_end(self): + mock_llm = MagicMock() + mock_llm.chat.return_value = { + "choices": [ + {"message": {"role": "assistant", "content": "According to [1], sky is blue."}} + ] + } + + pipeline = RAGPipeline(llm=mock_llm, embed_fn=fake_embed) + chunk_ids = pipeline.add_documents( + ["The sky on Mars looks butterscotch, but on Earth the sky is blue."], + chunk_size=100, + chunk_overlap=20, + ) + self.assertGreater(len(chunk_ids), 0) + + result = pipeline.query("What color is the sky on Earth?", k=2, mode="hybrid") + self.assertIn("sky is blue", result["answer"]) + self.assertEqual(len(result["sources"]), 1) + self.assertTrue(mock_llm.chat.called) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_live_servers.py b/tests/test_live_servers.py new file mode 100644 index 0000000..e0f3d72 --- /dev/null +++ b/tests/test_live_servers.py @@ -0,0 +1,226 @@ +"""Opt-in integration tests against a REAL local LLM server. + +These are the tests that certify the discovery layer and the Ollama capability +reporting against an actual server rather than a fixture. They are skipped +unless ``LOCAL_LLM_KIT_LIVE=1`` is set, so the default suite stays offline. + + LOCAL_LLM_KIT_LIVE=1 python -m pytest tests/test_live_servers.py -q + +What they require: + * A local OpenAI-compatible or Ollama server listening on one of the + well-known ports (``local-llm-kit doctor`` prints the catalog). + * For the inference tests, at least one model that runs **on this machine**. + Provider-routed models (Ollama ``:cloud``) are deliberately never used: + they leave the device, so they cannot certify local inference. + * No credentials and no network access beyond loopback. + +Tests skip individually when the machine cannot satisfy them, and report why. +""" + +import json +import os +import unittest + +from local_llm_kit import LLM, discover +from local_llm_kit.discovery import find_local_server, normalize_base_url, probe_endpoint + +LIVE = os.environ.get("LOCAL_LLM_KIT_LIVE", "").strip() == "1" +SKIP_REASON = "set LOCAL_LLM_KIT_LIVE=1 (with a local server running) to run" + +_report_cache = {} + + +def live_report(): + """Discover once per test session and reuse.""" + if "report" not in _report_cache: + _report_cache["report"] = discover(timeout=1.5) + return _report_cache["report"] + + +def on_device_server(): + """The first live server offering an on-device model, or None.""" + for server in live_report().on_device(): + return server + return None + + +def on_device_model(server): + """The first model on *server* that is not provider-routed.""" + for model in server.local_models: + return model + return None + + +@unittest.skipUnless(LIVE, SKIP_REASON) +class TestDiscoveryAgainstRealServer(unittest.TestCase): + def test_a_local_server_is_found_within_the_interactive_budget(self): + report = live_report() + self.assertTrue(report.live, "no local server found; run `local-llm-kit doctor`") + self.assertLess(report.elapsed_ms, 5000, "discovery must stay interactive") + print( + "\n[live] probed %d endpoints in %sms; live: %s" + % (report.probed, report.elapsed_ms, [s.base_url for s in report.live]) + ) + + def test_provider_is_identified_from_live_payloads(self): + for server in live_report().live: + with self.subTest(base_url=server.base_url): + self.assertNotEqual(server.provider, "unknown") + self.assertNotEqual(server.provider, "custom") + print("\n[live] %s -> %s" % (server.base_url, server.provider)) + + def test_reported_capabilities_match_a_direct_probe(self): + for server in live_report().live: + with self.subTest(base_url=server.base_url): + fresh = probe_endpoint(server.base_url, timeout=1.5) + self.assertEqual( + sorted(m.id for m in fresh.models), sorted(m.id for m in server.models) + ) + + def test_off_device_models_are_detected_when_present(self): + report = live_report() + remote = [m for s in report.live for m in s.remote_models] + for model in remote: + with self.subTest(model=model.id): + self.assertTrue(model.remote_host, "an off-device model needs a remote host") + print("\n[live] off-device: %s -> %s" % (model.id, model.remote_host)) + + def test_find_local_server_prefers_on_device_capable_servers(self): + found = find_local_server(timeout=1.5) + if found is None: + self.skipTest("no server with an on-device model is running") + self.assertTrue(found.has_local_models) + + +@unittest.skipUnless(LIVE, SKIP_REASON) +class TestOllamaCapabilitiesAgainstRealServer(unittest.TestCase): + """Certify the capability reporting against a real Ollama ``/api/show``.""" + + def setUp(self): + server = on_device_server() + if server is None or server.provider != "ollama": + self.skipTest("no Ollama server with an on-device model is running") + self.server = server + self.model = on_device_model(server) + + def test_show_reports_a_context_length_the_adapter_now_uses(self): + backend = LLM( + self.model.id, + backend="ollama", + use_cache=False, + backend_kwargs={"host": self.server.base_url.rsplit("/v1", 1)[0]}, + ).backend + raw = backend.show() + reported = backend.detect_capabilities() + self.assertTrue(reported["detected"], reported) + server_context = None + for key, value in (raw.get("model_info") or {}).items(): + if key.endswith(".context_length") and isinstance(value, int) and value > 0: + server_context = value + self.assertIsNotNone(server_context, "server did not publish a context length") + self.assertEqual(backend.get_context_window(), server_context) + print( + "\n[live] %s: adapter now reports ctx=%d (was hardcoded 4096); capabilities=%s" + % (self.model.id, backend.get_context_window(), reported["capabilities"]) + ) + + def test_local_model_is_never_flagged_as_remote(self): + self.assertFalse(self.model.remote) + self.assertIsNone(self.model.remote_host) + + def test_cloud_models_are_flagged_when_the_server_lists_any(self): + remote = self.server.remote_models + if not remote: + self.skipTest("this server lists no provider-routed models") + self.assertTrue(all(m.remote_host for m in remote)) + + +@unittest.skipUnless(LIVE, SKIP_REASON) +class TestRealInferenceOnDevice(unittest.TestCase): + """Prove the end-to-end path works against a genuinely local model.""" + + def setUp(self): + server = on_device_server() + if server is None: + self.skipTest("no server with an on-device model is running") + if server.provider != "ollama": + self.skipTest("inference check currently targets the Ollama backend") + model = on_device_model(server) + if model is None: + self.skipTest("no on-device model available") + self.server = server + self.model = model + self.llm = LLM( + model.id, + backend="ollama", + use_cache=False, + backend_kwargs={"host": server.base_url.rsplit("/v1", 1)[0]}, + ) + + def test_chat_round_trip(self): + response = self.llm.chat( + [{"role": "user", "content": "Reply with the single word: OK"}], max_tokens=16 + ) + content = response["choices"][0]["message"]["content"] + self.assertTrue(content.strip(), "model returned empty content") + self.assertEqual(response["choices"][0]["finish_reason"], "stop") + self.assertGreater(response["usage"]["completion_tokens"], 0) + print("\n[live] %s chat -> %r" % (self.model.id, content.strip()[:60])) + + def test_streaming_round_trip(self): + pieces = [] + for chunk in self.llm.chat( + [{"role": "user", "content": "Count to three."}], max_tokens=24, stream=True + ): + pieces.append(chunk["choices"][0]["delta"].get("content") or "") + self.assertTrue("".join(pieces).strip()) + print("\n[live] %s streamed %d chunks" % (self.model.id, len(pieces))) + + def test_context_window_is_the_server_value(self): + raw = self.llm.backend.show() + expected = None + for key, value in (raw.get("model_info") or {}).items(): + if key.endswith(".context_length") and isinstance(value, int) and value > 0: + expected = value + self.assertIsNotNone(expected) + self.assertEqual(self.llm.detect_backend_capabilities()["context_window"], expected) + + def test_require_local_accepts_this_model(self): + self.assertTrue(self.llm.assert_local()) + + +@unittest.skipUnless(LIVE, SKIP_REASON) +class TestRequireLocalAgainstRealServer(unittest.TestCase): + def test_a_remote_model_is_refused_on_a_real_server(self): + report = live_report() + remote = [(s, m) for s in report.live for m in s.remote_models] + if not remote: + self.skipTest("no provider-routed model is available to refuse") + server, model = remote[0] + with self.assertRaises(RuntimeError) as ctx: + LLM( + model.id, + backend="ollama", + use_cache=False, + require_local=True, + backend_kwargs={"host": server.base_url.rsplit("/v1", 1)[0]}, + ) + self.assertIn("not on this machine", str(ctx.exception)) + print("\n[live] refused %r as required: %s" % (model.id, str(ctx.exception)[:80])) + + +class TestNormalizeAgainstRealUrls(unittest.TestCase): + """Runs always: pure string handling, no server needed.""" + + def test_loopback_forms_normalise_consistently(self): + for raw in ("localhost:11434", "http://localhost:11434", "http://localhost:11434/v1"): + self.assertEqual(normalize_base_url(raw), "http://localhost:11434/v1") + + def test_live_report_serialises(self): + if not LIVE: + self.skipTest(SKIP_REASON) + json.dumps(live_report().to_dict()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_mcp.py b/tests/test_mcp.py new file mode 100644 index 0000000..ade1fff --- /dev/null +++ b/tests/test_mcp.py @@ -0,0 +1,439 @@ +"""Offline tests for the Model Context Protocol (MCP) client. + +Covers schema conversion, the stdio transport (subprocess JSON-RPC), +the Streamable HTTP transport (JSON + SSE), error/timeout/cleanup paths, +and end-to-end registration + tool execution through ``LLM``. + +Everything here is offline: the stdio server is a local Python script and +the HTTP server is an in-process ``http.server``. No network, no models, +no optional dependencies. Python 3.9 compatible. + +Run: python -m pytest tests/test_mcp.py -q +""" + +import json +import os +import subprocess +import sys +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from local_llm_kit import LLM +from local_llm_kit.backends.base import BaseBackend +from local_llm_kit.mcp import ( + MCPError, + MCPProtocolError, + MCPServer, + MCPTool, + MCPToolError, + mcp_tools_to_openai, + sanitize_tool_name, +) + +FAKE_SERVER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "_fake_mcp_server.py") + + +def _repo_root(): + return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def stdio_server(*extra, name="fake", timeout=10.0): + return MCPServer( + name, command=sys.executable, args=[FAKE_SERVER] + list(extra), timeout=timeout + ) + + +# --------------------------------------------------------------------------- +# Fake HTTP MCP server +# --------------------------------------------------------------------------- +def _http_rpc(msg): + """Mirror of the stdio fake server, returning a response dict or None.""" + method = msg.get("method") + mid = msg.get("id") + params = msg.get("params") or {} + if mid is None: + return None + if method == "initialize": + return { + "jsonrpc": "2.0", + "id": mid, + "result": { + "protocolVersion": "2025-06-18", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "fake-http", "version": "1.0"}, + }, + } + if method == "tools/list": + return { + "jsonrpc": "2.0", + "id": mid, + "result": { + "tools": [ + { + "name": "echo", + "description": "Echo text.", + "inputSchema": { + "type": "object", + "properties": {"text": {"type": "string"}}, + "required": ["text"], + }, + } + ] + }, + } + if method == "tools/call": + name = params.get("name") + args = params.get("arguments") or {} + if name == "echo": + return { + "jsonrpc": "2.0", + "id": mid, + "result": {"content": [{"type": "text", "text": str(args.get("text", ""))}]}, + } + return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32602, "message": "unknown tool"}} + return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no method"}} + + +class _Handler(BaseHTTPRequestHandler): + def log_message(self, *args): # silence test output + pass + + def _read(self): + length = int(self.headers.get("Content-Length", 0)) + return json.loads(self.rfile.read(length) or b"{}") + + def do_POST(self): # noqa: N802 (http.server API) + msg = self._read() + self.server.seen.append((dict(self.headers), msg)) + resp = _http_rpc(msg) + if resp is None: + self.send_response(202) + self.end_headers() + return + if self.server.mode == "sse": + payload = ("event: message\ndata: " + json.dumps(resp) + "\n\n").encode() + ctype = "text/event-stream" + else: + payload = json.dumps(resp).encode() + ctype = "application/json" + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(payload))) + if self.server.session_id: + self.send_header("Mcp-Session-Id", self.server.session_id) + self.end_headers() + self.wfile.write(payload) + + def do_DELETE(self): # noqa: N802 + self.send_response(200) + self.end_headers() + + +class HttpServerFixture: + def __init__(self, mode="json", session_id=None): + self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + self.httpd.mode = mode + self.httpd.seen = [] + self.httpd.session_id = session_id + self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True) + self.thread.start() + + @property + def url(self): + host, port = self.httpd.server_address + return "http://%s:%d/mcp" % (host, port) + + def close(self): + self.httpd.shutdown() + self.httpd.server_close() + + +# --------------------------------------------------------------------------- +# Fake backend that emits a tool call on its first turn +# --------------------------------------------------------------------------- +class _ToolBackend(BaseBackend): + backend_name = "fake-tools" + + def __init__(self, tool_name, arguments=None): + self.tool_name = tool_name + self.arguments = arguments or {} + self.turns = 0 + + def generate(self, prompt, **kwargs): + self.turns += 1 + if self.turns == 1: + return { + "text": "", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": self.tool_name, + "arguments": json.dumps(self.arguments), + }, + } + ], + } + return {"text": "final answer", "finish_reason": "stop"} + + def generate_stream(self, prompt, **kwargs): + yield {"text": "final answer"} + + def get_context_window(self): + return 4096 + + def count_tokens(self, text): + return max(1, len(str(text)) // 4) + + +class TestNameConversion(unittest.TestCase): + def test_sanitize_tool_name(self): + self.assertEqual(sanitize_tool_name("weird/name"), "weird_name") + self.assertEqual(sanitize_tool_name("ok-name_1"), "ok-name_1") + self.assertEqual(sanitize_tool_name(""), "tool") + self.assertEqual(sanitize_tool_name("a b.c"), "a_b_c") + + def test_from_wire_requires_name(self): + with self.assertRaises(MCPProtocolError): + MCPTool.from_wire({"description": "no name"}) + with self.assertRaises(MCPProtocolError): + MCPTool.from_wire("not a dict") + + def test_to_openai_defaults_missing_schema(self): + tool = MCPTool.from_wire({"name": "noop", "description": "d"}) + spec = tool.to_openai() + self.assertEqual(spec["type"], "function") + self.assertEqual(spec["function"]["name"], "noop") + self.assertEqual(spec["function"]["parameters"], {"type": "object", "properties": {}}) + + def test_prefix_namespacing(self): + tools = [MCPTool(name="add"), MCPTool(name="weird/name")] + specs = mcp_tools_to_openai(tools, prefix="srv") + self.assertEqual([s["function"]["name"] for s in specs], ["srv__add", "srv__weird_name"]) + + +class TestStdioTransport(unittest.TestCase): + def test_open_list_and_call(self): + with stdio_server() as srv: + tools = srv.list_tools() + self.assertEqual(sorted(t.name for t in tools), ["add", "boom", "weird/name"]) + self.assertEqual(srv.server_info.get("name"), "fake-stdio") + self.assertEqual(srv.call_tool("add", {"a": 2, "b": 3}), "5") + + def test_to_openai_tools_shape(self): + with stdio_server() as srv: + specs = srv.to_openai_tools() + by_name = {s["function"]["name"]: s for s in specs} + self.assertIn("add", by_name) + self.assertIn("weird_name", by_name) # sanitized + self.assertEqual(by_name["add"]["function"]["parameters"]["required"], ["a", "b"]) + + def test_tool_error_is_raised(self): + with stdio_server() as srv: + with self.assertRaises(MCPToolError): + srv.call_tool("boom", {}) + + def test_jsonrpc_error_is_raised(self): + with stdio_server() as srv: + with self.assertRaises(MCPProtocolError) as ctx: + srv.call_tool("does-not-exist", {}) + self.assertEqual(ctx.exception.code, -32602) + + def test_pagination_collects_all_pages(self): + with stdio_server("--paginate") as srv: + tools = srv.list_tools() + self.assertEqual(sorted(t.name for t in tools), ["add", "boom", "weird/name"]) + + def test_refresh_tools_refetches(self): + with stdio_server() as srv: + first = srv.list_tools() + second = srv.refresh_tools() + self.assertEqual(len(first), len(second)) + + def test_close_terminates_and_blocks_further_use(self): + srv = stdio_server() + srv.open() + self.assertFalse(srv.closed) + srv.close() + self.assertTrue(srv.closed) + with self.assertRaises(MCPProtocolError): + srv.request("tools/list", {}) + + def test_missing_command_raises_clean_error(self): + srv = MCPServer("bad", command="/nonexistent/mcp-binary-xyz", timeout=2.0) + with self.assertRaises(MCPError): + srv.open() + + def test_timeout_is_reported(self): + srv = stdio_server("--sleep", timeout=0.5) + try: + srv.open() + with self.assertRaises(MCPProtocolError) as ctx: + srv.list_tools() + self.assertIn("Timed out", str(ctx.exception)) + finally: + srv.close() + + +class TestHttpTransport(unittest.TestCase): + def test_json_body_transport(self): + fx = HttpServerFixture(mode="json") + try: + with MCPServer("http-json", url=fx.url, timeout=5.0) as srv: + self.assertEqual([t.name for t in srv.tools()], ["echo"]) + self.assertEqual(srv.call_tool("echo", {"text": "hi"}), "hi") + finally: + fx.close() + + def test_sse_transport_and_session_header(self): + fx = HttpServerFixture(mode="sse", session_id="sess-123") + try: + with MCPServer("http-sse", url=fx.url, timeout=5.0) as srv: + self.assertEqual([t.name for t in srv.tools()], ["echo"]) + self.assertEqual(srv.call_tool("echo", {"text": "yo"}), "yo") + # The initialize response carried a session id; later requests echoed it. + init_headers = fx.httpd.seen[0][0] + self.assertEqual(init_headers.get("Mcp-Session-Id"), None) + later_headers = fx.httpd.seen[-1][0] + self.assertEqual(later_headers.get("Mcp-Session-Id"), "sess-123") + finally: + fx.close() + + def test_http_error_is_wrapped(self): + srv = MCPServer("dead", url="http://127.0.0.1:1/mcp", timeout=2.0) + with self.assertRaises(MCPError): + srv.open() + + +class TestConfigValidation(unittest.TestCase): + def test_requires_exactly_one_transport(self): + with self.assertRaises(ValueError): + MCPServer("x") + with self.assertRaises(ValueError): + MCPServer("x", command="python", url="http://localhost:1/mcp") + with self.assertRaises(ValueError): + MCPServer("", command="python") + with self.assertRaises(ValueError): + MCPServer("x", url="ftp://nope") + + +class TestLLMIntegration(unittest.TestCase): + def test_tool_loop_executes_mcp_tool(self): + srv = stdio_server() + backend = _ToolBackend("fake__add", {"a": 2, "b": 3}) + llm = LLM("test-model", backend_instance=backend, use_cache=False) + try: + names = llm.add_mcp_server(srv) + self.assertIn("fake__add", names) + response = llm.chat([{"role": "user", "content": "add 2 and 3"}]) + self.assertEqual(response["choices"][0]["message"]["content"], "final answer") + # The server is tracked, and its tool output was fed back to the model. + self.assertIn("fake", llm.mcp_servers) + tool_texts = [m.get("content") for m in llm.memory.messages if m.get("role") == "tool"] + self.assertIn("5", tool_texts) + finally: + llm.close() + self.assertTrue(srv.closed) + + def test_include_excludes_tools(self): + srv = stdio_server() + llm = LLM( + "test-model", + backend_instance=_ToolBackend("fake__add", {"a": 1, "b": 1}), + use_cache=False, + ) + try: + names = llm.add_mcp_server(srv, include=["add"]) + self.assertEqual(names, ["fake__add"]) + finally: + llm.close() + + def test_no_prefix_keeps_raw_names(self): + srv = stdio_server() + llm = LLM("test-model", backend_instance=_ToolBackend("x"), use_cache=False) + try: + names = llm.add_mcp_server(srv, prefix=False) + self.assertIn("add", names) + self.assertIn("weird_name", names) + finally: + llm.close() + + def test_repr_smoke(self): + srv = stdio_server() + try: + srv.open() + self.assertIn("fake", repr(srv)) + finally: + srv.close() + + +class TestCli(unittest.TestCase): + def _run(self, argv): + import contextlib + import io + + from local_llm_kit import cli + + out = io.StringIO() + with contextlib.redirect_stdout(out): + code = cli.main(argv) + return code, out.getvalue() + + def test_mcp_tools_json(self): + cmd = "%s %s" % (sys.executable, FAKE_SERVER) + code, out = self._run(["mcp", "tools", "--command", cmd, "--json"]) + self.assertEqual(code, 0, msg=out) + specs = json.loads(out) + names = sorted(s["function"]["name"] for s in specs) + self.assertEqual(names, ["add", "boom", "weird_name"]) + + def test_mcp_tools_table(self): + cmd = "%s %s" % (sys.executable, FAKE_SERVER) + code, out = self._run(["mcp", "tools", "--command", cmd]) + self.assertEqual(code, 0, msg=out) + self.assertIn("add", out) + self.assertIn("required", out) + + def test_mcp_call(self): + cmd = "%s %s" % (sys.executable, FAKE_SERVER) + code, out = self._run( + ["mcp", "call", "--command", cmd, "--tool", "add", "--args", '{"a": 4, "b": 5}'] + ) + self.assertEqual(code, 0, msg=out) + self.assertEqual(out.strip(), "9") + + def test_mcp_tools_over_http_url(self): + fx = HttpServerFixture(mode="json") + try: + code, out = self._run(["mcp", "tools", "--url", fx.url, "--json"]) + self.assertEqual(code, 0, msg=out) + specs = json.loads(out) + self.assertEqual([s["function"]["name"] for s in specs], ["echo"]) + finally: + fx.close() + + def test_mcp_call_error_exit_code(self): + cmd = "%s %s" % (sys.executable, FAKE_SERVER) + with self.assertRaises(SystemExit) as ctx: + self._run(["mcp", "call", "--command", cmd, "--tool", "boom"]) + self.assertEqual(ctx.exception.code, 1) + + +class TestCoreStaysLight(unittest.TestCase): + def test_import_mcp_pulls_no_heavy_deps(self): + code = ( + "import sys; import local_llm_kit.mcp; " + "bad = [m for m in ('torch', 'transformers', 'llama_cpp') if m in sys.modules]; " + "print(','.join(bad))" + ) + out = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, cwd=_repo_root() + ) + self.assertEqual(out.returncode, 0, msg=out.stderr[-2000:]) + self.assertEqual(out.stdout.strip(), "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_mcp_interop.py b/tests/test_mcp_interop.py new file mode 100644 index 0000000..cbd9460 --- /dev/null +++ b/tests/test_mcp_interop.py @@ -0,0 +1,113 @@ +"""Opt-in interop test: our stdlib MCP client vs. the official ``mcp`` SDK. + +This is the *real runtime* counterpart to the mocked contract tests in +``tests/test_mcp.py``. It starts a server built with the official Python SDK +(``mcp`` >= 2.0, which requires Python >= 3.10) as a subprocess and drives it +through :class:`local_llm_kit.mcp.MCPServer`. + +It is skipped in the default suite and enabled in the Python 3.12 Linux CI job. +Enable it locally:: + + pip install "mcp" # Python >= 3.10 + LOCAL_LLM_KIT_MCP_INTEROP=1 pytest tests/test_mcp_interop.py -v + +A skip means "not run here", not "passed". +""" + +import os +import socket +import subprocess +import sys +import time +import unittest +import urllib.error +import urllib.request + +from local_llm_kit.mcp import MCPServer + +RUN = os.environ.get("LOCAL_LLM_KIT_MCP_INTEROP") == "1" + +HAVE_MCP = False +if RUN and sys.version_info >= (3, 10): + try: + import mcp # noqa: F401 + + HAVE_MCP = True + except Exception: # pragma: no cover - depends on the environment + HAVE_MCP = False + +SERVER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "_interop_mcp_server.py") + +_SKIP_REASON = ( + "opt-in interop test: set LOCAL_LLM_KIT_MCP_INTEROP=1 with the official " + "'mcp' SDK installed on Python >= 3.10" +) + + +@unittest.skipUnless(RUN and HAVE_MCP, _SKIP_REASON) +class TestOfficialSdkInterop(unittest.TestCase): + def test_list_and_call_tools_from_official_sdk_server(self): + with MCPServer("interop", command=sys.executable, args=[SERVER], timeout=30.0) as srv: + names = sorted(t.name for t in srv.tools()) + self.assertIn("add", names) + self.assertIn("greet", names) + + specs = {s["function"]["name"]: s for s in srv.to_openai_tools()} + self.assertEqual(specs["add"]["function"]["parameters"]["type"], "object") + self.assertIn("a", specs["add"]["function"]["parameters"]["properties"]) + + self.assertIn("42", srv.call_tool("add", {"a": 2, "b": 40})) + self.assertIn("Ada", srv.call_tool("greet", {"name": "Ada"})) + + def test_stateless_2026_protocol_with_official_sdk(self): + with MCPServer( + "modern", + command=sys.executable, + args=[SERVER], + timeout=10, + protocol_version="2026-07-28", + ) as server: + self.assertIn("2026-07-28", server.initialize()["supportedVersions"]) + self.assertIn("add", [tool.name for tool in server.list_tools()]) + self.assertIn("42", server.call_tool("add", {"a": 2, "b": 40})) + + def test_stateless_http_json_and_sse_with_official_sdk(self): + for json_mode in (False, True): + with self.subTest(json_mode=json_mode): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + args = [sys.executable, SERVER, str(port)] + (["json"] if json_mode else []) + process = subprocess.Popen( + args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + url = "http://127.0.0.1:%s/mcp" % port + try: + deadline = time.monotonic() + 10 + while True: + try: + with urllib.request.urlopen(url, timeout=0.1): + break + except urllib.error.HTTPError as error: + error.close() + break # HTTP 405 is enough to establish readiness. + except OSError: + if process.poll() is not None or time.monotonic() >= deadline: + self.fail("Official MCP HTTP fixture did not start.") + time.sleep(0.02) + with MCPServer( + "http-interop", url=url, timeout=3, protocol_version="2026-07-28" + ) as server: + self.assertIn("add", [tool.name for tool in server.list_tools()]) + self.assertIn("42", server.call_tool("add", {"a": 2, "b": 40})) + finally: + process.terminate() + try: + process.wait(timeout=3) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_memory.py b/tests/test_memory.py new file mode 100644 index 0000000..c1c104b --- /dev/null +++ b/tests/test_memory.py @@ -0,0 +1,82 @@ +"""History truncation keeps tool exchanges atomic. + +Regression tests for split tool-call/result pairs: truncation and +summarization must never strand an assistant ``tool_calls`` message without +its ``tool`` results (or vice versa). +""" + +import unittest + +from local_llm_kit.memory import MessageHistory + + +def _exchange(n): + return [ + {"role": "user", "content": "question %d" % n}, + { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": "call-%d" % n, + "type": "function", + "function": {"name": "get_weather", "arguments": '{"n": %d}' % n}, + } + ], + }, + {"role": "tool", "tool_call_id": "call-%d" % n, "content": "sunny %d" % n}, + ] + + +class TestToolExchangeTruncation(unittest.TestCase): + def test_truncation_removes_whole_exchanges(self): + history = MessageHistory(context_window=10**9) + history.add_messages([{"role": "system", "content": "sys"}]) + for n in range(4): + history.add_messages(_exchange(n)) + history.context_window = 1 # force truncation of everything non-system + history._truncate_if_needed() + roles = [m.get("role") for m in history.messages] + self.assertEqual(roles[0], "system") + # Every remaining assistant tool_calls message keeps its tool result. + for i, message in enumerate(history.messages): + if message.get("tool_calls"): + following = [m.get("role") for m in history.messages[i + 1 : i + 3]] + self.assertIn("tool", following) + # No orphaned tool results without their assistant call. + for i, message in enumerate(history.messages): + if message.get("role") == "tool": + owners = [ + m + for m in history.messages[:i] + if m.get("role") == "assistant" and m.get("tool_calls") + ] + self.assertTrue(owners) + + def test_summarizer_does_not_start_inside_exchange(self): + history = MessageHistory(context_window=10**9) + history.add_messages(_exchange(0) + _exchange(1)) + history._summarize_history() + first_kept = history.messages[-1] if history.messages else None + # The kept tail must not begin with a bare tool result. + kept_roles = [ + m.get("role") + for m in history.messages + if m.get("role") != "system" or "summarized" not in str(m.get("content", "")) + ] + self.assertNotEqual(kept_roles[0], "tool") + self.assertIsNotNone(first_kept) + + def test_plain_history_truncation_unchanged(self): + history = MessageHistory(context_window=10**9) + history.add_messages([{"role": "user", "content": "hello world, this is a test"}]) + history.context_window = 1 + history._truncate_if_needed() + # Single over-limit message takes the pre-existing summarize path. + self.assertEqual(len(history.messages), 2) + self.assertIn("summarized", history.messages[0]["content"]) + self.assertEqual(history.messages[1]["role"], "user") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_prompt_templates.py b/tests/test_prompt_templates.py new file mode 100644 index 0000000..2dbacea --- /dev/null +++ b/tests/test_prompt_templates.py @@ -0,0 +1,167 @@ +"""Offline tests for the prompt-template module. + +Stdlib unittest only. Python 3.9 compatible. + +Run: python -m pytest tests/test_prompt_templates.py -q +""" + +import json +import os +import tempfile +import unittest + +from local_llm_kit.prompt_templates import ( + DEFAULT_REGISTRY, + PromptTemplate, + TemplateRegistry, + get_template, + register_template, + render_template, +) + + +class TestPromptTemplate(unittest.TestCase): + def test_required_variable(self): + t = PromptTemplate("Hello, {{name}}!") + self.assertEqual(t.render(name="World"), "Hello, World!") + + def test_required_variable_missing_raises(self): + t = PromptTemplate("Hello, {{name}}!") + with self.assertRaises(KeyError): + t.render() + + def test_default_value(self): + t = PromptTemplate("Hello, {{name|stranger}}!") + self.assertEqual(t.render(name="Alice"), "Hello, Alice!") + self.assertEqual(t.render(), "Hello, stranger!") + + def test_single_braces_preserved(self): + t = PromptTemplate('{"key": "{{value}}"}') + self.assertEqual(t.render(value="x"), '{"key": "x"}') + + def test_no_placeholders(self): + t = PromptTemplate("static text") + self.assertEqual(t.render(), "static text") + + def test_multiple_placeholders(self): + t = PromptTemplate("{{greeting}}, {{name}}!") + self.assertEqual(t.render(greeting="Hi", name="Bob"), "Hi, Bob!") + + def test_render_non_string_values(self): + t = PromptTemplate("{{count}} items at {{price}}") + self.assertEqual(t.render(count=42, price=3.14), "42 items at 3.14") + + def test_from_string(self): + t = PromptTemplate.from_string("Hi {{name}}") + self.assertEqual(t.render(name="X"), "Hi X") + + def test_from_file_json(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "tmpl.json") + with open(path, "w") as fh: + json.dump( + {"template": "Hello {{name}}", "name": "greeting", "description": "d"}, fh + ) + t = PromptTemplate.from_file(path) + self.assertEqual(t.name, "greeting") + self.assertEqual(t.description, "d") + self.assertEqual(t.render(name="World"), "Hello World") + + def test_from_file_bare_string(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "tmpl.txt") + with open(path, "w") as fh: + fh.write("Bare {{x}}") + t = PromptTemplate.from_file(path, name="bare") + self.assertEqual(t.name, "bare") + self.assertEqual(t.render(x="val"), "Bare val") + + def test_repr(self): + t = PromptTemplate("hi {{name}}", name="greet") + self.assertIn("greet", repr(t)) + + +class TestTemplateRegistry(unittest.TestCase): + def test_register_and_get(self): + reg = TemplateRegistry() + t = reg.register("greet", "Hello {{name}}") + self.assertIs(reg.get("greet"), t) + with self.assertRaises(KeyError): + reg.get("nope") + + def test_register_by_object_requires_name(self): + reg = TemplateRegistry() + with self.assertRaises(ValueError): + reg.register(PromptTemplate("hi")) + + def test_register_by_object_with_name(self): + reg = TemplateRegistry() + t = reg.register(PromptTemplate("hi {{n}}", name="g")) + self.assertIsNotNone(t.name) + + def test_register_by_name_requires_template_str(self): + reg = TemplateRegistry() + with self.assertRaises(ValueError): + reg.register("x", None) + + def test_render(self): + reg = TemplateRegistry() + reg.register("greet", "Hello {{who}}") + self.assertEqual(reg.render("greet", who="World"), "Hello World") + + def test_contains_and_len(self): + reg = TemplateRegistry() + reg.register("a", "A {{x}}") + reg.register("b", "B {{x}}") + self.assertIn("a", reg) + self.assertNotIn("c", reg) + self.assertEqual(len(reg), 2) + + def test_list_templates_is_copy(self): + reg = TemplateRegistry() + reg.register("a", "A {{x}}") + templates = reg.list_templates() + templates.clear() + self.assertEqual(len(reg), 1) + + def test_load_directory(self): + with tempfile.TemporaryDirectory() as tmp: + with open(os.path.join(tmp, "a.json"), "w") as fh: + json.dump({"template": "A{{x}}", "name": "a"}, fh) + with open(os.path.join(tmp, "b.json"), "w") as fh: + json.dump({"template": "B{{y}}", "name": "b"}, fh) + with open(os.path.join(tmp, "c.txt"), "w") as fh: + fh.write("should be ignored") + reg = TemplateRegistry() + count = reg.load_directory(tmp) + self.assertEqual(count, 2) + self.assertIn("a", reg) + self.assertIn("b", reg) + + def test_register_from_file(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "tmpl.json") + with open(path, "w") as fh: + json.dump({"template": "Hello {{who}}", "name": "greet"}, fh) + reg = TemplateRegistry() + reg.register_from_file(path) + self.assertEqual(reg.render("greet", who="World"), "Hello World") + + +class TestModuleLevelHelpers(unittest.TestCase): + def test_default_registry_exists(self): + self.assertIsInstance(DEFAULT_REGISTRY, TemplateRegistry) + + def test_register_get_render(self): + name = "test_helper_" + str(id(self)) + register_template(name, "Hi {{who}}") + self.assertEqual(get_template(name).render(who="U"), "Hi U") + self.assertEqual(render_template(name, who="U"), "Hi U") + + def test_get_template_missing_raises(self): + with self.assertRaises(KeyError): + get_template("definitely_not_registered") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_rag.py b/tests/test_rag.py index 6b0f989..55c1b95 100644 --- a/tests/test_rag.py +++ b/tests/test_rag.py @@ -354,5 +354,120 @@ def test_rag_import_pulls_no_torch(self): self.assertEqual(out.stdout.strip(), "") +@unittest.skipUnless(HAS_RAG, "local_llm_kit.rag not available") +class TestMMR(unittest.TestCase): + def _dense_store(self): + from local_llm_kit.rag import SimpleVectorStore + + def fake_embed(texts): + vecs = [] + for text in texts: + if "sky" in text: + vecs.append([0.0, 0.0, 1.0]) + elif "company" in text: + vecs.append([0.9, 0.1, 0.0]) + else: + vecs.append([1.0, 0.0, 0.0]) + return vecs + + store = SimpleVectorStore(embed_fn=fake_embed) + store.add( + ["red apple fruit", "red apple company", "green apple fruit", "blue sky ocean"], + embeddings=[ + [1.0, 0.0, 0.0], + [0.9, 0.1, 0.0], + [0.9, 0.0, 0.1], + [0.0, 0.0, 1.0], + ], + ) + return store + + def test_mmr_function_selects_diverse_order(self): + from local_llm_kit.rag import mmr + + picked = mmr( + [1.0, 0.0, 0.0], + [[1.0, 0.0, 0.0], [0.9, 0.1, 0.0], [0.0, 0.0, 1.0]], + k=2, + lambda_mult=0.0, + ) + self.assertEqual(picked[0], 0) + self.assertEqual(picked[1], 2) + pure = mmr( + [1.0, 0.0, 0.0], + [[1.0, 0.0, 0.0], [0.9, 0.1, 0.0], [0.0, 0.0, 1.0]], + k=2, + lambda_mult=1.0, + ) + self.assertEqual(pure, [0, 1]) + + def test_mmr_validates_inputs(self): + from local_llm_kit.rag import mmr + + with self.assertRaises(ValueError): + mmr([1.0], [[1.0]], k=0) + with self.assertRaises(ValueError): + mmr([1.0], [[1.0]], k=2, lambda_mult=1.5) + self.assertEqual(mmr([1.0], [], k=3), []) + + def test_search_lambda_none_matches_pure_relevance(self): + store = self._dense_store() + plain = store.search([1.0, 0.0, 0.0], k=3) + diversified = store.search([1.0, 0.0, 0.0], k=3, lambda_mult=1.0) + self.assertEqual([h["id"] for h in plain], [h["id"] for h in diversified]) + + def test_search_lambda_zero_diversifies(self): + store = self._dense_store() + hits = store.search([1.0, 0.0, 0.0], k=3, lambda_mult=0.0) + texts = [h["text"] for h in hits] + self.assertEqual(texts[0], "red apple fruit") + self.assertIn("blue sky ocean", texts[1:]) + self.assertTrue(all(h["score"] >= 0 for h in hits)) + + def test_search_lambda_rejects_lexical_and_bad_values(self): + store = make_store() + store_add(store, ["the cat sat", "quantum physics"]) + with self.assertRaisesRegex(ValueError, "dense vectors"): + store.search("cat", k=2, lambda_mult=0.5) + dense = self._dense_store() + with self.assertRaisesRegex(ValueError, "lambda_mult"): + dense.search([1.0, 0.0, 0.0], k=2, lambda_mult=2.0) + + def test_hybrid_alpha_endpoints(self): + store = self._dense_store() + dense_only = store.search_hybrid("apple fruit", k=3, alpha=1.0) + pure_dense = store.search("apple fruit", k=3, lambda_mult=None) + self.assertEqual([h["id"] for h in dense_only], [h["id"] for h in pure_dense]) + lex_only = store.search_hybrid("apple fruit", k=3, alpha=0.0) + self.assertEqual(len(lex_only), 3) + self.assertTrue(all(h["score"] >= 0 for h in lex_only)) + + def test_hybrid_blends_dense_and_lexical(self): + store = self._dense_store() + hits = store.search_hybrid("blue sky", k=4, alpha=0.5) + self.assertEqual(hits[0]["text"], "blue sky ocean") + with_mmr = store.search_hybrid("apple", k=3, alpha=0.5, lambda_mult=0.0) + self.assertEqual(len(with_mmr), 3) + + def test_hybrid_validates_inputs(self): + store = self._dense_store() + with self.assertRaisesRegex(ValueError, "text query"): + store.search_hybrid([1.0, 0.0, 0.0], k=2) + with self.assertRaisesRegex(ValueError, "alpha"): + store.search_hybrid("apple", k=2, alpha=1.5) + lexical_only = make_store() + store_add(lexical_only, ["the cat sat", "quantum physics"]) + with self.assertRaisesRegex(ValueError, "dense vectors"): + lexical_only.search_hybrid("apple", k=2) + + def test_retrieve_passes_lambda_through(self): + from local_llm_kit.rag import retrieve + + store = self._dense_store() + hits = retrieve([1.0, 0.0, 0.0], store, k=2, lambda_mult=0.0) + self.assertEqual(len(hits), 2) + self.assertEqual(hits[0]["text"], "red apple fruit") + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_responses_sdk.py b/tests/test_responses_sdk.py new file mode 100644 index 0000000..a416ffc --- /dev/null +++ b/tests/test_responses_sdk.py @@ -0,0 +1,217 @@ +"""Optional conformance against the installed official OpenAI Python SDK. + +Run LOCAL_LLM_KIT_OPENAI_INTEROP=1 pytest tests/test_responses_sdk.py. +All requests stay within FastAPI TestClient; no credentials or remote inference. +""" + +import json +import os + +import pytest + +pytestmark = pytest.mark.skipif( + os.environ.get("LOCAL_LLM_KIT_OPENAI_INTEROP") != "1", + reason="opt-in OpenAI SDK interoperability test", +) + + +class FixtureLLM: + model_path = "fixture" + + def __init__(self): + self.calls = [] + + def chat(self, messages, **kwargs): + self.calls.append((messages, kwargs)) + tools = kwargs.get("tools") + tool_reply = messages[-1]["role"] == "tool" + text = '{"age":3}' if kwargs.get("response_format") else "works" + message = {"role": "assistant", "content": text} + if tools and not tool_reply: + message = { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": "call_original", + "type": "function", + "function": {"name": "read", "arguments": '{"path":"local.txt"}'}, + } + ], + } + usage = {"prompt_tokens": 11, "completion_tokens": 5, "total_tokens": 16} + if kwargs.get("stream"): + if message.get("tool_calls"): + return iter( + [ + { + "choices": [ + { + "delta": { + "tool_calls": [ + { + "index": 0, + "id": "call_original", + "function": { + "name": "read", + "arguments": '{"path":', + }, + } + ] + } + } + ] + }, + { + "choices": [ + { + "delta": { + "tool_calls": [ + {"index": 0, "function": {"arguments": '"local.txt"}'}} + ] + }, + "finish_reason": "tool_calls", + } + ], + "usage": usage, + }, + ] + ) + return iter( + [ + {"choices": [{"delta": {"content": text[:2]}}]}, + { + "choices": [{"delta": {"content": text[2:]}, "finish_reason": "stop"}], + "usage": usage, + }, + ] + ) + return { + "choices": [ + { + "message": message, + "finish_reason": "tool_calls" if message.get("tool_calls") else "stop", + } + ], + "usage": usage, + } + + +@pytest.fixture +def client(): + openai = pytest.importorskip("openai") + testclient = pytest.importorskip("fastapi.testclient") + from local_llm_kit.server import create_app + + llm = FixtureLLM() + with testclient.TestClient(create_app(llm=llm)) as http_client: + with openai.OpenAI( + api_key="unused-local-test", base_url="http://testserver/v1", http_client=http_client + ) as sdk: + yield sdk, llm + + +TOOL = { + "type": "function", + "name": "read", + "description": "Read a local fixture", + "parameters": { + "type": "object", + "properties": {"path": {"type": "string"}}, + "required": ["path"], + }, +} + + +def test_sdk_responses_text_and_usage(client): + sdk, _ = client + response = sdk.responses.create(model="fixture", input="hello", store=False) + assert response.output_text == "works" + assert response.usage.input_tokens == 11 and response.usage.output_tokens == 5 + + +def test_sdk_function_call_and_result_round_trip(client): + sdk, llm = client + response = sdk.responses.create(model="fixture", input="read a file", tools=[TOOL]) + call = response.output[0] + assert call.type == "function_call" and call.call_id == "call_original" + assert json.loads(call.arguments) == {"path": "local.txt"} + assert llm.calls[-1][1]["tools"][0]["function"]["name"] == "read" + follow_up = sdk.responses.create( + model="fixture", + input=[ + {"role": "user", "content": "read a file"}, + call.model_dump(), + {"type": "function_call_output", "call_id": call.call_id, "output": "file content"}, + ], + tools=[TOOL], + ) + assert follow_up.output_text == "works" + assert llm.calls[-1][0][-1] == { + "role": "tool", + "tool_call_id": "call_original", + "content": "file content", + } + assert llm.calls[-1][1]["execute_tools"] is False + + +@pytest.mark.parametrize("tools", [[], [TOOL]]) +def test_sdk_stream_manager_can_build_final_text_and_tool_calls(client, tools): + sdk, _ = client + with sdk.responses.stream(model="fixture", input="hello", tools=tools) as stream: + events = list(stream) + response = stream.get_final_response() + assert response.status == "completed" + assert response.usage.total_tokens == 16 + assert [event.sequence_number for event in events] == list(range(len(events))) + if tools: + assert response.output[0].call_id == "call_original" + assert json.loads(response.output[0].arguments) == {"path": "local.txt"} + else: + assert response.output_text == "works" + + +def test_sdk_schema_format_and_image_parts_are_forwarded(client): + sdk, llm = client + schema = { + "type": "object", + "properties": {"age": {"type": "integer"}}, + "required": ["age"], + "additionalProperties": False, + } + response = sdk.responses.create( + model="fixture", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": "age?"}, + {"type": "input_image", "image_url": "data:image/png;base64,eA=="}, + ], + } + ], + text={"format": {"type": "json_schema", "name": "Age", "schema": schema}}, + ) + assert json.loads(response.output_text) == {"age": 3} + assert llm.calls[-1][0][0]["content"][1]["type"] == "image_url" + assert llm.calls[-1][1]["response_format"]["json_schema"]["schema"] == schema + + +def test_responses_invalid_fields_are_400_and_stream_failures_are_events(client): + sdk, llm = client + http = sdk._client + for payload in ( + {"tools": [{"type": "function", "function": "invalid"}]}, + {"stream": "false"}, + {"text": {"format": []}}, + {"reasoning": {}}, + ): + response = http.post("http://testserver/v1/responses", json=dict(input="hi", **payload)) + assert response.status_code == 400 + llm.chat = lambda **kwargs: (_ for _ in ()).throw(RuntimeError("fixture failure")) + response = http.post("http://testserver/v1/responses", json={"input": "hi", "stream": True}) + events = [ + json.loads(line[6:]) for line in response.text.splitlines() if line.startswith("data: ") + ] + assert events[-1]["type"] == "response.failed" + assert events[-1]["response"]["error"]["message"] == "fixture failure" diff --git a/tests/test_retry.py b/tests/test_retry.py new file mode 100644 index 0000000..f1da0c4 --- /dev/null +++ b/tests/test_retry.py @@ -0,0 +1,413 @@ +"""Offline tests for the retry policy and its wiring into the HTTP backends. + +The policy is exercised directly, and end-to-end against a local fixture that +counts requests and can be told to fail a given number of times first. No +network, no models. + +The behaviour under test: + * transient failures (refused connection, 429, 5xx) are retried, + * client errors (4xx other than 429) are not, + * ``max_retries=0`` restores single-attempt behaviour, + * a stream is retried only before the first frame is emitted, + * ``Retry-After`` is honoured and clamped. +""" + +import json +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from local_llm_kit.backends.ollama import OllamaBackend +from local_llm_kit.backends.openai_compat import OpenAICompatBackend +from local_llm_kit.retry import ( + DEFAULT_RETRY, + MAX_RETRY_AFTER, + RETRYABLE_STATUS, + RetryPolicy, + coerce_policy, + is_retryable_status, + retry_after_seconds, +) + + +class _FakeHeaders: + def __init__(self, value=None): + self._value = value + + def get(self, name, default=None): + if name == "Retry-After": + return self._value + return default + + +def dead_url(): + """A loopback port that was bound then released.""" + server = ThreadingHTTPServer(("127.0.0.1", 0), BaseHTTPRequestHandler) + port = server.server_port + server.server_close() + return "http://127.0.0.1:%d" % port + + +class Handler(BaseHTTPRequestHandler): + """Fixture that fails the first ``fail_times`` requests, then succeeds.""" + + fail_times = 0 + fail_status = 503 + retry_after = None + attempts = 0 + paths = [] + + def log_message(self, *args): + pass + + def _respond(self, payload, status=200, content_type="application/json"): + encoded = payload.encode() if isinstance(payload, str) else json.dumps(payload).encode() + self.send_response(status) + self.send_header("Content-Type", content_type) + if self.retry_after is not None: + self.send_header("Retry-After", str(self.retry_after)) + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + def do_POST(self): + Handler.attempts += 1 + Handler.paths.append(self.path) + length = int(self.headers.get("Content-Length") or 0) + body = json.loads(self.rfile.read(length)) if length else {} + if Handler.attempts <= Handler.fail_times: + return self._respond({"error": "still loading"}, status=Handler.fail_status) + + # Ollama's native routes use a different envelope than /v1. + if self.path == "/api/chat": + if body.get("stream"): + lines = [ + {"message": {"content": "hello"}, "done": False}, + {"message": {"content": ""}, "done": True, "done_reason": "stop"}, + ] + return self._respond( + "".join(json.dumps(line) + "\n" for line in lines), + content_type="application/x-ndjson", + ) + return self._respond( + {"message": {"content": "hello"}, "done": True, "done_reason": "stop"} + ) + + if body.get("stream"): + frames = [ + {"choices": [{"delta": {"content": "hello"}, "finish_reason": None}]}, + {"choices": [{"delta": {}, "finish_reason": "stop"}]}, + ] + return self._respond( + "".join("data: %s\n\n" % json.dumps(f) for f in frames) + "data: [DONE]\n\n", + content_type="text/event-stream", + ) + return self._respond( + {"choices": [{"message": {"content": "hello"}, "finish_reason": "stop"}]} + ) + + def do_GET(self): + Handler.attempts += 1 + Handler.paths.append(self.path) + if Handler.attempts <= Handler.fail_times: + return self._respond({"error": "still loading"}, status=Handler.fail_status) + return self._respond({"object": "list", "data": [{"id": "fixture"}]}) + + +class Fixture: + def __init__(self, fail_times=0, fail_status=503, retry_after=None): + Handler.fail_times = fail_times + Handler.fail_status = fail_status + Handler.retry_after = retry_after + Handler.attempts = 0 + Handler.paths = [] + + def __enter__(self): + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.url = "http://127.0.0.1:%d" % self.server.server_port + return self + + def __exit__(self, *exc): + self.server.shutdown() + self.server.server_close() + self.thread.join(timeout=5) + + +# No sleeping in the test suite: delays are zeroed so only the counts matter. +def fast(max_retries): + """A policy with the given retry count and no real delay.""" + return RetryPolicy(max_retries=max_retries, initial_delay=0.0, max_delay=0.0) + + +FAST = fast(2) + + +class TestRetryPolicyValues(unittest.TestCase): + def test_defaults_match_the_official_openai_client(self): + self.assertEqual(DEFAULT_RETRY.max_retries, 2) + self.assertEqual(DEFAULT_RETRY.initial_delay, 0.5) + self.assertEqual(DEFAULT_RETRY.max_delay, 8.0) + + def test_validation_rejects_nonsense(self): + for kwargs in ( + {"max_retries": -1}, + {"max_retries": True}, + {"max_retries": 1.5}, + {"initial_delay": -0.1}, + {"max_delay": -1}, + {"initial_delay": 5.0, "max_delay": 1.0}, + ): + with self.subTest(**kwargs): + with self.assertRaises((TypeError, ValueError)): + RetryPolicy(**kwargs) + + def test_zero_retries_disables_the_policy(self): + self.assertFalse(RetryPolicy(max_retries=0).enabled) + self.assertTrue(RetryPolicy(max_retries=1).enabled) + + def test_backoff_doubles_and_is_capped(self): + policy = RetryPolicy(max_retries=5, initial_delay=0.5, max_delay=2.0, jitter=False) + self.assertEqual(policy.delay_for(1), 0.5) + self.assertEqual(policy.delay_for(2), 1.0) + self.assertEqual(policy.delay_for(3), 2.0) + self.assertEqual(policy.delay_for(4), 2.0) + + def test_jitter_stays_within_half_to_full_backoff(self): + policy = RetryPolicy(max_retries=5, initial_delay=1.0, max_delay=8.0, jitter=True) + for attempt in (1, 2, 3): + delay = policy.delay_for(attempt) + nominal = min(1.0 * (2 ** (attempt - 1)), 8.0) + self.assertGreaterEqual(delay, nominal / 2) + self.assertLessEqual(delay, nominal) + + def test_retry_after_wins_over_computed_backoff(self): + policy = RetryPolicy(max_retries=5, initial_delay=1.0, jitter=False) + self.assertEqual(policy.delay_for(1, retry_after=3.0), 3.0) + self.assertEqual(policy.delay_for(5, retry_after=0.25), 0.25) + + def test_retry_after_is_clamped(self): + policy = RetryPolicy(max_retries=5, initial_delay=1.0, jitter=False) + self.assertEqual(policy.delay_for(1, retry_after=999.0), MAX_RETRY_AFTER) + self.assertLessEqual(policy.delay_for(1, retry_after=999.0), MAX_RETRY_AFTER) + + def test_negative_retry_after_falls_back_to_backoff(self): + policy = RetryPolicy(max_retries=5, initial_delay=2.0, jitter=False) + self.assertEqual(policy.delay_for(1, retry_after=-1.0), 2.0) + + def test_sleep_returns_the_delay_it_used(self): + self.assertEqual(RetryPolicy(max_retries=1, initial_delay=0.0).sleep(1), 0.0) + + +class TestRetryableClassification(unittest.TestCase): + def test_transient_statuses_are_retryable(self): + for status in (429, 500, 502, 503, 504): + with self.subTest(status=status): + self.assertTrue(is_retryable_status(status)) + self.assertIn(status, RETRYABLE_STATUS) + + def test_client_errors_are_not_retryable(self): + for status in (400, 401, 403, 404, 422): + with self.subTest(status=status): + self.assertFalse(is_retryable_status(status)) + + def test_none_status_is_not_retryable(self): + self.assertFalse(is_retryable_status(None)) + self.assertFalse(RetryPolicy().should_retry_status(None)) + + +class TestRetryAfterParsing(unittest.TestCase): + def test_delta_seconds_are_parsed(self): + self.assertEqual(retry_after_seconds(_FakeHeaders("2")), 2.0) + self.assertEqual(retry_after_seconds(_FakeHeaders("0.5")), 0.5) + + def test_missing_or_bogus_values_return_none(self): + for value in (None, "", " ", "Wed, 21 Oct 2026 07:28:00 GMT", "-3", "soon"): + with self.subTest(value=value): + self.assertIsNone(retry_after_seconds(_FakeHeaders(value))) + + def test_no_header_container_is_tolerated(self): + self.assertIsNone(retry_after_seconds(object())) + self.assertIsNone(retry_after_seconds(None)) + + def test_large_values_are_clamped(self): + self.assertEqual(retry_after_seconds(_FakeHeaders("100000")), MAX_RETRY_AFTER) + + +class TestCoercePolicy(unittest.TestCase): + def test_none_yields_the_default(self): + self.assertIs(coerce_policy(None), DEFAULT_RETRY) + + def test_int_becomes_a_policy(self): + self.assertEqual(coerce_policy(3).max_retries, 3) + self.assertEqual(coerce_policy(0).max_retries, 0) + + def test_policy_passes_through(self): + policy = RetryPolicy(max_retries=7) + self.assertIs(coerce_policy(policy), policy) + + def test_other_types_are_rejected(self): + for bad in (True, "3", 1.5, object()): + with self.subTest(bad=bad): + with self.assertRaises(TypeError): + coerce_policy(bad) + + +class TestOpenAICompatRetries(unittest.TestCase): + def _backend(self, url, **kwargs): + return OpenAICompatBackend("fixture", base_url=url + "/v1", timeout=5.0, **kwargs) + + def test_transient_5xx_is_retried_then_succeeds(self): + with Fixture(fail_times=2, fail_status=503) as fixture: + backend = self._backend(fixture.url, max_retries=2) + backend.retry = FAST + result = backend.chat([{"role": "user", "content": "hi"}]) + self.assertEqual(result["text"], "hello") + self.assertEqual(Handler.attempts, 3) + + def test_429_is_retried(self): + with Fixture(fail_times=1, fail_status=429) as fixture: + backend = self._backend(fixture.url, max_retries=2) + backend.retry = FAST + result = backend.chat([{"role": "user", "content": "hi"}]) + self.assertEqual(result["text"], "hello") + self.assertEqual(Handler.attempts, 2) + + def test_client_error_is_not_retried(self): + with Fixture(fail_times=99, fail_status=400) as fixture: + backend = self._backend(fixture.url, max_retries=2) + backend.retry = FAST + with self.assertRaises(RuntimeError) as ctx: + backend.chat([{"role": "user", "content": "hi"}]) + self.assertIn("HTTP 400", str(ctx.exception)) + self.assertEqual(Handler.attempts, 1) + + def test_retries_are_exhausted_then_the_status_is_reported(self): + with Fixture(fail_times=99, fail_status=503) as fixture: + backend = self._backend(fixture.url, max_retries=1) + backend.retry = fast(1) + with self.assertRaises(RuntimeError) as ctx: + backend.chat([{"role": "user", "content": "hi"}]) + self.assertIn("HTTP 503", str(ctx.exception)) + self.assertEqual(Handler.attempts, 2) + + def test_more_retries_means_more_attempts(self): + for retries in (0, 1, 3): + with self.subTest(max_retries=retries): + with Fixture(fail_times=99, fail_status=503) as fixture: + backend = self._backend(fixture.url, max_retries=retries) + backend.retry = fast(retries) + with self.assertRaises(RuntimeError): + backend.chat([{"role": "user", "content": "hi"}]) + self.assertEqual(Handler.attempts, retries + 1) + + def test_zero_retries_makes_exactly_one_attempt(self): + with Fixture(fail_times=99, fail_status=503) as fixture: + backend = self._backend(fixture.url, max_retries=0) + with self.assertRaises(RuntimeError): + backend.chat([{"role": "user", "content": "hi"}]) + self.assertEqual(Handler.attempts, 1) + + def test_refused_connection_is_retried_then_reported(self): + backend = self._backend(dead_url(), max_retries=2) + backend.retry = FAST + with self.assertRaises(ConnectionError) as ctx: + backend.chat([{"role": "user", "content": "hi"}]) + self.assertIn("not reachable", str(ctx.exception)) + + def test_connection_retries_can_be_disabled(self): + backend = self._backend(dead_url(), max_retries=0) + with self.assertRaises(ConnectionError): + backend.chat([{"role": "user", "content": "hi"}]) + + def test_model_listing_is_retried_too(self): + with Fixture(fail_times=1, fail_status=503) as fixture: + backend = self._backend(fixture.url, max_retries=1) + backend.retry = FAST + models = backend.list_models() + self.assertEqual(models[0]["id"], "fixture") + self.assertEqual(Handler.attempts, 2) + + def test_streaming_retries_before_the_first_frame(self): + with Fixture(fail_times=2, fail_status=503) as fixture: + backend = self._backend(fixture.url, max_retries=2) + backend.retry = FAST + chunks = list(backend.chat_stream([{"role": "user", "content": "hi"}])) + self.assertEqual("".join(c.get("text", "") for c in chunks), "hello") + self.assertEqual(Handler.attempts, 3) + + def test_streaming_does_not_replay_after_frames_arrive(self): + with Fixture() as fixture: + backend = self._backend(fixture.url, max_retries=2) + backend.retry = FAST + chunks = list(backend.chat_stream([{"role": "user", "content": "hi"}])) + self.assertEqual("".join(c.get("text", "") for c in chunks), "hello") + self.assertEqual(Handler.attempts, 1) + + def test_retry_after_header_is_consumed(self): + with Fixture(fail_times=1, fail_status=429, retry_after=0) as fixture: + backend = self._backend(fixture.url, max_retries=2) + result = backend.chat([{"role": "user", "content": "hi"}]) + self.assertEqual(result["text"], "hello") + self.assertEqual(Handler.attempts, 2) + + def test_retry_policy_is_configurable_by_int_or_object(self): + self.assertEqual(self._backend("http://127.0.0.1:1").retry, DEFAULT_RETRY) + self.assertEqual(self._backend("http://127.0.0.1:1", max_retries=5).retry.max_retries, 5) + custom = RetryPolicy(max_retries=9) + self.assertIs(self._backend("http://127.0.0.1:1", max_retries=custom).retry, custom) + with self.assertRaises(TypeError): + self._backend("http://127.0.0.1:1", max_retries="lots") + + +class TestOllamaRetries(unittest.TestCase): + def test_transient_5xx_is_retried(self): + with Fixture(fail_times=2, fail_status=503) as fixture: + backend = OllamaBackend("fixture", host=fixture.url, timeout=5.0, max_retries=2) + backend.retry = FAST + result = backend.chat([{"role": "user", "content": "hi"}]) + self.assertEqual(result["text"], "hello") + self.assertEqual(Handler.attempts, 3) + + def test_client_error_is_not_retried(self): + with Fixture(fail_times=99, fail_status=400) as fixture: + backend = OllamaBackend("fixture", host=fixture.url, timeout=5.0, max_retries=2) + backend.retry = FAST + with self.assertRaises(RuntimeError) as ctx: + backend.chat([{"role": "user", "content": "hi"}]) + self.assertIn("HTTP 400", str(ctx.exception)) + self.assertEqual(Handler.attempts, 1) + + def test_zero_retries_makes_exactly_one_attempt(self): + with Fixture(fail_times=99, fail_status=503) as fixture: + backend = OllamaBackend("fixture", host=fixture.url, timeout=5.0, max_retries=0) + with self.assertRaises(RuntimeError): + backend.chat([{"role": "user", "content": "hi"}]) + self.assertEqual(Handler.attempts, 1) + + def test_connection_failure_message_still_points_at_ollama_serve(self): + backend = OllamaBackend("fixture", host=dead_url(), timeout=0.4, max_retries=0) + with self.assertRaises(ConnectionError) as ctx: + backend.chat([{"role": "user", "content": "hi"}]) + self.assertIn("ollama serve", str(ctx.exception)) + + def test_streaming_retries_before_the_first_frame(self): + with Fixture(fail_times=1, fail_status=503) as fixture: + backend = OllamaBackend("fixture", host=fixture.url, timeout=5.0, max_retries=1) + backend.retry = FAST + chunks = list(backend.chat_stream([{"role": "user", "content": "hi"}])) + self.assertEqual("".join(c.get("text", "") for c in chunks), "hello") + self.assertEqual(Handler.attempts, 2) + + def test_capability_detection_does_not_retry(self): + # Detection is best-effort and must stay fast, so it is single-attempt + # even when the backend itself retries. + backend = OllamaBackend("fixture", host=dead_url(), timeout=0.3, max_retries=5) + result = backend.detect_capabilities(timeout=0.3) + self.assertFalse(result["detected"]) + self.assertIsNotNone(result["error"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_server.py b/tests/test_server.py index ea683df..cd91082 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -199,6 +199,70 @@ def test_malformed_body_is_4xx_not_500(self): self.assertGreaterEqual(resp.status_code, 400) self.assertLess(resp.status_code, 500) + def test_responses_string_input(self): + resp = self.client.post( + "/v1/responses", json={"model": "echo-model", "input": "hello responses"} + ) + self.assertEqual(resp.status_code, 200, msg=resp.text[:500]) + body = resp.json() + self.assertEqual(body["object"], "response") + self.assertEqual(body["status"], "completed") + output = body["output"][0] + self.assertEqual(output["type"], "message") + self.assertEqual(output["role"], "assistant") + self.assertIn("hello responses", output["content"][0]["text"]) + + def test_responses_message_list_and_instructions(self): + resp = self.client.post( + "/v1/responses", + json={ + "model": "echo-model", + "instructions": "Be terse.", + "input": [ + {"role": "user", "content": "first"}, + {"type": "input_text", "text": "second"}, + { + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": "third"}], + }, + ], + }, + ) + self.assertEqual(resp.status_code, 200, msg=resp.text[:500]) + self.assertIn("third", resp.json()["output"][0]["content"][0]["text"]) + + def test_responses_rejects_bad_input_and_stateful_options(self): + for payload in ({"input": ""}, {"input": []}, {"input": [{"type": "nonsense"}]}): + resp = self.client.post("/v1/responses", json=payload) + self.assertEqual(resp.status_code, 400, msg=resp.text[:300]) + for payload in ( + {"input": "hi", "previous_response_id": "resp_1"}, + {"input": "hi", "background": True}, + {"input": "hi", "store": True}, + {"input": "hi", "reasoning": {"effort": "low"}}, + ): + resp = self.client.post("/v1/responses", json=payload) + self.assertEqual(resp.status_code, 400, msg=resp.text[:300]) + + def test_responses_streaming_deltas_and_completed(self): + resp = self.client.post("/v1/responses", json={"input": "hi", "stream": True}) + self.assertEqual(resp.status_code, 200, msg=resp.text[:500]) + events = [ + line[len("data: ") :] + for line in resp.text.splitlines() + if line.startswith("data: ") and line.strip() != "data: [DONE]" + ] + import json as _json + + parsed = [_json.loads(e) for e in events] + deltas = [e["delta"] for e in parsed if e.get("type") == "response.output_text.delta"] + self.assertTrue(deltas) + completed = [e for e in parsed if e.get("type") == "response.completed"] + self.assertEqual(len(completed), 1) + full = completed[0]["response"]["output"][0]["content"][0]["text"] + self.assertEqual(full, "".join(deltas)) + def test_embeddings_use_the_llm_vectors_when_it_returns_openai_shape(self): """LLM.embed() answers with {"data": [...]}: use those vectors, not a stub.""" app = make_app(DictEmbedLLM()) diff --git a/tests/test_structured.py b/tests/test_structured.py new file mode 100644 index 0000000..137cd19 --- /dev/null +++ b/tests/test_structured.py @@ -0,0 +1,100 @@ +"""Unit and regression tests for resilient JSON repair and structured chat.""" + +import json +import unittest +from unittest.mock import MagicMock + +from local_llm_kit.structured import chat_structured, extract_json, repair_json, validate_schema + + +class TestStructuredJSON(unittest.TestCase): + def test_repair_markdown_code_fences(self): + raw = '```json\n{\n "status": "ok",\n "code": 200\n}\n```' + repaired = repair_json(raw) + data = json.loads(repaired) + self.assertEqual(data["status"], "ok") + self.assertEqual(data["code"], 200) + + def test_repair_conversational_wrapping(self): + raw = 'Here is the result you requested:\n{"summary": "done"}\nLet me know if you need anything else!' + data = extract_json(raw) + self.assertEqual(data["summary"], "done") + + def test_repair_trailing_commas(self): + raw = '{"items": [1, 2, 3,], "user": {"id": 1,},}' + data = extract_json(raw) + self.assertEqual(data["items"], [1, 2, 3]) + self.assertEqual(data["user"]["id"], 1) + + def test_repair_python_literals(self): + raw = '{"active": True, "archived": False, "details": None}' + data = extract_json(raw) + self.assertTrue(data["active"]) + self.assertFalse(data["archived"]) + self.assertIsNone(data["details"]) + + def test_repair_single_quotes(self): + raw = "{'name': 'Bob', 'role': 'editor'}" + data = extract_json(raw) + self.assertEqual(data["name"], "Bob") + self.assertEqual(data["role"], "editor") + + def test_repair_unquoted_keys(self): + raw = '{name: "Charlie", score: 95}' + data = extract_json(raw) + self.assertEqual(data["name"], "Charlie") + self.assertEqual(data["score"], 95) + + def test_repair_truncated_braces(self): + raw = '{"users": [{"id": 1}, {"id": 2' + data = extract_json(raw) + self.assertEqual(len(data["users"]), 2) + self.assertEqual(data["users"][0]["id"], 1) + self.assertEqual(data["users"][1]["id"], 2) + + def test_extract_json_direct(self): + raw = '{"valid": true}' + self.assertEqual(extract_json(raw), {"valid": True}) + + def test_schema_validation(self): + schema = { + "type": "object", + "required": ["name", "age"], + "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}, + } + # Valid + validate_schema({"name": "David", "age": 30}, schema) + + # Missing field + with self.assertRaises(ValueError) as ctx: + validate_schema({"name": "David"}, schema) + self.assertIn("age", str(ctx.exception)) + + def test_chat_structured_retry_loop(self): + mock_llm = MagicMock() + + # Turn 1: Malformed JSON that cannot be parsed + # Turn 2: Valid JSON + mock_llm.chat.side_effect = [ + { + "choices": [ + { + "message": { + "content": "I apologize, but this is not JSON at all: <>" + } + } + ] + }, + {"choices": [{"message": {"content": '{"resolved": true, "attempt": 2}'}}]}, + ] + + messages = [{"role": "user", "content": "Return status"}] + result = chat_structured(mock_llm, messages, max_retries=2) + + self.assertEqual(result["resolved"], True) + self.assertEqual(result["attempt"], 2) + self.assertEqual(mock_llm.chat.call_count, 2) + + +if __name__ == "__main__": + unittest.main()