diff --git a/abstractcore/architectures/detection.py b/abstractcore/architectures/detection.py index 37ed84fd..9c49b603 100644 --- a/abstractcore/architectures/detection.py +++ b/abstractcore/architectures/detection.py @@ -721,6 +721,9 @@ def format_messages(messages: List[Dict[str, str]], architecture: str) -> str: return "\n".join([f"{msg['role']}: {msg['content']}" for msg in messages]) formatted_parts = [] + bos = arch_format.get("bos_token") + if isinstance(bos, str) and bos: + formatted_parts.append(bos) for msg in messages: role = msg["role"] diff --git a/abstractcore/architectures/response_postprocessing.py b/abstractcore/architectures/response_postprocessing.py index 8d2ec3fd..b5b873c8 100644 --- a/abstractcore/architectures/response_postprocessing.py +++ b/abstractcore/architectures/response_postprocessing.py @@ -222,7 +222,9 @@ class IncrementalThinkingTagStripper: matching `strip_thinking_tags()` behavior (#TRUNCATION labeled). """ - def __init__(self, *, start_tag: str, end_tag: str, assume_visible_start: bool = False) -> None: + def __init__( + self, *, start_tag: str, end_tag: str, assume_visible_start: bool = False, strip_stray_close: bool = False + ) -> None: if not isinstance(start_tag, str) or not start_tag: raise ValueError("start_tag must be a non-empty string") if not isinstance(end_tag, str) or not end_tag: @@ -233,6 +235,19 @@ def __init__(self, *, start_tag: str, end_tag: str, assume_visible_start: bool = self._buffer = "" self._state: str = "visible" if assume_visible_start else "searching" # searching|visible|thinking + # Thinking was switched off, yet some models (LFM3-1.7B) still reason in the + # answer and then write a closing tag they were never given an opening for. + # The text before it has already streamed as content and cannot be taken back; + # the stray tag itself is markup and never part of the answer. Only ONE closing + # tag is the format's (the end of the reasoning, the boundary the non-streamed + # path splits on); a later `` is the answer's own text. (Neither the text + # nor the token id tells a first mention in prose apart: LFM3's `` is an + # added token, produced for the literal string too.) + # Only for a model whose registry entry declares the leak + # (`thinking_off_leaks_close_tag`: LFM3-1.7B, LFM3-VL); any other model's answer + # keeps every character. + self._stray_close_possible = bool(assume_visible_start and strip_stray_close) + self.stray_close_tags = 0 self._current_reasoning_parts: list[str] = [] self._reasoning_blocks: list[str] = [] # Reasoning identified since the last `take_reasoning_delta()`: streamed @@ -365,8 +380,22 @@ def process(self, text: str) -> str: if self._state == "visible": start_idx = self._buffer.find(self._start_tag) + if self._stray_close_possible: + end_idx = self._buffer.find(self._end_tag) + if end_idx != -1 and (start_idx == -1 or end_idx < start_idx): + self._add_visible(out_parts, self._buffer[:end_idx]) + self._buffer = self._buffer[end_idx + len(self._end_tag) :] + self.stray_close_tags += 1 + self._stray_close_possible = False + _logger.warning( + "#THINKING-LEAK: the model closed a thinking block with thinking off; " + "the text before the stray closing tag was streamed as content" + ) + continue if start_idx == -1: keep = self._suffix_prefix_len(self._buffer, self._start_tag) + if self._stray_close_possible: + keep = max(keep, self._suffix_prefix_len(self._buffer, self._end_tag)) if keep: self._add_visible(out_parts, self._buffer[:-keep]) self._buffer = self._buffer[-keep:] @@ -381,6 +410,7 @@ def process(self, text: str) -> str: self._buffer = self._buffer[start_idx + len(self._start_tag) :] self._state = "thinking" self._seen_block = True + self._stray_close_possible = False self._current_reasoning_parts = [] continue @@ -501,6 +531,7 @@ def maybe_create_incremental_thinking_tag_stripper( architecture_format: Optional[Mapping[str, Any]] = None, model_capabilities: Optional[Mapping[str, Any]] = None, assume_visible_start: bool = False, + strip_stray_close: bool = False, ) -> Optional[IncrementalThinkingTagStripper]: """Return an incremental thinking-tag stripper when configured via assets. @@ -520,6 +551,7 @@ def maybe_create_incremental_thinking_tag_stripper( start_tag=start_tag, end_tag=end_tag, assume_visible_start=assume_visible_start, + strip_stray_close=strip_stray_close, ) except Exception: return None diff --git a/abstractcore/assets/architecture_formats.json b/abstractcore/assets/architecture_formats.json index f075573b..c6353e6f 100644 --- a/abstractcore/assets/architecture_formats.json +++ b/abstractcore/assets/architecture_formats.json @@ -1427,8 +1427,16 @@ ] }, "lfm3": { - "description": "Liquid AI LFM3 text tri-hybrid: im_start/end messages and Qwen3-Coder XML tools (official LFM3-1.7B chat template, 2026-10-30).", + "description": "Liquid AI LFM3 family: <|startoftext|> then im_start/end messages, Qwen3-Coder XML tools, tool results as a `tool` turn wrapping (official LFM3-1.7B chat template, checked 2026-11-30). Thinking control is declared per model: the members differ (enable_thinking on 1.7B/VL, on by default; on Omni, off by default; none on Audio, whose generation prompt opens no thinking block). llama_cpp_context: flash attention on and a window-sized sliding-attention cache; the short-convolution state already stops llama.cpp from cutting a cached prefix, so a full-size sliding cache buys nothing (measured at n_ctx 32,768 on llama-cpp-python 0.3.38: sliding cache 320 MiB -> 7.5 MiB, Metal compute buffer 1,178 MiB -> 299 MiB). mlx_vlm_model_types: the config.json model_type mlx-lm ships no module for and mlx-vlm loads from the version given, verified on real weights (MLX provider; a model_type not declared anywhere keeps mlx-lm's own error).", "message_format": "im_start_end", + "bos_token": "<|startoftext|>", + "mlx_vlm_model_types": { + "lfm3": "0.7.12" + }, + "llama_cpp_context": { + "flash_attn": true, + "swa_full": false + }, "system_prefix": "<|im_start|>system\n", "system_suffix": "<|im_end|>\n", "user_prefix": "<|im_start|>user\n", @@ -1445,10 +1453,6 @@ "", "" ], - "thinking_control": { - "template_kwarg": "enable_thinking", - "assistant_prefill_disable": "\n\n\n\n" - }, "reasoning_support": true, "patterns": [ "lfm3-", diff --git a/abstractcore/assets/llamacpp_known_architectures.json b/abstractcore/assets/llamacpp_known_architectures.json index d29fb448..597a86a7 100644 --- a/abstractcore/assets/llamacpp_known_architectures.json +++ b/abstractcore/assets/llamacpp_known_architectures.json @@ -1,8 +1,8 @@ { "schema": "llamacpp_known_architectures_v1", - "llama_cpp_python": "0.3.36", - "llama_cpp_commit": "0c1e57098bba43ac29e6e3b677cdceebdd22334f", - "source": "src/llama-arch.cpp LLM_ARCH_NAMES of the llama.cpp commit vendored by llama-cpp-python 0.3.36", + "llama_cpp_python": "0.3.38", + "llama_cpp_commit": "f5e6915c28f10330885fcb9243a93ae98d3115ab", + "source": "src/llama-arch.cpp LLM_ARCH_NAMES of the llama.cpp commit vendored by llama-cpp-python 0.3.38", "architectures": [ "afmoe", "apertus", @@ -13,12 +13,15 @@ "bailingmoe", "bailingmoe2", "bailingmoe3", + "beam", "bert", "bitnet", "bloom", "chameleon", "chatglm", + "clef", "clip", + "clover_moe", "codeshell", "cogvlm", "cohere2", @@ -31,7 +34,9 @@ "deepseek2-ocr", "deepseek32", "deepseek4", + "deepseek41", "dflash", + "domynedge", "dots1", "dots3note", "dream", @@ -44,8 +49,10 @@ "exaone4", "falcon", "falcon-h1", + "flint", "gemma", "gemma-embedding", + "gemma-embedding2", "gemma2", "gemma3", "gemma3n", @@ -72,38 +79,51 @@ "hunyuan_vl", "hy_v3", "hy_v4", + "inkling2", + "inkling2_loop", "internlm2", "jais", "jais2", "jamba", "jina-bert-v2", "jina-bert-v3", + "k2-horizon", "kimi-k3", + "kimi-k31", "kimi-linear", + "kokoro", + "kolibri1", "laguna", "lfm2", "lfm2moe", + "lfm3", + "limite", "llada", "llada-moe", "llama", "llama-embed", "llama4", "maincoder", + "maion-coder", "mamba", "mamba2", "maple", "mellum", + "metis16", "mimo2", "minicpm", "minicpm3", "minimax-01", "minimax-m2", "minimax-m3", + "mistral-large4", "mistral3", "mistral4", "modern-bert", + "moshi", "mpt", "muse-glimmer", + "muse-spark", "nanbeige", "nemotron", "nemotron_h", @@ -140,11 +160,13 @@ "qwen3vlmoe", "qwen4exp", "refact", + "ricursive", "rnd1", "rwkv6", "rwkv6qwen2", "rwkv7", "seed_oss", + "sensenova_u1", "smallthinker", "smollm3", "spark2_5", @@ -155,7 +177,12 @@ "t5", "t5encoder", "talkie", + "tiny-voca", + "vllm-decision2", "wavtokenizer-dec", - "xverse" + "xing4_0", + "xverse", + "zaya1", + "zonos3" ] } \ No newline at end of file diff --git a/abstractcore/assets/model_capabilities.json b/abstractcore/assets/model_capabilities.json index c2a122bd..991bd67f 100644 --- a/abstractcore/assets/model_capabilities.json +++ b/abstractcore/assets/model_capabilities.json @@ -12507,18 +12507,26 @@ }, "lfm3-1.7b": { "canonical_name": "lfm3-1.7b", + "gguf_template_tools": true, + "thinking_off_leaks_close_tag": true, "aliases": [ "LiquidAI/LFM3-1.7B", "LiquidAI/LFM3-1.7B-GGUF", "lmstudio-community/LFM3-1.7B-GGUF", "LiquidAI/LFM3-1.7B-MLX-4bit", - "LiquidAI/LFM3-1.7B-MLX-8bit" + "LiquidAI/LFM3-1.7B-MLX-5bit", + "LiquidAI/LFM3-1.7B-MLX-6bit", + "LiquidAI/LFM3-1.7B-MLX-8bit", + "LiquidAI/LFM3-1.7B-MLX-bf16", + "LiquidAI/LFM3-1.7B-FP8", + "LiquidAI/LFM3-1.7B-NVFP4", + "LiquidAI/LFM3-1.7B-ONNX" ], "max_tokens": 262144, "max_output_tokens": null, "tool_support": "native", "structured_output": "prompted", - "parallel_tools": false, + "parallel_tools": true, "max_tools": -1, "vision_support": false, "audio_support": false, @@ -12535,19 +12543,27 @@ "text" ] }, - "notes": "Text-only tri-hybrid LFM3: 13 short-convolution, 5 sliding-attention and 6 full-attention layers. Its chat template supports enable_thinking and Qwen3-Coder XML tool calls. This is the post-trained text model, not the Base, VL, Audio or Omni checkpoint.", - "source": "https://huggingface.co/LiquidAI/LFM3-1.7B model card, config.json and chat_template.jinja, accessed 2026-10-30.", + "notes": "Text-only tri-hybrid LFM3: 13 short-convolution, 5 sliding-attention (256-token window) and 6 full-attention layers, so only the 6 full-attention layers keep a whole-context cache (12,288 bytes per token in bf16, measured on MLX). Reasoning is on by default: the chat template opens in the generation prompt; enable_thinking=False writes an empty instead. Qwen3-Coder XML tool calls (), several calls in one reply. Card sampling (generation_config.json): temperature 0.1, top_k 50, repetition_penalty 1.1, no top_p (1.0). With thinking off the model still reasons in its answer on harder prompts (sometimes followed by a stray , or a block it opens itself); Core reports that text as reasoning, never as the answer and never discarded. The card does not recommend it for agentic coding or complex multi-step reasoning. This is the post-trained text model, not the Base, VL, Audio or Omni checkpoint. Loads on mlx-vlm >= 0.7.12 (no mlx-lm release has lfm3; 0.7.11 has the module but leaks the reasoning into the answer) and llama-cpp-python >= 0.3.38.", + "source": "https://huggingface.co/LiquidAI/LFM3-1.7B model card, config.json, generation_config.json and chat_template.jinja (accessed 2026-11-30); LiquidAI/LFM3-1.7B-GGUF metadata (general.sampling.*); real runs on mlx-vlm 0.7.12 and llama-cpp-python 0.3.38, 2026-11-30 (two tool calls in one reply on both engines).", "thinking_tags": [ "", "" ], "thinking_control": { - "template_kwarg": "enable_thinking" + "template_kwarg": "enable_thinking", + "assistant_prefill_disable": "" + }, + "inference_parameters": { + "temperature": 0.1, + "top_p": 1.0, + "top_k": 50, + "repeat_penalty": 1.1 }, "license": "lfm1.0" }, "lfm3-vl-2b": { "canonical_name": "lfm3-vl-2b", + "thinking_off_leaks_close_tag": true, "aliases": [ "LiquidAI/LFM3-VL-2B", "LiquidAI/LFM3-VL-2B-GGUF", @@ -12592,7 +12608,8 @@ "" ], "thinking_control": { - "template_kwarg": "enable_thinking" + "template_kwarg": "enable_thinking", + "assistant_prefill_disable": "" }, "license": "lfm1.0", "inference_parameters": { diff --git a/abstractcore/assets/model_downloads_catalog.json b/abstractcore/assets/model_downloads_catalog.json index 39eed805..1167ce62 100644 --- a/abstractcore/assets/model_downloads_catalog.json +++ b/abstractcore/assets/model_downloads_catalog.json @@ -6094,17 +6094,27 @@ "provider": "huggingface", "artifact": "LiquidAI/LFM3-1.7B-GGUF:Q4_K_M", "quant": "q4_k_m", - "download_bytes": null, - "size_source": "unknown", - "verified": false + "download_bytes": 1099627808, + "size_source": "catalog", + "verified": true, + "upstream": { + "method": "hf_api", + "checked": "2026-11-30", + "revision": "cd0c74c575b5c416f3011b5b4c298077f26ca8c2" + } }, { "provider": "mlx", "artifact": "LiquidAI/LFM3-1.7B-MLX-4bit", "quant": "4bit", - "download_bytes": null, - "size_source": "unknown", - "verified": false + "download_bytes": 973083386, + "size_source": "catalog", + "verified": true, + "upstream": { + "method": "hf_api", + "checked": "2026-11-30", + "revision": "91f34088d6946482cbcae11b85d4657093618c34" + } }, { "provider": "lmstudio", @@ -6115,7 +6125,13 @@ "verified": false } ], - "notes": "Primary model cards and local engine inventory audited 2026-10-30; installed variants retain their exact identifiers." + "notes": "Sizes and revisions from the Hugging Face API on 2026-11-30 (weight files only); both artifacts ran end to end through AbstractCore on 2026-11-30 (MLX via mlx-vlm >= 0.7.12, GGUF via llama-cpp-python >= 0.3.38). The LM Studio row is the catalog name; its size is not recorded.", + "kv_geometry": { + "n_layers": 6, + "n_kv_heads": 4, + "head_dim": 128, + "source": "config.json of LiquidAI/LFM3-1.7B-MLX-4bit@91f34088: 6 of 24 layers are full_attention (layer_types); 5 sliding_attention layers keep a 256-token window and 13 conv layers a fixed state. Measured on MLX 2026-11-30: 12,288 bytes per cached token" + } }, { "id": "bonsai-27b", diff --git a/abstractcore/core/retry.py b/abstractcore/core/retry.py index c96e0335..cb991bb8 100644 --- a/abstractcore/core/retry.py +++ b/abstractcore/core/retry.py @@ -265,6 +265,10 @@ def __init__(self, config: Optional[RetryConfig] = None): "InvalidRequestError", "ModelNotFoundError", "UnsupportedFeatureError", + # An attachment that cannot be read stays unreadable on attempt 2. + "MediaProcessingError", + "UnsupportedMediaTypeError", + "FileSizeExceededError", "ConfigurationError", # A lane that cannot speculate will not start speculating on # attempt 2; retrying only multiplies the latency the caller was diff --git a/abstractcore/media/auto_handler.py b/abstractcore/media/auto_handler.py index 5e5d9f98..47a204e8 100644 --- a/abstractcore/media/auto_handler.py +++ b/abstractcore/media/auto_handler.py @@ -11,8 +11,8 @@ from pathlib import Path from typing import Dict, Any, Optional, List -from .base import BaseMediaHandler -from .types import MediaContent, MediaType, ContentFormat, detect_media_type +from .base import BaseMediaHandler, MediaProcessingError, UnsupportedMediaTypeError +from .types import MediaContent, MediaType, ContentFormat, detect_media_type, is_text_file from .processors import ImageProcessor, TextProcessor, PDFProcessor, OfficeProcessor, AudioProcessor, VideoProcessor from ..exceptions import UnsupportedFeatureError @@ -190,16 +190,15 @@ def _select_processor(self, file_path: Path, media_type: MediaType) -> Optional[ # Office documents elif file_extension in {'.docx', '.xlsx', '.pptx'}: - if self._available_processors.get('office', False): - return self._get_office_processor() - else: - self.logger.warning(f"Office document processing requested but unstructured library not available for {file_extension}") - # Fall back to text processor (limited functionality) - return self._get_text_processor() + # Without its library the OfficeProcessor raises its own install hint; + # the text reader would hand the model the zip archive's bytes. + return self._get_office_processor() - # Text-based documents - else: + # Text-based documents (e.g. .rtf); a binary file of a type AbstractCore has + # no reader for (.doc, .xls, .zip, .bin...) has none. + elif is_text_file(file_path): return self._get_text_processor() + return None # Handle audio elif media_type == MediaType.AUDIO: @@ -242,54 +241,29 @@ def _process_internal(self, file_path: Path, media_type: MediaType, **kwargs) -> # Select the appropriate processor processor = self._select_processor(file_path, media_type) + # A file that cannot be read is an error naming the file, its kind and the cause, + # never a `[Document: name]` placeholder sent to the model as if it were the content. if processor is None: - # Create a basic text representation as fallback - return self._create_fallback_content(file_path, media_type) - - # Delegate to the selected processor + raise UnsupportedMediaTypeError( + f"Cannot read {media_type.value} file '{file_path.name}': {self._no_reader_cause(file_path, media_type)}" + + (". Remove it, or attach a text or PDF version" if media_type == MediaType.DOCUMENT else "") + ) try: return processor._process_internal(file_path, media_type, **kwargs) except Exception as e: - self.logger.error(f"Processor {processor.__class__.__name__} failed for {file_path}: {e}") - # Fall back to basic content creation - return self._create_fallback_content(file_path, media_type) - - def _create_fallback_content(self, file_path: Path, media_type: MediaType) -> MediaContent: - """ - Create fallback content when processors are not available. - - Args: - file_path: Path to the file - media_type: Media type - - Returns: - Basic MediaContent object - """ - file_extension = file_path.suffix.lower() + raise MediaProcessingError( + f"Cannot read {media_type.value} file '{file_path.name}': {e}. " + "Attach a valid copy (or a text or PDF version), or remove it" + ) from e - # Try to read as text for document types - if media_type == MediaType.DOCUMENT and file_extension in {'.txt', '.md', '.csv', '.tsv'}: - try: - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - content_format = ContentFormat.TEXT - except Exception: - content = f"[Unable to read file: {file_path.name}]" - content_format = ContentFormat.TEXT - else: - # For other types, create a placeholder - content = f"[{media_type.value.title()}: {file_path.name}]" - content_format = ContentFormat.TEXT - - return self._create_media_content( - content=content, - file_path=file_path, - media_type=media_type, - content_format=content_format, - mime_type="auto", - fallback_processing=True, - available_processors=list(self._available_processors.keys()) - ) + def _no_reader_cause(self, file_path: Path, media_type: MediaType) -> str: + """Why no processor serves this file (see `_select_processor`).""" + if media_type == MediaType.IMAGE: + return "the image reader (Pillow) is not installed: pip install -U abstractcore" + if media_type == MediaType.DOCUMENT: + ext = file_path.suffix.lower() or "(no extension)" + return f"AbstractCore has no reader for binary {ext} files" + return f"AbstractCore has no reader for {media_type.value} files" def _should_apply_compression(self, file_path: Path, media_type: MediaType, provider: str, model: str, glyph_compression: str) -> bool: diff --git a/abstractcore/media/handlers/local_handler.py b/abstractcore/media/handlers/local_handler.py index 8b809052..1a451e21 100644 --- a/abstractcore/media/handlers/local_handler.py +++ b/abstractcore/media/handlers/local_handler.py @@ -268,12 +268,19 @@ def create_multimodal_message(self, text: str, media_contents: List[MediaContent # Decision logic: require BOTH provider AND model support for structured format if provider_vision_support and model_vision_support: self.logger.debug(f"Using structured format for vision model '{self.model_name}' on provider '{self.provider_name}'") + from ..base import MediaProcessingError + try: return self._create_structured_message(text, media_contents) + except MediaProcessingError: + raise # names the attachment that cannot go except Exception as e: - self.logger.error(f"Failed to create structured message for vision model: {e}") - self.logger.warning("Falling back to text-embedded format") - return self._create_text_embedded_message(text, media_contents) + # The model can see; an attachment we failed to encode must not turn into a + # text placeholder (or a caption from another model) without a word. + raise MediaProcessingError( + f"could not build the {self.provider_name} message for vision model " + f"{self.model_name!r}: {type(e).__name__}: {e}" + ) from e # Handle capability mismatches with detailed warnings if has_images and not model_vision_support and self.model_name: @@ -399,11 +406,26 @@ def _create_text_embedded_message(self, text: str, media_contents: List[MediaCon ) # Fallback to basic placeholder other_parts.append(f"[Image {i+1}: {file_name} - vision processing unavailable]") + elif media_content.media_type in (MediaType.AUDIO, MediaType.VIDEO): + # Sound and moving pictures have no text form here: writing the file's + # path (or its bytes' repr) into the prompt is a placeholder the model + # would answer about as if it had heard or seen it. + from ..base import UnsupportedMediaTypeError + + file_name = media_content.metadata.get('file_name', f'{media_content.media_type.value}_{i+1}') + raise UnsupportedMediaTypeError( + f"{media_content.media_type.value} attachment '{file_name}' cannot be sent to " + f"{self.model_name or 'this model'} as text; it needs a route that carries " + f"{media_content.media_type.value}" + + ( + ": pass audio_policy='speech_to_text' (or configure the input.voice default) to send a transcript" + if media_content.media_type == MediaType.AUDIO + else ": pass video_policy='frames_caption' or extracted frames as images" + ) + ) else: # Embed text/document content directly - content = str(media_content.content) - file_name = media_content.metadata.get('file_name', f'document_{i+1}') - other_parts.append(f"\n\n--- Content from {file_name} ---\n{content}\n--- End of {file_name} ---") + other_parts.append(self._document_text_block(media_content, i)) message_parts: List[str] = [] @@ -430,7 +452,30 @@ def _create_text_embedded_message(self, text: str, media_contents: List[MediaCon def _create_structured_message(self, text: str, media_contents: List[MediaContent]) -> Dict[str, Any]: """ Create a structured message for local providers using provider-specific format. + + Every attachment must reach the message: the Ollama and LM Studio formats carry + base64 images, and a text or document attachment goes into the text as it does for a + text-only model; anything else (a file path, a kind this handler cannot encode) + raises, naming that attachment, instead of being left out. """ + base64_images_only = self.provider_name in ("ollama", "lmstudio") + unsent = [ + mc for mc in media_contents + if not self.can_handle_media(mc) + or (base64_images_only and not ( + (mc.media_type == MediaType.IMAGE and mc.content_format == ContentFormat.BASE64) + or self._is_text_attachment(mc))) + ] + if unsent: + from ..base import MediaProcessingError + + names = ", ".join( + f"{mc.media_type.value} '{mc.metadata.get('file_name') or mc.file_path or '?'}' ({mc.content_format.value})" + for mc in unsent + ) + raise MediaProcessingError( + f"{self.provider_name} message for {self.model_name!r} cannot carry: {names}" + ) if self.provider_name == "ollama": return self._create_ollama_message(text, media_contents) elif self.provider_name == "lmstudio": @@ -447,7 +492,9 @@ def _create_ollama_message(self, text: str, media_contents: List[MediaContent]) """ message = { "role": "user", - "content": text.strip() if text.strip() else "What's in this image?" + "content": (text.strip() if text.strip() else "What's in this image?") + "".join( + self._document_text_block(mc, i) for i, mc in enumerate(media_contents) if self._is_text_attachment(mc) + ), } # Extract base64 images for Ollama's images array @@ -506,11 +553,29 @@ def _create_lmstudio_message(self, text: str, media_contents: List[MediaContent] else: self.logger.warning(f"LMStudio requires base64 image format, got {media_content.content_format}") + for i, media_content in enumerate(media_contents): + if self._is_text_attachment(media_content): + content.append({"type": "text", "text": self._document_text_block(media_content, i)}) + return { "role": "user", "content": content } + @staticmethod + def _is_text_attachment(media_content: MediaContent) -> bool: + """A text or document attachment already read as text (it goes into the prompt).""" + return ( + media_content.media_type in (MediaType.TEXT, MediaType.DOCUMENT) + and media_content.content_format == ContentFormat.TEXT + ) + + @staticmethod + def _document_text_block(media_content: MediaContent, index: int) -> str: + """The `--- Content from ---` block a text attachment becomes in the prompt.""" + file_name = media_content.metadata.get('file_name', f'document_{index+1}') + return f"\n\n--- Content from {file_name} ---\n{media_content.content}\n--- End of {file_name} ---" + def _create_generic_structured_message(self, text: str, media_contents: List[MediaContent]) -> Dict[str, Any]: """ Create generic structured message for unknown local providers. diff --git a/abstractcore/providers/anthropic_provider.py b/abstractcore/providers/anthropic_provider.py index 1bddb7f4..fcd3cba4 100644 --- a/abstractcore/providers/anthropic_provider.py +++ b/abstractcore/providers/anthropic_provider.py @@ -320,12 +320,8 @@ def _generate_internal(self, # Create multimodal message combining text and media multimodal_message = media_handler.create_multimodal_message(prompt, media) api_messages.append(multimodal_message) - except ImportError: - self.logger.warning("Media processing not available. Install with: pip install -U abstractcore") - api_messages.append({"role": "user", "content": prompt}) except Exception as e: - self.logger.warning(f"Failed to process media content: {e}") - api_messages.append({"role": "user", "content": prompt}) + raise self._media_not_delivered(media, route="Anthropic messages API", cause=e) from e else: api_messages.append({"role": "user", "content": prompt}) @@ -368,10 +364,8 @@ def _generate_internal(self, else: text0 = str(api_messages[idx].get("content") or "") api_messages[idx] = media_handler.create_multimodal_message(text0, media) - except ImportError: - self.logger.warning("Media processing not available. Install with: pip install -U abstractcore") except Exception as e: - self.logger.warning(f"Failed to process media content: {e}") + raise self._media_not_delivered(media, route="Anthropic messages API", cause=e) from e # Prepare API call parameters using unified system generation_kwargs = self._prepare_generation_kwargs(**kwargs) @@ -560,12 +554,8 @@ async def _agenerate_internal(self, # Create multimodal message combining text and media multimodal_message = media_handler.create_multimodal_message(prompt, media) api_messages.append(multimodal_message) - except ImportError: - self.logger.warning("Media processing not available. Install with: pip install -U abstractcore") - api_messages.append({"role": "user", "content": prompt}) except Exception as e: - self.logger.warning(f"Failed to process media content: {e}") - api_messages.append({"role": "user", "content": prompt}) + raise self._media_not_delivered(media, route="Anthropic messages API", cause=e) from e else: api_messages.append({"role": "user", "content": prompt}) @@ -608,10 +598,8 @@ async def _agenerate_internal(self, else: text0 = str(api_messages[idx].get("content") or "") api_messages[idx] = media_handler.create_multimodal_message(text0, media) - except ImportError: - self.logger.warning("Media processing not available. Install with: pip install -U abstractcore") except Exception as e: - self.logger.warning(f"Failed to process media content: {e}") + raise self._media_not_delivered(media, route="Anthropic messages API", cause=e) from e # Prepare API call parameters (same logic as sync) generation_kwargs = self._prepare_generation_kwargs(**kwargs) diff --git a/abstractcore/providers/base.py b/abstractcore/providers/base.py index 5dc5f312..47dbea7e 100644 --- a/abstractcore/providers/base.py +++ b/abstractcore/providers/base.py @@ -1358,6 +1358,16 @@ def _has_explicit_duration(msg: str) -> bool: ): return error + # A request this provider or model cannot carry (an attachment the route cannot + # deliver, a file that cannot be read) is the CALLER's, decided before anything is + # sent: keep its type. Wrapped as ProviderAPIError("API error: ...") it was retried + # as a transient fault and reached HTTP clients as a server error. + from ..exceptions import UnsupportedFeatureError + from ..media.base import MediaProcessingError + + if isinstance(error, (UnsupportedFeatureError, MediaProcessingError)): + return error + # `require_acceleration=True` is a caller assertion about the LANE, not a # transient API fault. Wrapping it into ProviderAPIError would destroy # both the type callers catch and the machine-readable `.reason` that is @@ -4416,13 +4426,23 @@ def _pop_stt_route_params(route: Dict[str, Any]) -> Dict[str, Any]: media_enrichment = enrichments elif policy == "auto": - if model_supports_audio: + # The native path needs both a model that hears AND a provider route that + # carries audio to it (`_carries_native_audio`); otherwise the configured + # speech-to-text serves the request, as for a model that cannot hear. + if model_supports_audio and self._carries_native_audio(): pass # provider-native path else: if not stt_route_default: + why = ( + f"model '{self.model}' hears, but {self.__class__.__name__} has no route that carries audio to it" + if model_supports_audio + else f"Audio input is not supported by model '{self.model}'" + ) raise UnsupportedFeatureError( - f"Audio input is not supported by model '{self.model}', and input.voice is not configured. " - "Configure the input.voice capability default for STT fallback, or choose an audio-capable model." + f"{why}, and input.voice is not configured. " + "Configure the input.voice capability default for speech-to-text, or pass " + "audio_policy='speech_to_text' with a speech-to-text engine installed, or choose a " + "route that carries audio." ) stt_language = kwargs.pop("audio_language", None) or kwargs.pop( "stt_language", None @@ -5521,6 +5541,12 @@ def unified_stream(): model_capabilities=self.model_capabilities, assume_visible_start=thinking_effectively_off or native_separated_reasoning, + # A model the registry says closes a block it was never given + # with thinking off (LFM3): that one tag is markup, removed and + # counted in metadata `thinking_stray_close_tags`. + strip_stray_close=self._strips_stray_close_tag( + thinking_effectively_off, native_separated_reasoning + ), ) last_chunk: Optional[GenerateResponse] = None last_seen_usage: Optional[Dict[str, Any]] = None @@ -5640,9 +5666,15 @@ def unified_stream(): model_capabilities=self.model_capabilities, ) if thinking_stripper is not None: + stray_before = thinking_stripper.stray_close_tags processed_chunk.content = thinking_stripper.process( processed_chunk.content ) + if thinking_stripper.stray_close_tags != stray_before: + processed_chunk.metadata = dict(processed_chunk.metadata or {}) + processed_chunk.metadata["thinking_stray_close_tags"] = ( + thinking_stripper.stray_close_tags + ) # Inline thinking streams as `reasoning_delta` as it # is generated (display only; the complete # `reasoning` still comes from the stripper at the @@ -6641,17 +6673,31 @@ def _handle_prompted_tool_execution( return response # Parse tool calls from response content using UniversalToolHandler - tool_call_response = self.tool_handler.parse_response(response.content, mode="prompted") + tool_names = self._offered_tool_names(tools) + tool_call_response = self.tool_handler.parse_response( + response.content, mode="prompted", tool_names=tool_names + ) tool_calls = tool_call_response.tool_calls if not tool_calls: return response # Execute with events and return result - return self._execute_tools_with_events(response, tool_calls, execute_tools_param) + return self._execute_tools_with_events( + response, tool_calls, execute_tools_param, tool_names=tool_names + ) + + def _offered_tool_names(self, tools: Optional[List[Any]]) -> set[str]: + """Names of the tools offered on a request (any accepted tool shape).""" + return self._get_allowed_tool_names(self._convert_request_tools(tools, warn_unknown=False)) def _execute_tools_with_events( - self, response: GenerateResponse, tool_calls: List, execute_tools_param: bool = None + self, + response: GenerateResponse, + tool_calls: List, + execute_tools_param: bool = None, + *, + tool_names: Optional[set[str]] = None, ) -> GenerateResponse: """Core tool execution with event emission (shared implementation)""" # Check if tool execution is enabled @@ -6714,7 +6760,9 @@ def _execute_tools_with_events( # Return updated response with tool results # Use the cleaned content from tool parsing - tool_call_response = self.tool_handler.parse_response(response.content, mode="prompted") + tool_call_response = self.tool_handler.parse_response( + response.content, mode="prompted", tool_names=tool_names + ) cleaned_content = tool_call_response.content or "" return GenerateResponse( content=cleaned_content + results_text, @@ -8720,6 +8768,47 @@ def estimate_tokens(self, text: str) -> int: """Rough estimation of token count for given text""" return super().estimate_tokens(text) + def _carries_native_audio(self) -> bool: + """Whether this provider delivers an audio attachment to the model itself. No provider + in AbstractCore does today (Ollama, LM Studio and the GGUF lane have no audio transport; + the MLX native lane takes image frames only): under `audio_policy='auto'` a model the + registry says hears is then served by the configured speech-to-text, like any other.""" + return False + + def _strips_stray_close_tag(self, thinking_off: bool, native_separated_reasoning: bool) -> bool: + """With thinking off, remove the one closing tag a model writes for a block it was never + given: only for a model whose registry entry declares that leak + (`thinking_off_leaks_close_tag`: LFM3-1.7B, LFM3-VL), never on a route that already + separates reasoning (LM Studio's native one); every other answer keeps every character.""" + caps = self.model_capabilities if isinstance(getattr(self, "model_capabilities", None), dict) else {} + return bool(thinking_off and not native_separated_reasoning and caps.get("thinking_off_leaks_close_tag") is True) + + def _media_not_delivered(self, media: Any, *, route: str, cause: Any) -> UnsupportedFeatureError: + """The error for an attachment this provider cannot deliver to the model. + + Never a text-only request instead: a model asked about a picture or a recording + it never received answers anyway, and nobody can tell (finding 2026-11-30: the + OpenAI-compatible lane caught an encoding error, logged it and sent the text + alone). Names the model, the route and the kind of each attachment.""" + items = media if isinstance(media, (list, tuple)) else [media] + described = [] + for item in items: + kind = getattr(getattr(item, "media_type", None), "value", None) or getattr(item, "media_type", None) + path = getattr(item, "file_path", None) + if isinstance(item, dict): + kind = kind or item.get("media_type") or item.get("type") + path = path or item.get("file_path") or item.get("path") + if isinstance(item, str): + path = item + name = str(path).replace("\\", "/").rsplit("/", 1)[-1] if path else None + described.append(f"{kind or 'file'}" + (f" '{name}'" if name else "")) + what = ", ".join(described) or "file" + reason = f"{type(cause).__name__}: {cause}" if isinstance(cause, BaseException) else str(cause) + return UnsupportedFeatureError( + f"{self.__class__.__name__} cannot deliver the attached {what} to model '{self.model}' " + f"({route}): {reason}. The request was not sent without it." + ) + def _process_media_content( self, media: List[Union[str, Dict[str, Any], "MediaContent"]], @@ -8772,10 +8861,9 @@ def _process_media_content( if result.success: processed_media.append(result.media_content) else: - self.logger.warning( - f"Failed to process media file {media_item}: {result.error_message}" + raise self._media_not_delivered( + media_item, route="reading the attachment", cause=result.error_message ) - continue elif hasattr(media_item, "media_type"): # Already a MediaContent object @@ -8825,8 +8913,8 @@ def _process_media_content( media_content.mime_type = content_type.strip() processed_media.append(media_content) else: - self.logger.warning( - f"Failed to process media file {file_path_raw}: {result.error_message}" + raise self._media_not_delivered( + media_item, route="reading the attachment", cause=result.error_message ) continue @@ -8835,19 +8923,20 @@ def _process_media_content( media_content = MediaContent.from_dict(media_item) processed_media.append(media_content) except Exception as e: - self.logger.warning(f"Failed to convert media dict at index {i}: {e}") - continue + raise self._media_not_delivered( + media_item, route=f"reading attachment {i + 1}", cause=e + ) from e else: - self.logger.warning(f"Unsupported media type at index {i}: {type(media_item)}") - continue + raise self._media_not_delivered( + media_item, route=f"reading attachment {i + 1}", + cause=f"unsupported attachment type {type(media_item).__name__}", + ) + except UnsupportedFeatureError: + raise except Exception as e: - self.logger.warning(f"Failed to process media item at index {i}: {e}") - continue - - if not processed_media and media: - self.logger.warning("No media items were successfully processed") + raise self._media_not_delivered(media_item, route=f"reading attachment {i + 1}", cause=e) from e return processed_media @@ -9149,7 +9238,7 @@ def _normalize_tool_calls_passthrough( return response try: - parsed = tool_handler.parse_response(content, mode="prompted") + parsed = tool_handler.parse_response(content, mode="prompted", tool_names=allowed_names) except Exception: return response @@ -9234,7 +9323,7 @@ def _recover_tool_calls_from_reasoning( for opener in self._TOOL_ENVELOPE_OPENER_RE.finditer(body): tail = body[opener.start():] try: - parsed = tool_handler.parse_response(tail, mode="prompted") + parsed = tool_handler.parse_response(tail, mode="prompted", tool_names=allowed_names) except Exception: continue calls = getattr(parsed, "tool_calls", None) diff --git a/abstractcore/providers/huggingface_provider.py b/abstractcore/providers/huggingface_provider.py index 6e3fcc5b..4588d4b9 100644 --- a/abstractcore/providers/huggingface_provider.py +++ b/abstractcore/providers/huggingface_provider.py @@ -83,6 +83,7 @@ def _module_available(name: str) -> bool: ModelNotDownloadedError, ModelNotFoundError, ProviderError, + UnsupportedFeatureError, format_model_error, ) from .generation_cancel import CANCEL_KWARG, as_cancel_event, cancelled_error, raise_if_cancelled @@ -108,6 +109,13 @@ def _engine_install_hint(what: str) -> str: _MPS_GENERATION_LOCK = threading.Lock() +def _raise_if_cancelled_while_queued(cancel_event: Optional[threading.Event]) -> None: + if cancel_event is not None and cancel_event.is_set(): + from .generation_cancel import cancelled_error + + raise cancelled_error(provider="huggingface", where="while waiting for the model (another generation held it)") + + class _InstanceGenerationWorker: """Every operation on the model of ONE provider instance runs on ONE worker thread, one at a time. @@ -164,7 +172,12 @@ def _interrupted(cancel_event: Optional[threading.Event]) -> None: def run(self, call: Any, *, cancel_event: Optional[threading.Event] = None) -> Any: if self._on_worker(): return call() - future = self._submit(call) + + def queued_call() -> Any: + _raise_if_cancelled_while_queued(cancel_event) + return call() + + future = self._submit(queued_call) if future is None: return call() try: @@ -192,6 +205,9 @@ def stream(self, call: Any, *, cancel_event: Optional[threading.Event] = None, def task() -> None: try: try: + # A caller that stopped while this call waited for the worker (a client that + # left during a busy run) never starts its generation. + _raise_if_cancelled_while_queued(cancel_event) chunks = call() except BaseException as exc: # noqa: BLE001 - delivered to the caller at the call started.set_exception(exc) @@ -1589,7 +1605,13 @@ def _apply_provider_thinking_kwargs( # the base ladder warns honestly. Text-shaped requests are served by the # control-plane local render, where both controls are real. shape = request_shape if isinstance(request_shape, dict) else {} - lane_blocked = bool(shape.get("has_response_model")) or bool(shape.get("has_media")) + # A structured request blocks the lane only when it takes llama.cpp's constrained + # output (response_format through create_chat_completion). Behind a template that opens + # a thinking block it takes the prompted lane instead (see the structured handler), an + # ordinary text request: it gets the same thinking control as any other. + lane_blocked = ( + bool(shape.get("has_response_model")) and not self.gguf_constrained_output_lands_in_thinking() + ) or bool(shape.get("has_media")) # Lane-predicate PARITY (adversarial find V2-F2, 2026-08-20): the claim # must be computed with the same tests the control-plane gate applies at # generate time, or a claim-then-fallback path reaches @@ -1604,14 +1626,15 @@ def _apply_provider_thinking_kwargs( if isinstance(shape_messages, list) and shape_messages: # Same criteria as _gguf_control_plane_can_stream, applied to the raw # caller messages (whose roles/content _gguf_build_chat_messages copies - # verbatim): exotic roles (tool/function) or content-parts payloads + # verbatim): roles the renderer cannot render or content-parts payloads # fall back to create_chat_completion. + roles = self._gguf_control_plane_roles() for msg in shape_messages: if not isinstance(msg, dict): lane_blocked = True break role = str(msg.get("role") or "").strip().lower() - if role not in {"system", "user", "assistant"}: + if role not in roles: lane_blocked = True break content = msg.get("content") @@ -1897,7 +1920,7 @@ def _gguf_slot_fits(self, model_path: Any, n_ctx: int) -> Optional[str]: from .hf_residency import gguf_file_geometry geom = gguf_file_geometry(model_path) or {} - kv = int(kv_cache_bytes(geom, int(n_ctx), pad_v=True) or 0) if geom else 0 + kv = int(kv_cache_bytes(geom, int(n_ctx), **self._gguf_kv_estimate_kwargs()) or 0) if geom else 0 n_head = int(geom.get("head_count") or 0) need = kv + 512 * n_head * 4 * int(n_ctx) buffer = self._gguf_memory_buffer() @@ -2030,6 +2053,28 @@ def _gguf_prompt_cache_chat_format(self) -> str: return "llama-3" return "" + # llama.cpp context parameters an architecture declares in its format + # (`architecture_formats.json` -> `llama_cpp_context`), each a measured choice. + _GGUF_CONTEXT_OPTION_KEYS = ("flash_attn", "swa_full") + + def _gguf_context_options(self) -> Dict[str, Any]: + """`Llama(...)` context options declared for this architecture, e.g. LFM3 + `{"flash_attn": true, "swa_full": false}` (measured at n_ctx 32K: sliding-window + cache 320 MiB -> 7.5 MiB, compute buffer 1,178 MiB -> 299 MiB). Undeclared: {} + (llama-cpp-python's defaults).""" + cfg = getattr(self, "architecture_config", None) + declared = cfg.get("llama_cpp_context") if isinstance(cfg, dict) else None + if not isinstance(declared, dict): + return {} + return {k: bool(declared[k]) for k in self._GGUF_CONTEXT_OPTION_KEYS if isinstance(declared.get(k), bool)} + + def _gguf_kv_estimate_kwargs(self) -> Dict[str, Any]: + """`kv_cache_bytes` options matching the context this provider builds: V rows are + padded only without flash attention; a sliding layer is full-size unless `swa_full` + is declared False.""" + opts = self._gguf_context_options() + return {"pad_v": not opts.get("flash_attn", False), "swa_full": opts.get("swa_full", True)} + def _gguf_architecture_message_format(self) -> str: cfg = getattr(self, "architecture_config", None) if not isinstance(cfg, dict): @@ -2407,6 +2452,7 @@ def prompt_cache_render_fragment( prompt_text, prompt_tokens = self._gguf_render_prompt_tokens( messages=chat_messages, add_generation_prompt=bool(add_generation_prompt), + tools=self._gguf_template_tools(tools), ) serialized = json.dumps( { @@ -2495,6 +2541,7 @@ def prompt_cache_render_bloc_text( return self._gguf_render_prompt_text( messages=chat_messages, add_generation_prompt=bool(add_generation_prompt), + tools=self._gguf_template_tools(tools), ) except Exception: return None @@ -2891,6 +2938,41 @@ def _gguf_clone_llama_cache(self, cache_obj: Any, *, capacity_bytes: int) -> Opt return None return cloned + def _gguf_template_tools_declared(self) -> bool: + """The model's registry entry declares that its GGUF template's own tool block and `tool` + turns are served (`model_capabilities.json` -> `gguf_template_tools: true`), per model: + only what was run on real weights (LFM3-1.7B); its siblings' templates differ.""" + caps = getattr(self, "model_capabilities", None) + return isinstance(caps, dict) and caps.get("gguf_template_tools") is True + + def _gguf_template_tools(self, tools: Optional[List[Dict[str, Any]]]) -> Optional[List[Dict[str, Any]]]: + """The request's tools as the model's OWN embedded chat template takes them (`tools=`), + when this lane renders through that template and the template renders tools (both + GGUF lanes then send exactly the model's own tool block: LFM3 `` JSON lines). + None otherwise: the prompted tool block is merged into the system turn instead. + Same rule as the MLX lane (`chat_template_renders_tools`).""" + if not tools: + return None + llm = getattr(self, "llm", None) + if not str(getattr(llm, "chat_format", "") or "").startswith("chat_template"): + return None + metadata = getattr(llm, "metadata", {}) + template = str(metadata.get("tokenizer.chat_template") or "") if isinstance(metadata, dict) else "" + handler = getattr(self, "tool_handler", None) + if not template or handler is None or not getattr(handler, "supports_prompted", False): + return None + # Opt-in per model (`gguf_template_tools` in model_capabilities.json, verified on + # real weights: LFM3-1.7B). Every other GGUF keeps the prompted block, as on 2.41.0: the + # parsers read a family's calls in its declared syntax, which is not always the one its + # template teaches (Llama 3.1: bare JSON, not detected streamed; Mistral `[TOOL_CALLS]`). + if not self._gguf_template_tools_declared(): + return None + from ..tools.handler import chat_template_renders_tools + + if not chat_template_renders_tools(template): + return None + return handler.format_tools_for_chat_template(tools) or None + def _gguf_build_chat_messages( self, *, @@ -2918,7 +3000,9 @@ def _gguf_build_chat_messages( # per-lane parity test in tests/providers/test_prompt_cache_thinking_prefix.py. base_system = (system_prompt.strip() or None) if isinstance(system_prompt, str) else None merged_system = ( - merge_tools_into_system(self.tool_handler, base_system, tools) if tools else base_system + merge_tools_into_system(self.tool_handler, base_system, tools) + if tools and self._gguf_template_tools(tools) is None + else base_system ) if isinstance(merged_system, str) and merged_system: chat_messages.append({"role": "system", "content": merged_system}) @@ -3145,6 +3229,7 @@ def _gguf_render_llama_cpp_chat_template_prompt( add_generation_prompt: bool, enable_thinking: Optional[bool] = None, reasoning_effort: Optional[str] = None, + tools: Optional[List[Dict[str, Any]]] = None, ) -> str: metadata = getattr(getattr(self, "llm", None), "metadata", {}) template = str(metadata.get("tokenizer.chat_template") or "") if isinstance(metadata, dict) else "" @@ -3161,12 +3246,19 @@ def _gguf_render_llama_cpp_chat_template_prompt( eos = self._gguf_model_token_text(int(self.llm.token_eos())) except Exception: eos = "" - formatter = Jinja2ChatFormatter( - template, - eos_token=eos or "", - bos_token=bos or "", - add_generation_prompt=bool(add_generation_prompt), - ) + # Compiling the template is the expensive part (about 24 ms for LFM3's 12 KB template, + # measured on llama-cpp-python 0.3.38) and every controlled request renders two or more + # times (the prompt, its generation boundary): compile once per template and tokens. + key = (template, eos or "", bos or "", bool(add_generation_prompt)) + formatters = self.__dict__.setdefault("_gguf_template_formatters", {}) + formatter = formatters.get(key) + if formatter is None: + formatter = formatters[key] = Jinja2ChatFormatter( + template, + eos_token=eos or "", + bos_token=bos or "", + add_generation_prompt=bool(add_generation_prompt), + ) render_kwargs: Dict[str, Any] = {} if isinstance(enable_thinking, bool): render_kwargs["enable_thinking"] = enable_thinking @@ -3179,8 +3271,10 @@ def _gguf_render_llama_cpp_chat_template_prompt( if effort_kwarg: render_kwargs[effort_kwarg] = reasoning_effort response = formatter( - messages=[copy.deepcopy(m) for m in messages if isinstance(m, dict)], - tools=None, + messages=self._gguf_normalize_tool_call_arguments_for_template( + [copy.deepcopy(m) for m in messages if isinstance(m, dict)] + ), + tools=tools or None, tool_choice=None, **render_kwargs, ) @@ -3217,9 +3311,13 @@ def _gguf_render_prompt_text( add_generation_prompt: bool, enable_thinking: Optional[bool] = None, reasoning_effort: Optional[str] = None, + tools: Optional[List[Dict[str, Any]]] = None, ) -> str: """The exact prompt STRING this lane sends for these chat messages. + `tools`: the `_gguf_template_tools` list, rendered only by the model's own + template (the other renderers get the tools merged into the system turn). + Split out of `_gguf_render_prompt_tokens` so the bloc planner and the live generate path share ONE renderer and ONE tokenizer (below). The planner's guarantee — every bloc boundary is a true token prefix of the @@ -3239,6 +3337,7 @@ def _gguf_render_prompt_text( add_generation_prompt=bool(add_generation_prompt), enable_thinking=enable_thinking, reasoning_effort=reasoning_effort, + tools=tools, ) return self._gguf_render_chatml_prompt( messages=messages, @@ -3282,12 +3381,14 @@ def _gguf_render_prompt_tokens( add_generation_prompt: bool, enable_thinking: Optional[bool] = None, reasoning_effort: Optional[str] = None, + tools: Optional[List[Dict[str, Any]]] = None, ) -> tuple[str, tuple[int, ...]]: prompt_text = self._gguf_render_prompt_text( messages=messages, add_generation_prompt=bool(add_generation_prompt), enable_thinking=enable_thinking, reasoning_effort=reasoning_effort, + tools=tools, ) return prompt_text, self._gguf_tokenize_rendered_prompt(prompt_text) @@ -3479,6 +3580,7 @@ def _gguf_generation_prompt_boundary( prompt_tokens: tuple[int, ...], enable_thinking: Optional[bool] = None, reasoning_effort: Optional[str] = None, + tools: Optional[List[Dict[str, Any]]] = None, ) -> Optional[int]: """Token POSITION where this call's generation-prompt scaffolding begins. @@ -3516,6 +3618,7 @@ def _gguf_generation_prompt_boundary( add_generation_prompt=False, enable_thinking=enable_thinking, reasoning_effort=reasoning_effort, + tools=tools, ) except Exception: return None @@ -3776,7 +3879,7 @@ def _gguf_ensure_cpu_fit(self, model_path: Any, n_ctx: int) -> None: avail = ((get_memory_snapshot() or {}).get("ram") or {}).get("available_bytes") weights_b = _gguf_total_weight_bytes(model_path) - kv = kv_cache_bytes(gguf_file_geometry(model_path), int(n_ctx), pad_v=True) + kv = kv_cache_bytes(gguf_file_geometry(model_path), int(n_ctx), **self._gguf_kv_estimate_kwargs()) if not (isinstance(avail, int) and weights_b and kv): return need = int(weights_b) + int(kv) + (1 << 30) @@ -3811,7 +3914,7 @@ def _gguf_ensure_fit(self, model_path: Any, min_ctx: int) -> Optional[Dict[str, if getattr(self, "_gguf_weights_already_resident", False): weights_b = 0 # borrowed: only this context's KV is allocated reserve = max(self._GGUF_RESERVE_FLOOR_BYTES, int(total_b * self._GGUF_RESERVE_FRACTION)) - need = int(weights_b) + int(kv_cache_bytes(geom, int(min_ctx), pad_v=True) or 0) + reserve + need = int(weights_b) + int(kv_cache_bytes(geom, int(min_ctx), **self._gguf_kv_estimate_kwargs()) or 0) + reserve except Exception: return None from . import process_residency @@ -3941,8 +4044,8 @@ def _gguf_max_context_that_fits(self, model_path: Any, advertised: int) -> Optio if getattr(self, "_gguf_weights_already_resident", False): weights_b = 0 # borrowed: only this context's KV is allocated buffer = self._gguf_memory_buffer() - one = kv_cache_breakdown(geom, 1, pad_v=True) or {} - two = kv_cache_breakdown(geom, 2, pad_v=True) or {} + one = kv_cache_breakdown(geom, 1, **self._gguf_kv_estimate_kwargs()) or {} + two = kv_cache_breakdown(geom, 2, **self._gguf_kv_estimate_kwargs()) or {} kv_per_token = int((two.get("kv_bytes") or 0) - (one.get("kv_bytes") or 0)) if kv_per_token <= 0: return None @@ -6245,6 +6348,7 @@ def _prompt_cache_backend_append( messages=chat_messages, add_generation_prompt=state.add_generation_prompt, enable_thinking=gguf_enable_thinking, + tools=self._gguf_template_tools(state.tools), ) with getattr(self, "_gguf_prompt_cache_lock", _MPS_GENERATION_LOCK): @@ -8067,6 +8171,14 @@ def _load_gguf_model_unlocked(self): gguf_arch = read_gguf_architecture(Path(model_path)) except Exception: gguf_arch = None + # An architecture the INSTALLED llama.cpp does not name cannot load: say which + # llama-cpp-python release can (lfm3: 0.3.38), before any context is tried. + if gguf_arch: + from ..utils.model_cache import gguf_unloadable_reason + + unloadable = gguf_unloadable_reason(gguf_arch) + if unloadable: + raise RuntimeError(f"GGUF model {self.model}: {unloadable}") model_lower = self.model.lower() @@ -8221,6 +8333,7 @@ def _load_gguf_model_unlocked(self): "n_batch": 512, "use_mmap": use_mmap, "use_mlock": False, + **self._gguf_context_options(), } try: @@ -8895,22 +9008,16 @@ def _generate_transformers(self, if isinstance(multimodal_message, str): prompt = multimodal_message else: - # If we get a structured message, extract the content - if isinstance(multimodal_message, dict) and "content" in multimodal_message: - if isinstance(multimodal_message["content"], list): - # Find text content in the structured message - text_content = "" - for item in multimodal_message["content"]: - if item.get("type") == "text": - text_content = item.get("text", "") - break - prompt = text_content or prompt - else: - prompt = str(multimodal_message["content"]) - except ImportError: - self.logger.warning("Media processing not available. Install with: pip install -U abstractcore") + # A structured (image-bearing) message cannot ride this text lane: + # keeping only its text would answer about pictures never seen. + raise self._media_not_delivered( + media, route="transformers text-generation lane (no image input)", + cause="the model's loader on this lane takes text only", + ) + except UnsupportedFeatureError: + raise except Exception as e: - self.logger.warning(f"Failed to process media content: {e}") + raise self._media_not_delivered(media, route="transformers text-generation lane", cause=e) from e # Generation parameters using unified system generation_kwargs = self._prepare_generation_kwargs(**kwargs) @@ -9758,62 +9865,48 @@ def _generate_gguf(self, finish_reason="error" ) - # Handle media content for the user message - use proper vision format for GGUF models + # Media for the user message. This lane loads no vision projector (mmproj) and + # no audio encoder, so pixels and sound have no transport here: the old code + # built `{"type": "image"}` parts for a sighted model, which the template + # rendered as image markers with nothing behind them (the model was told a + # picture was there and never saw it), and caught any error to send the text + # alone. Documents still go in as text (LocalMediaHandler); an image the + # handler cannot turn into text, or audio/video, raises. media_enrichment = None if media: + from ..media.types import MediaType + try: from ..architectures.detection import supports_vision - # Check if this model supports vision natively - if supports_vision(self.model): - # Use HuggingFace multimodal format for vision-capable GGUF models - user_message_content = [] - - # Add text content - user_message_content.append({"type": "text", "text": prompt}) - - # Add media content - for media_item in media: - if hasattr(media_item, 'file_path') and media_item.file_path: - # Use file:// URL format as specified in HuggingFace docs - file_path = str(media_item.file_path) - if not file_path.startswith('file://'): - file_path = f"file://{file_path}" - user_message_content.append({ - "type": "image", - "image": file_path - }) - elif hasattr(media_item, 'content') and media_item.content: - # For base64 or other content, we might need to save to temp file - import tempfile - import base64 - with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp_file: - if isinstance(media_item.content, str) and media_item.content.startswith('data:'): - # Handle base64 data URLs - header, data = media_item.content.split(',', 1) - decoded_data = base64.b64decode(data) - tmp_file.write(decoded_data) - else: - tmp_file.write(media_item.content) - tmp_file.flush() - user_message_content.append({ - "type": "image", - "image": f"file://{tmp_file.name}" - }) - else: - # Fallback to text-based media handling for non-vision models - from ..media.handlers import LocalMediaHandler - media_handler = LocalMediaHandler("huggingface", self.model_capabilities, model_name=self.model) - multimodal_message = media_handler.create_multimodal_message(prompt, media) - media_enrichment = getattr(media_handler, "media_enrichment", None) - user_message_content = multimodal_message if isinstance(multimodal_message, str) else prompt + carried = [ + m for m in media + if getattr(m, "media_type", None) in (MediaType.AUDIO, MediaType.VIDEO) + or (getattr(m, "media_type", None) == MediaType.IMAGE and supports_vision(self.model)) + ] + if carried: + raise self._media_not_delivered( + carried, route="GGUF through llama-cpp-python", + cause=( + "this provider loads no vision projector (mmproj) or audio encoder for GGUF models; " + "send images through the MLX, LM Studio or Ollama provider, and audio with " + "audio_policy='speech_to_text'" + ), + ) + from ..media.handlers import LocalMediaHandler - except ImportError: - self.logger.warning("Media processing not available. Install with: pip install -U abstractcore") - user_message_content = prompt + media_handler = LocalMediaHandler("huggingface", self.model_capabilities, model_name=self.model) + multimodal_message = media_handler.create_multimodal_message(prompt, media) + media_enrichment = getattr(media_handler, "media_enrichment", None) + if not isinstance(multimodal_message, str): + raise self._media_not_delivered( + media, route="GGUF through llama-cpp-python", cause="the attachment did not become text", + ) + user_message_content = multimodal_message + except UnsupportedFeatureError: + raise except Exception as e: - self.logger.warning(f"Failed to process media content: {e}") - user_message_content = prompt + raise self._media_not_delivered(media, route="GGUF through llama-cpp-python", cause=e) from e else: user_message_content = prompt @@ -9862,6 +9955,17 @@ def _generate_gguf(self, "top_p": unified_kwargs.get("top_p", 0.9), "stream": stream } + # The same sampler settings the control-plane lane applies: the caller's, else the + # provider's top_k, else the model card's (registry `inference_parameters`: LFM3 + # top_k 50, repeat_penalty 1.1). Undeclared ones keep llama-cpp-python's defaults. + for _name, _provider_attr in (("top_k", True), ("repeat_penalty", False), ("min_p", False)): + _value = kwargs.get(_name) + if _value is None and _provider_attr: + _value = getattr(self, _name, None) + if _value is None: + _value = self._metadata_generation_default(_name, None) + if _value is not None: + generation_kwargs[_name] = _value host_cancel = None if cancel_event is not None: # Fallback lane (create_chat_completion): per-sampled-token check @@ -9891,15 +9995,21 @@ def _generate_gguf(self, # llama-cpp-python supports native structured outputs using the response_format parameter # This provides server-side guaranteed schema compliance if response_model and PYDANTIC_AVAILABLE: - json_schema = response_model.model_json_schema() + # llama-cpp-python builds a grammar only for `{"type": "json_object"}`, from its + # `schema` (`llama_chat_format._grammar_for_response_format`); the OpenAI + # `json_schema` shape it ignores, so that request was an unconstrained generation + # the structured handler then re-ran on the prompted lane (2 generations each). generation_kwargs["response_format"] = { - "type": "json_schema", - "json_schema": { - "name": response_model.__name__, - "schema": json_schema - } + "type": "json_object", + "schema": response_model.model_json_schema(), } + # The model's own embedded template renders the tool block itself (LFM3 + # `` JSON): hand it the tools, exactly as the control-plane lane does. + template_tools = self._gguf_template_tools(tools) + if template_tools: + generation_kwargs["tools"] = template_tools + # Handle tools - both native and prompted support has_native_tools = False if tools: @@ -9960,6 +10070,7 @@ def _generate_gguf(self, else None ), cancel_event=cancel_event, + tools=self._gguf_template_tools(tools), ) marker = self._thinking_disable_prefill(gguf_enable_thinking) @@ -10112,6 +10223,19 @@ def _gguf_control_plane_stop_strings(self) -> List[str]: # ChatML and chatml-function-calling. return ["<|im_end|>"] + def gguf_constrained_output_lands_in_thinking(self) -> bool: + """True when the create_chat_completion lane's generation prompt opens a thinking block + (LFM3's template: `enable_thinking | default(true)` -> ``), so a grammar-constrained + answer would be written inside it (the structured handler then uses the prompted lane). + Rendered once per provider with a one-turn probe conversation; a template that cannot be + re-rendered is reported by `_gguf_fallback_prompt_text` and answers False (as 2.41.0).""" + cached = getattr(self, "_gguf_constrained_lands_in_thinking", None) + if cached is None: + prompt, error = self._gguf_fallback_prompt_text([{"role": "user", "content": "x"}]) + cached = error is None and self._thinking_opened_chunk(prompt) is not None + self._gguf_constrained_lands_in_thinking = cached + return bool(cached) + def _thinking_opened_chunk(self, prompt_text: Any) -> Optional[GenerateResponse]: """The leading stream chunk saying the rendered prompt opened the thinking block. @@ -10210,14 +10334,27 @@ def _apply_prompt_opened_thinking(self, response: Any, prompt_text: Any) -> Any: response.metadata = meta return response + def _gguf_control_plane_roles(self) -> set: + """Message roles the control-plane renderer renders faithfully: the model's own + embedded template renders `tool` turns (and assistant `tool_calls`) itself; the + hand-built ChatML / Llama-3 renderers know system, user and assistant only.""" + roles = {"system", "user", "assistant"} + if ( + self._gguf_prompt_cache_control_plane_chat_format() == "llama-cpp-chat-template" + and self._gguf_template_tools_declared() + ): + roles.add("tool") # opt-in per family, like the template's tool block (2.41.0 otherwise) + return roles + def _gguf_control_plane_can_stream(self, chat_messages: List[Dict[str, Any]]) -> bool: """Return True when control-plane streaming can safely handle the message payloads.""" # Control-plane renderer/tokenizer only supports text content (strings / JSON-serializable). + roles = self._gguf_control_plane_roles() for msg in chat_messages or []: if not isinstance(msg, dict): return False role = str(msg.get("role") or "").strip().lower() - if role not in {"system", "user", "assistant"}: + if role not in roles: return False content = msg.get("content") if content is None: @@ -10252,6 +10389,7 @@ def _gguf_control_plane_stream_generate( cache_state: Optional[_GGUFPromptCacheValue] = None, cache_key: Optional[str] = None, cancel_event: Any = None, + tools: Optional[List[Dict[str, Any]]] = None, ) -> Iterator[GenerateResponse]: """Generate GGUF text by prefilling cached KV state and sampling from it. @@ -10270,7 +10408,6 @@ def _gguf_control_plane_stream_generate( return stop_strs = [s for s in (self._gguf_control_plane_stop_strings() or []) if isinstance(s, str) and s] - flush_threshold = 160 # Render inside the generator body must DEGRADE, not raise: a template # that refuses a conversation shape (e.g. the Ornith template's @@ -10284,6 +10421,7 @@ def _gguf_control_plane_stream_generate( add_generation_prompt=True, enable_thinking=enable_thinking, reasoning_effort=reasoning_effort, + tools=tools, ) except Exception as e: yield GenerateResponse( @@ -10346,6 +10484,7 @@ def _gguf_control_plane_stream_generate( prompt_tokens=prompt_tokens, enable_thinking=enable_thinking, reasoning_effort=reasoning_effort, + tools=tools, ) # Same STRUCTURE as the MLX and transformers lanes (parity, 2026-08-07): # mode/key identify the cache, outcome/cached_tokens/fed_tokens describe @@ -10471,7 +10610,12 @@ def _gguf_control_plane_stream_generate( if token_bytes: pending += decoder.decode(token_bytes) - if len(pending) > flush_threshold: + # Each decoded piece goes out at once. (A 160-character buffer here held the + # first text back for ~40 tokens, 0.3 s at 120 tok/s, and an answer shorter + # than that arrived in one piece at the end. Nothing needs it: stops are + # matched on token ids above, and tool-call and thinking markup is held back + # downstream only while it may still be the start of a tag.) + if pending: yield GenerateResponse(content=pending, model=self.model) pending = "" if context_exhausted: @@ -10589,6 +10733,7 @@ def _gguf_control_plane_generate( cache_state: Optional[_GGUFPromptCacheValue] = None, cache_key: Optional[str] = None, cancel_event: Any = None, + tools: Optional[List[Dict[str, Any]]] = None, ) -> Union[GenerateResponse, Iterator[GenerateResponse]]: if stream: return self._gguf_control_plane_stream_generate( @@ -10613,6 +10758,7 @@ def _gguf_control_plane_generate( cache_state=cache_state, cache_key=cache_key, cancel_event=cancel_event, + tools=tools, ) collected = "" @@ -10640,6 +10786,7 @@ def _gguf_control_plane_generate( cache_state=cache_state, cache_key=cache_key, cancel_event=cancel_event, + tools=tools, ): if isinstance(chunk.metadata, dict) and chunk.metadata.get("_thinking_opened_by_prompt"): # The prompt opened the thinking block: split the whole reply diff --git a/abstractcore/providers/mlx_provider.py b/abstractcore/providers/mlx_provider.py index adf9c1cc..2b768f13 100644 --- a/abstractcore/providers/mlx_provider.py +++ b/abstractcore/providers/mlx_provider.py @@ -60,22 +60,11 @@ # (`MLXProvider._build_prompt`); read back into `metadata["prompt_renderer"]`. _RENDER_STATE = threading.local() -# A template renders tool definitions when `tools` is used as a VARIABLE inside -# a Jinja statement or expression -- not when the word appears in its text, a -# comment or a string literal. import re as _re -_JINJA_TAG = _re.compile(r"\{\{.*?\}\}|\{%.*?%\}", _re.S) -_JINJA_COMMENT = _re.compile(r"\{#.*?#\}", _re.S) -_JINJA_STRING = _re.compile(r"'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"", _re.S) -_TOOLS_NAME = _re.compile(r"\btools\b") - - -def _template_uses_tools(source: str) -> bool: - source = _JINJA_COMMENT.sub("", source or "") - return any( - _TOOLS_NAME.search(_JINJA_STRING.sub("", tag.group(0))) for tag in _JINJA_TAG.finditer(source) - ) +# Shared with the GGUF lane (huggingface_provider): one rule for "this chat template +# renders `tools=` itself". +from ..tools.handler import chat_template_renders_tools as _template_uses_tools class _SharedMLXModel: @@ -136,6 +125,107 @@ def _installed_mlx_versions() -> str: return ", ".join(parts) +def _declared_mlx_vlm_model_types() -> Dict[str, str]: + """model_type -> minimum mlx-vlm version, from `architecture_formats.json` + (`mlx_vlm_model_types` of each family): the types verified on real weights to load + through mlx-vlm when mlx-lm ships no module for them.""" + from ..architectures import detection + + detection._load_json_assets() + declared: Dict[str, str] = {} + for fmt in ((detection._architecture_formats or {}).get("architectures") or {}).values(): + if isinstance(fmt, dict) and isinstance(fmt.get("mlx_vlm_model_types"), dict): + declared.update({str(k): str(v) for k, v in fmt["mlx_vlm_model_types"].items()}) + return declared + + +def _version_at_least(installed: str, floor: str) -> bool: + """`installed >= floor` for dotted release numbers (`0.7.12`, `0.7.2`): compared number by + number, the release part only (`0.7.12.dev1` counts as `0.7.12`).""" + def parts(v: str) -> Tuple[int, ...]: + out = [] + for piece in str(v).split("."): + digits = "" + for ch in piece: + if not ch.isdigit(): + break + digits += ch + if not digits: + break + out.append(int(digits)) + return tuple(out) + + return parts(installed) >= parts(floor) + + +class MlxVlmTooOldError(ImportError): + """A declared mlx-vlm-only model_type, and the installed mlx-vlm cannot load it.""" + + +def _mlx_vlm_only_model_type(config: Any) -> Optional[str]: + """The mlx-vlm model type of a checkpoint the installed mlx-lm cannot build, else None. + + Read from the checkpoint's config.json (`model_type`, with each library's own + remapping), never from the model name, and only for a model_type the registry + declares verified on that lane (`_declared_mlx_vlm_model_types`): mlx-vlm ships + about 190 module names mlx-lm lacks (vision, image-generation, detection models + among them), and none of the others was run through this lane. None when mlx-lm + has the module (the ordinary lane wins, so an upstream mlx-lm release takes over + by itself), for an undeclared type (mlx-lm then raises its own "not supported" + error), or when the config names a `model_file` (code shipped in the model + repository, which AbstractCore never executes). A declared type with mlx-vlm + missing or older than its declared version raises `MlxVlmTooOldError` naming + both versions and the install command. An mlx-lm that cannot be inspected leaves + the decision to mlx-lm's own load. + """ + import importlib.util + + if not isinstance(config, dict) or config.get("model_file"): + return None + raw = str(config.get("model_type") or "").strip() + if not raw: + return None + floor = _declared_mlx_vlm_model_types().get(raw) + if floor is None: + return None + try: + from mlx_lm import utils as lm_utils + + lm_type = raw + architectures = config.get("architectures") or () + if isinstance(architectures, str): + architectures = (architectures,) + arch_remap = getattr(lm_utils, "MODEL_ARCHITECTURE_REMAPPING", {}) or {} + for architecture in architectures: + if (raw, architecture) in arch_remap: + lm_type = arch_remap[(raw, architecture)] + break + else: + lm_type = (getattr(lm_utils, "MODEL_REMAPPING", {}) or {}).get(raw, raw) + if importlib.util.find_spec(f"mlx_lm.models.{lm_type}") is not None: + return None + except (ImportError, ValueError, AttributeError): + return None + import importlib.metadata + + try: + installed: Optional[str] = importlib.metadata.version("mlx-vlm") + except importlib.metadata.PackageNotFoundError: + installed = None + vlm_type = None + if installed is not None and _version_at_least(installed, floor): + from mlx_vlm.utils import get_model_type + + vlm_type = get_model_type(config) + if not vlm_type or importlib.util.find_spec(f"mlx_vlm.models.{vlm_type}") is None: + raise MlxVlmTooOldError( + f"model_type {raw!r} has no module in the installed mlx-lm and loads through mlx-vlm " + f">= {floor}; installed: {('mlx-vlm ' + installed) if installed else 'no mlx-vlm'}. " + f'Fix with: pip install -U "abstractcore[apple]" (or pip install -U "mlx-vlm>={floor}")' + ) + return str(vlm_type) + + def _mlx_model_sharing_enabled(kwargs: Optional[Dict[str, Any]] = None) -> bool: """Read legacy sharing flags so disabled sharing can be refused before allocation.""" explicit = (kwargs or {}).get("share_loaded_model") @@ -2271,6 +2361,12 @@ def _as_text(val: Any) -> str: bos = str(getattr(getattr(self, "tokenizer", None), "bos_token", "") or "") if bos: parts.append(bos) + elif include_bos and not prefilled: + # A format whose template opens with a BOS token (LFM3 `<|startoftext|>`) + # declares it; the tokenizers of such models add none on encode. + declared_bos = (arch_cfg or {}).get("bos_token") + if isinstance(declared_bos, str) and declared_bos: + parts.append(declared_bos) if base_system_prompt and "system" not in prefilled: if is_chatml: @@ -2317,7 +2413,15 @@ def _as_text(val: Any) -> str: if is_chatml: parts.append("<|im_start|>assistant\n") if enable_thinking is False: - parts.append("\n\n\n\n") + # The marker the model's registry entry declares (Qwen + # `\n\n\n\n`, LFM3 ``). + from ..architectures.thinking_controls import resolve_thinking_control_surfaces + + marker = resolve_thinking_control_surfaces( + model_capabilities=getattr(self, "model_capabilities", None), + architecture_format=arch_cfg, + ).assistant_prefill_disable + parts.append(marker if isinstance(marker, str) and marker else "\n\n\n\n") elif is_gemma_turn: parts.append("<|turn>model\n") else: @@ -4300,6 +4404,7 @@ def _looks_like_gguf_dir(d: Path) -> bool: self._resolved_model_id = load_target # The architecture NAME for native-lane error text (the checkpoint's # own `model_type`), so a Qwen3.5 model is never told it is "Qwen4". + _cfg = None try: _cfg = json.loads((Path(load_target) / "config.json").read_text(encoding="utf-8")) self._native_model_type = str(_cfg.get("model_type") or "") or None if isinstance(_cfg, dict) else None @@ -4411,13 +4516,24 @@ def _looks_like_gguf_dir(d: Path) -> bool: mtp_plan = self._plan_mtp_lane(load_target) if mtp_plan is not None and self._enter_mtp_lane(load_target, mtp_plan): return - if self._mlx_batching or mtp_keys: - why = ( - f"its weights carry {len(mtp_keys)} MTP tensor(s) (`mtp.` keys), and mlx-lm " - "mis-converts such checkpoints (garbage output), so it loads only through mlx-vlm" - if mtp_keys - else "native MLX batching (mlx_batching=True) runs through mlx-vlm" - ) + # A model_type the installed mlx-lm has no module for, but mlx-vlm has + # (LFM3: no mlx-lm release ships `lfm3`; mlx-vlm >= 0.7.12 loads it). Decided + # from config.json, never from the name; once mlx-lm ships the module the + # ordinary mlx-lm lane wins again. + vlm_only_type = _mlx_vlm_only_model_type(_cfg) + if self._mlx_batching or mtp_keys or vlm_only_type: + if mtp_keys: + why = ( + f"its weights carry {len(mtp_keys)} MTP tensor(s) (`mtp.` keys), and mlx-lm " + "mis-converts such checkpoints (garbage output), so it loads only through mlx-vlm" + ) + elif vlm_only_type: + why = ( + f"its model_type {vlm_only_type!r} has no module in the installed mlx-lm " + "and one in mlx-vlm, so it loads through mlx-vlm" + ) + else: + why = "native MLX batching (mlx_batching=True) runs through mlx-vlm" self._enter_mtp_lane(load_target, {"drafter": None, "block_size": None, "why": why}) if mtp_keys: self.logger.info( @@ -4512,7 +4628,7 @@ def _looks_like_gguf_dir(d: Path) -> bool: raise ImportError( f"{e}\n" f"Installed MLX stack: {_installed_mlx_versions()} " - f"(AbstractCore requires mlx>=0.32.2, mlx-lm>=0.31.3, mlx-vlm>=0.7.1). " + f"(AbstractCore requires mlx>=0.32.2, mlx-lm>=0.31.3, mlx-vlm>=0.7.12). " f"Fix with: pip install -U \"abstractcore[apple]\"" ) from e except InvalidRequestError: @@ -5035,6 +5151,12 @@ def _prepare_native_sampling(self, kwargs): """ names = ("min_p", "repetition_penalty", "presence_penalty", "frequency_penalty", "repetition_context_size", "presence_context_size", "frequency_context_size", "logit_bias") + if kwargs.get("repetition_penalty") is None: + # The model card's repetition penalty (registry `inference_parameters.repeat_penalty`, + # e.g. LFM3 1.1) is a default like its temperature; a caller's value wins. + declared = self._metadata_generation_default("repeat_penalty", None) + if declared is not None: + kwargs = {**kwargs, "repetition_penalty": declared} self._native_sampling_kwargs = {k: kwargs[k] for k in names if k in kwargs} neutral = {"repetition_penalty": (None, 1, 1.0), "presence_penalty": (None, 0, 0.0), "frequency_penalty": (None, 0, 0.0), "logit_bias": (None, {})} @@ -6721,7 +6843,9 @@ def _stream_generate_with_tools( if scheduled: # Base strips tool-call markup before appending results; # slicing by the ORIGINAL text length truncates results. - cleaned = self.tool_handler.parse_response(collected_content, mode="prompted").content or "" + cleaned = self.tool_handler.parse_response( + collected_content, mode="prompted", tool_names=self._offered_tool_names(tools) + ).content or "" if not final_response.content.startswith(cleaned): raise ProviderAPIError("Tool execution returned a response without its parsed content prefix") result_text = final_response.content[len(cleaned):] diff --git a/abstractcore/providers/ollama_provider.py b/abstractcore/providers/ollama_provider.py index ed7a24f8..dcbbf1fb 100644 --- a/abstractcore/providers/ollama_provider.py +++ b/abstractcore/providers/ollama_provider.py @@ -545,6 +545,9 @@ def _generate_internal(self, tools is not None or messages is not None or think_value is not None + # Attachments ride only the chat route: `/api/generate` below never sends them, + # so a media request there answered from the text alone. + or bool(media) ) # Media enrichment metadata (populated only when we route media through LocalMediaHandler). @@ -585,20 +588,8 @@ def _generate_internal(self, }) else: payload["messages"].append(multimodal_message) - except ImportError: - self.logger.warning("Media processing not available. Install with: pip install -U abstractcore") - if user_message_text: - payload["messages"].append({ - "role": "user", - "content": user_message_text - }) except Exception as e: - self.logger.warning(f"Failed to process media content: {e}") - if user_message_text: - payload["messages"].append({ - "role": "user", - "content": user_message_text - }) + raise self._media_not_delivered(media, route="Ollama chat API", cause=e) from e # Add prompt as separate message if provided (for backward compatibility) elif prompt and prompt.strip(): @@ -917,8 +908,8 @@ async def _agenerate_internal(self, json_schema = response_model.model_json_schema() payload["format"] = json_schema - # Use chat format - use_chat_format = tools is not None or messages is not None + # Use chat format (attachments ride only the chat route, see the sync path) + use_chat_format = tools is not None or messages is not None or bool(media) if use_chat_format: payload["messages"] = [] @@ -945,10 +936,7 @@ async def _agenerate_internal(self, else: payload["messages"].append(multimodal_message) except Exception as e: - if hasattr(self, 'logger'): - self.logger.warning(f"Failed to process media: {e}") - if user_message_text: - payload["messages"].append({"role": "user", "content": user_message_text}) + raise self._media_not_delivered(media, route="Ollama chat API", cause=e) from e elif prompt and prompt.strip(): payload["messages"].append({"role": "user", "content": prompt}) @@ -1109,7 +1097,9 @@ async def _async_stream_generate(self, endpoint: str, payload: Dict[str, Any], def _handle_tool_execution(self, response: GenerateResponse, tools: List[Dict[str, Any]]) -> GenerateResponse: """Handle tool execution for prompted models""" # Parse tool calls from response - tool_call_response = self.tool_handler.parse_response(response.content, mode="prompted") + tool_call_response = self.tool_handler.parse_response( + response.content, mode="prompted", tool_names=self._offered_tool_names(tools) + ) if not tool_call_response.has_tool_calls(): return response diff --git a/abstractcore/providers/openai_compatible_provider.py b/abstractcore/providers/openai_compatible_provider.py index 8e7a200e..c2533699 100644 --- a/abstractcore/providers/openai_compatible_provider.py +++ b/abstractcore/providers/openai_compatible_provider.py @@ -121,6 +121,7 @@ def _resolve(node: Any, *, seen: set[str]) -> Any: AuthenticationError, RateLimitError, InvalidRequestError, + UnsupportedFeatureError, format_model_error, ) from ..tools import UniversalToolHandler, merge_tools_into_system @@ -701,6 +702,17 @@ def _extract_error_detail(self, response: Optional[httpx.Response]) -> Optional[ return None + @staticmethod + def _extract_error_code(response: Optional[httpx.Response]) -> Optional[str]: + """The `error.code` of an OpenAI-shaped error body, if any.""" + try: + data = response.json() if response is not None else None + except Exception: + return None + err = data.get("error") if isinstance(data, dict) else None + code = err.get("code") if isinstance(err, dict) else None + return code if isinstance(code, str) else None + @staticmethod def _extract_retry_after_s(response: Optional[httpx.Response]) -> Optional[float]: """Parse the `Retry-After` header (seconds or HTTP-date) into seconds, if present. @@ -755,6 +767,10 @@ def _raise_for_status(self, response: httpx.Response, *, request_url: Optional[s msg = f"{prefix}: {detail}" if detail else prefix status = int(status_code) + if status == 400 and self._extract_error_code(response) == "unsupported_feature": + # AbstractCore's server: the route or model cannot carry this request (an attachment, + # a feature). The same typed, non-retried error as the stream's refusal event. + raise UnsupportedFeatureError(f"{self.PROVIDER_DISPLAY_NAME} refused the request: {detail}") if status in (401, 403): raise AuthenticationError(msg, status_code=status) if status == 429: @@ -1097,20 +1113,11 @@ def _generate_internal(self, chat_messages[-1] = multimodal_message else: chat_messages.append(multimodal_message) - except ImportError: - self.logger.warning("Media processing not available. Install with: pip install -U abstractcore") - if user_message_text: - chat_messages.append({ - "role": "user", - "content": user_message_text - }) except Exception as e: - self.logger.warning(f"Failed to process media content: {e}") - if user_message_text: - chat_messages.append({ - "role": "user", - "content": user_message_text - }) + # Never the text alone: images and audio vanished here without a word. + raise self._media_not_delivered( + media, route=f"OpenAI-compatible chat API at {self.base_url}", cause=e + ) from e # Add prompt as separate message if provided (for backward compatibility) elif prompt and prompt.strip(): @@ -1681,6 +1688,17 @@ def _raise_on_stream_error_event(self, chunk: Any) -> None: message = self._stream_error_event_detail(chunk) if message is None: return + err = chunk.get("error") if isinstance(chunk, dict) else None + if isinstance(err, dict) and err.get("type") == "invalid_request_error": + # AbstractCore's own server types a streamed refusal with one of its two codes (the + # provider is called on the stream's own thread, so the refusal is an event, not a + # 400): the same error, not retried, as the 400 of the same request. Any other + # server's event keeps the 2.41.0 handling below. + label = self.PROVIDER_DISPLAY_NAME + if err.get("code") == "unsupported_feature": + raise UnsupportedFeatureError(f"{label} refused the request: {message}") + if err.get("code") == "invalid_request": + raise InvalidRequestError(f"{label} API error (400): {message}", status_code=400) raise ProviderAPIError( f"{self.__class__.__name__.replace('Provider', '')} stream failed mid-generation: {message}" ) @@ -1742,14 +1760,10 @@ async def _agenerate_internal(self, chat_messages[-1] = multimodal_message else: chat_messages.append(multimodal_message) - except ImportError: - self.logger.warning("Media processing not available. Install with: pip install -U abstractcore") - if user_message_text: - chat_messages.append({"role": "user", "content": user_message_text}) except Exception as e: - self.logger.warning(f"Failed to process media content: {e}") - if user_message_text: - chat_messages.append({"role": "user", "content": user_message_text}) + raise self._media_not_delivered( + media, route=f"OpenAI-compatible chat API at {self.base_url}", cause=e + ) from e # Add prompt as separate message if provided elif prompt and prompt.strip(): diff --git a/abstractcore/providers/openai_provider.py b/abstractcore/providers/openai_provider.py index cd576c8b..f858cadf 100644 --- a/abstractcore/providers/openai_provider.py +++ b/abstractcore/providers/openai_provider.py @@ -269,10 +269,8 @@ def _generate_internal(self, api_messages[-1] = multimodal_message else: api_messages.append(multimodal_message) - except ImportError: - self.logger.warning("Media processing not available. Install with: pip install -U abstractcore") - if user_message_text and not replace_last_user: - api_messages.append({"role": "user", "content": user_message_text}) + except ImportError as e: + raise self._media_not_delivered(media, route="OpenAI chat API", cause=e) from e except Exception as e: # Do not silently drop user-supplied media. Fail loudly so callers can # choose an explicit fallback policy (e.g. audio_policy='speech_to_text'). @@ -513,10 +511,8 @@ async def _agenerate_internal(self, else: api_messages.append(multimodal_message) - except ImportError: - self.logger.warning("Media processing not available. Install with: pip install -U abstractcore") - if user_message_text and not replace_last_user: - api_messages.append({"role": "user", "content": user_message_text}) + except ImportError as e: + raise self._media_not_delivered(media, route="OpenAI chat API", cause=e) from e except Exception as e: from ..exceptions import UnsupportedFeatureError diff --git a/abstractcore/providers/streaming.py b/abstractcore/providers/streaming.py index 14ee5c94..7aaa7a05 100644 --- a/abstractcore/providers/streaming.py +++ b/abstractcore/providers/streaming.py @@ -374,20 +374,10 @@ def _collect_json_fence_content(self) -> Tuple[str, List[ToolCall]]: return streamable_content, completed_tools def _offered_tool_name(self, name: Any) -> Optional[str]: - """The offered tool `name` refers to (exact, wire alias or namespaced), or None.""" - if not isinstance(name, str) or not name.strip() or not self.json_fence_tools: - return None - name = name.strip() - if name in self.json_fence_tools: - return name - try: - from ..tools.wire_naming import map_namespaced_tool_name, resolve_wire_tool_name + """The offered tool `name` refers to, or None (the non-streamed parser's rule).""" + from ..tools.parser import offered_tool_name - return resolve_wire_tool_name(name, self.json_fence_tools) or map_namespaced_tool_name( - name, self.json_fence_tools - ) - except Exception: - return None + return offered_tool_name(name, self.json_fence_tools) def _parse_json_fence_tool_calls(self, body: str) -> List[ToolCall]: """Tool calls in a ```json body, or [] when the body is not (only) tool calls. @@ -1022,6 +1012,11 @@ def __init__(self) -> None: self.header = "" self.channel = "" self.recipient: Optional[str] = None + # False when the request offered no tools: a `to=` message is then not a + # call (nothing was offered to call) but the model's text, emitted as + # content (`to= ` + its body), framing tokens removed as + # everywhere else in the stream. + self.tool_calls = True @property def pending(self) -> bool: @@ -1087,6 +1082,9 @@ def feed(self, text: str) -> List[Tuple[str, Any]]: self.header += self.buffer[:idx] self.buffer = self.buffer[idx + len(self.MESSAGE):] self._open_message() + if self.recipient and not self.tool_calls: + events.append(("content", f"to={self.recipient} ")) + self.recipient, self.channel = None, "commentary" continue # body @@ -1410,6 +1408,8 @@ def _unparsed_metadata( def _drain(model: Any) -> Tuple[List[GenerateResponse], Optional[Dict[str, Any]]]: """Chunks owed at the end of the model's output (no finish_reason) + unparsed call.""" owed, tools, unparsed = self.detector.drain() + if not allowed_tool_names: + tools = [] # never a call to a tool the request did not offer out: List[GenerateResponse] = [] if owed: out.append(GenerateResponse(content=_rewritten(owed), model=model)) @@ -1433,6 +1433,8 @@ def _detector_pending() -> bool: ) harmony = self.harmony_splitter + if harmony is not None: + harmony.tool_calls = bool(allowed_tool_names) def _harmony_parts(events: List[Tuple[str, Any]]) -> Tuple[str, str, List[ToolCall], Optional[Dict[str, Any]]]: content = "".join(v for k, v in events if k == "content") @@ -1562,8 +1564,17 @@ def _harmony_chunk(chunk: GenerateResponse, terminal: bool): # terminal attributes ride a separate, final, empty chunk. terminal_attrs: Optional[GenerateResponse] = None - # Process chunk through detector (preserves tool calls for rewriting) - streamable_content, completed_tools = self.detector.process_chunk(chunk.content) + # Process chunk through detector (preserves tool calls for rewriting). + # A tool call exists only for a tool the request OFFERED: without + # tools the model's text is content, markup included, exactly as + # the non-streamed passthrough returns it (a caller that asked for + # tag rewriting still gets its markup rewritten, never a call). + if allowed_tool_names or self.detector.rewrite_tags: + streamable_content, completed_tools = self.detector.process_chunk(chunk.content) + if not allowed_tool_names: + completed_tools = [] + else: + streamable_content, completed_tools = chunk.content, [] if terminal and _detector_pending(): terminal_attrs = GenerateResponse( content="", @@ -1689,6 +1700,8 @@ def _harmony_chunk(chunk: GenerateResponse, terminal: bool): # content arrived after it): settle it now. These chunks are the # stream's last, so they carry the request-scoped metadata. owed, final_tools, unparsed = self.detector.drain() + if not allowed_tool_names: + final_tools = [] # never a call to a tool the request did not offer if owed: yield GenerateResponse( diff --git a/abstractcore/server/app.py b/abstractcore/server/app.py index 59adf0a6..cf8d053b 100644 --- a/abstractcore/server/app.py +++ b/abstractcore/server/app.py @@ -80,7 +80,8 @@ list_available_providers as _list_embedding_providers, list_direct_embedding_providers as _list_direct_embedding_providers, ) -from ..exceptions import AuthenticationError, DecisionModelError, EndpointUnreachableError, GenerationCancelledError, InvalidRequestError, ModelNotFoundError, ProviderAPIError, RateLimitError +from ..exceptions import AuthenticationError, DecisionModelError, EndpointUnreachableError, GenerationCancelledError, InvalidRequestError, ModelNotFoundError, ProviderAPIError, RateLimitError, UnsupportedFeatureError +from ..media.base import MediaProcessingError from ..providers.base import PromptCacheError from ..providers.model_capabilities import modalities_for_model from ..utils.structured_logging import get_logger, configure_logging @@ -3195,13 +3196,16 @@ def delayed_streaming_cleanup(): cleanup_thread = threading.Thread(target=delayed_streaming_cleanup, daemon=True) cleanup_thread.start() + except GenerationCancelledError as e: + # A Stop (the client left, or the host cancelled): nobody is reading, not a failure. + logger.info("Stream cancelled", request_id=request_id, detail=str(e)) except Exception as e: logger.error( "❌ Responses streaming failed", request_id=request_id, error=str(e), ) - error_chunk = {"error": {"message": str(e), "type": "server_error"}} + error_chunk = _stream_error_event(e) yield f"data: {json.dumps(error_chunk)}\n\n" yield "data: [DONE]\n\n" finally: @@ -5054,16 +5058,38 @@ def convert_to_abstractcore_messages(openai_messages: List[ChatMessage]) -> List return messages -def create_syntax_rewriter(target_format: SyntaxFormat, model_name: str) -> ToolCallSyntaxRewriter: - """Create appropriate syntax rewriter for target format.""" +def create_syntax_rewriter( + target_format: SyntaxFormat, model_name: str, tools: Optional[List[Dict[str, Any]]] = None +) -> ToolCallSyntaxRewriter: + """Create appropriate syntax rewriter for target format. + + `tools`: the request's tools; the rewriter reads a JSON object as a tool call only + when it names one of them (no tools: no JSON object is a call).""" if target_format == SyntaxFormat.PASSTHROUGH: - return create_passthrough_rewriter() + rewriter = create_passthrough_rewriter() elif target_format == SyntaxFormat.CODEX: - return create_codex_rewriter(model_name) + rewriter = create_codex_rewriter(model_name) elif target_format == SyntaxFormat.OPENAI: - return create_openai_rewriter(model_name) + rewriter = create_openai_rewriter(model_name) else: - return ToolCallSyntaxRewriter(target_format, model_name=model_name) + rewriter = ToolCallSyntaxRewriter(target_format, model_name=model_name) + rewriter.tool_names = _request_tool_names(tools) + return rewriter + + +def _request_tool_names(tools: Optional[List[Any]]) -> set: + """Tool names of an OpenAI-shaped `tools` list (`{"type": "function", "function": {"name": ...}}` or `{"name": ...}`).""" + names = set() + for tool in tools or []: + if hasattr(tool, "model_dump"): + tool = tool.model_dump() + if not isinstance(tool, dict): + continue + function = tool.get("function") if isinstance(tool.get("function"), dict) else tool + name = function.get("name") + if isinstance(name, str) and name.strip(): + names.add(name.strip()) + return names def _normalize_model_residency_task(task: Optional[str]) -> str: @@ -9222,6 +9248,32 @@ def _endpoint_unreachable_payload(exc: "EndpointUnreachableError") -> Dict[str, } +def _request_refusal_code(exc: BaseException) -> Optional[str]: + """The stable error code of a request this server refuses as the CALLER's (HTTP 400), or None. + + `UnsupportedFeatureError`: the model or route cannot do what the request asks (an + attachment it cannot carry or read, a feature it lacks); `MediaProcessingError` is the + reader's own error when it reaches the server unwrapped. Both get the one code + `unsupported_feature`. Sending the same request again gives the same answer, so it must + never look like a server fault (a 5xx is retried by remote clients).""" + if isinstance(exc, (UnsupportedFeatureError, MediaProcessingError)): + return "unsupported_feature" + return None + + +def _stream_error_event(exc: BaseException) -> Dict[str, Any]: + """The SSE error event for an error raised in a stream (the provider is called on the stream's + own thread, so a refusal arrives here): a request this server refuses keeps its type and code + (`invalid_request_error`, `unsupported_feature`), as a caller's own fault; anything else is the + `server_error` 2.41.0 sent.""" + code = _request_refusal_code(exc) + if code: + return {"error": {"message": str(exc), "type": "invalid_request_error", "code": code}} + if isinstance(exc, InvalidRequestError): + return {"error": {"message": str(exc), "type": "invalid_request_error", "code": "invalid_request"}} + return {"error": {"message": str(exc), "type": "server_error"}} + + def _provider_exception_status(exc: Exception) -> int: if isinstance(exc, EndpointUnreachableError): return 503 @@ -9233,6 +9285,8 @@ def _provider_exception_status(exc: Exception) -> int: return 404 if isinstance(exc, InvalidRequestError): return 400 + if _request_refusal_code(exc): + return 400 if isinstance(exc, ProviderAPIError): return 502 text = str(exc).lower() @@ -10424,7 +10478,7 @@ async def process_chat_completion( messages = convert_to_abstractcore_messages(processed_messages) # Create syntax rewriter - syntax_rewriter = create_syntax_rewriter(target_format, f"{provider}/{model}") + syntax_rewriter = create_syntax_rewriter(target_format, f"{provider}/{model}", request.tools) # Prepare generation parameters gen_kwargs = { @@ -10507,6 +10561,11 @@ async def process_chat_completion( request_id=request_id, cancel_event=cancel_event, loaded_runtime=loaded_runtime, ) if request.stream: + # The stream opens at once and the provider is called on the stream's own thread, + # as on 2.41.0: a shared model that is busy (a lent resident instance serving a + # run) is waited for there, never on a shared pool thread before the response + # starts. A refusal raised by that call arrives as the stream's first event, typed + # `invalid_request_error` / `unsupported_feature` (`_stream_error_event`). stream_content = ( generate_streaming_responses_response( llm, @@ -10645,6 +10704,11 @@ def delayed_cleanup(): if isinstance(e, InvalidRequestError): return JSONResponse(status_code=400, content={"error": { "message": str(e), "type": "invalid_request_error", "code": "invalid_request"}}) + if _request_refusal_code(e): + # This route/model cannot carry the request (an attachment, a feature): the + # caller's 400 with a stable code, never a 500 a remote client retries. + return JSONResponse(status_code=400, content={"error": { + "message": str(e), "type": "invalid_request_error", "code": _request_refusal_code(e)}}) if "llm" in locals() and supports_concurrent_generation(llm): return JSONResponse(status_code=getattr(e, "http_status", 500), content={"error": { "message": str(e), "type": "native_runtime_error", @@ -10958,13 +11022,16 @@ def delayed_streaming_cleanup(): cleanup_thread = threading.Thread(target=delayed_streaming_cleanup, daemon=True) cleanup_thread.start() + except GenerationCancelledError as e: + # A Stop (the client left, or the host cancelled): nobody is reading, not a failure. + logger.info("Stream cancelled", request_id=request_id, detail=str(e)) except Exception as e: logger.error( "❌ Streaming failed", request_id=request_id, error=str(e) ) - error_chunk = {"error": {"message": str(e), "type": "server_error"}} + error_chunk = _stream_error_event(e) yield f"data: {json.dumps(error_chunk)}\n\n" finally: if "provider_chunks" in locals(): diff --git a/abstractcore/structured/handler.py b/abstractcore/structured/handler.py index 3e339588..a093739d 100644 --- a/abstractcore/structured/handler.py +++ b/abstractcore/structured/handler.py @@ -280,7 +280,12 @@ def _has_native_support(self, provider) -> bool: if provider_name == 'HuggingFaceProvider': # Check if it's a GGUF model - these use llama-cpp-python which supports native structured outputs if hasattr(provider, 'model_type') and provider.model_type == 'gguf': - return True + # llama.cpp's grammar applies from the first generated token: behind a template + # whose generation prompt opens a thinking block (LFM3), the JSON is written + # inside that block, Core files it as unfinished reasoning, and the request is + # generated a second time on the prompted lane. One prompted generation instead. + lands_in_thinking = getattr(provider, "gguf_constrained_output_lands_in_thinking", None) + return not (callable(lands_in_thinking) and lands_in_thinking()) # Check if it's a Transformers model with Outlines available if hasattr(provider, 'model_type') and provider.model_type == 'transformers': @@ -290,13 +295,22 @@ def _has_native_support(self, provider) -> bool: except ImportError: return False - # MLXProvider supports native via Outlines + # MLXProvider supports native via Outlines, on its mlx-lm lane only: a model served + # through mlx-vlm (LFM3, Qwen4-Exp, MTP checkpoints, batching) has no Outlines lane, so + # a "native" attempt there was an unconstrained generation without the schema in the + # prompt, and every request generated twice (measured on LFM3-1.7B, 2026-11-30: 3 native + # + 3 prompted generations for 3 requests). if provider_name == 'MLXProvider': try: import outlines - return True except ImportError: return False + # An explicit `structured_output_method="native_outlines"` still goes to the + # provider, which refuses it on the mlx-vlm lane (never a silent switch to prompted). + return ( + getattr(provider, "_mtp_processor", None) is None + or getattr(provider, "structured_output_method", "auto") == "native_outlines" + ) # For other providers, check model capabilities capabilities = getattr(provider, 'model_capabilities', {}) diff --git a/abstractcore/tools/handler.py b/abstractcore/tools/handler.py index d8f7c436..53bd43af 100644 --- a/abstractcore/tools/handler.py +++ b/abstractcore/tools/handler.py @@ -6,6 +6,7 @@ """ import json +import re import warnings from typing import List, Dict, Any, Optional, Union, Callable @@ -55,6 +56,25 @@ def merge_tools_into_system( return tool_prompt + +# A template renders tool definitions when `tools` is used as a VARIABLE inside +# a Jinja statement or expression -- not when the word appears in its text, a +# comment or a string literal. +_JINJA_TAG = re.compile(r"\{\{.*?\}\}|\{%.*?%\}", re.S) +_JINJA_COMMENT = re.compile(r"\{#.*?#\}", re.S) +_JINJA_STRING = re.compile(r"'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"", re.S) +_TOOLS_NAME = re.compile(r"\btools\b") + + +def chat_template_renders_tools(source: str) -> bool: + """True when a Jinja chat template renders the `tools` it is given (MLX and GGUF + lanes then hand it `tools=` instead of AbstractCore's prompted tool block).""" + source = _JINJA_COMMENT.sub("", source or "") + return any( + _TOOLS_NAME.search(_JINJA_STRING.sub("", tag.group(0))) for tag in _JINJA_TAG.finditer(source) + ) + + class UniversalToolHandler: """ Universal tool handler that works with all models. @@ -257,7 +277,8 @@ def prepare_tools_for_native( def parse_response( self, response: Union[str, Dict[str, Any]], - mode: str = "prompted" + mode: str = "prompted", + tool_names: Optional[Any] = None, ) -> ToolCallResponse: """ Parse model response for tool calls. @@ -265,6 +286,10 @@ def parse_response( Args: response: Model response (string for prompted, dict for native) mode: Response mode ("native" or "prompted") + tool_names: Names of the tools offered on this request (prompted + responses): a call written as a JSON object counts only when it + names one of them (see `parser.parse_tool_calls`). ``None``: not + known by the caller. Returns: ToolCallResponse with content and tool calls @@ -272,11 +297,11 @@ def parse_response( if mode == "native" and isinstance(response, dict): return self._parse_native_response(response) elif mode == "prompted" and isinstance(response, str): - return self._parse_prompted_response(response) + return self._parse_prompted_response(response, tool_names=tool_names) else: # Fallback - try to handle whatever we get if isinstance(response, str): - return self._parse_prompted_response(response) + return self._parse_prompted_response(response, tool_names=tool_names) else: return self._parse_native_response(response) @@ -499,10 +524,10 @@ def _parse_native_response(self, response) -> ToolCallResponse: raw_response=response ) - def _parse_prompted_response(self, response: str) -> ToolCallResponse: + def _parse_prompted_response(self, response: str, tool_names: Optional[Any] = None) -> ToolCallResponse: """Parse prompted response format.""" # Use architecture-specific parsing - tool_calls = parse_tool_calls(response, self.model_name) + tool_calls = parse_tool_calls(response, self.model_name, tool_names=tool_names) # Extract content (everything that's not a tool call) using shared cleaning function from .parser import clean_tool_syntax diff --git a/abstractcore/tools/parser.py b/abstractcore/tools/parser.py index 5edb43e7..9fe8fc54 100644 --- a/abstractcore/tools/parser.py +++ b/abstractcore/tools/parser.py @@ -5,10 +5,11 @@ responses based on their architecture. """ -import re -import json import ast -from typing import List, Optional, Dict, Any +import functools +import json +import re +from typing import Any, Dict, Iterable, List, Optional from enum import Enum from .core import ToolCall, ToolDefinition @@ -158,13 +159,42 @@ def detect_unparsed_tool_intent(response: str) -> bool: return has_function and has_parameter -def parse_tool_calls(response: str, model_name: Optional[str] = None) -> List[ToolCall]: +def offered_tool_name(name: Any, tool_names: Optional[Iterable[str]]) -> Optional[str]: + """The offered tool `name` refers to (exact, wire alias or namespaced), or None. + + The one rule for a tool call written as a JSON object (an envelope-less object + or a ```json block), streamed or not: it is a call only when it names a tool + offered on this request. Without that, a JSON ANSWER that happens to carry a + "name" key (`{"name": "Maria Lopez", ...}`) would become a call. + """ + if not isinstance(name, str) or not name.strip() or not tool_names: + return None + name = name.strip() + names = [n for n in tool_names if isinstance(n, str) and n] + if name in names: + return name + from .wire_naming import map_namespaced_tool_name, resolve_wire_tool_name + + return resolve_wire_tool_name(name, names) or map_namespaced_tool_name(name, names) + + +def parse_tool_calls( + response: str, + model_name: Optional[str] = None, + tool_names: Optional[Iterable[str]] = None, +) -> List[ToolCall]: """ Parse tool calls from response. Args: response: Model response containing tool calls model_name: Optional model name for architecture detection + tool_names: Names of the tools offered on this request. A call written as + a JSON object (no tool-call envelope, or a ```json block) is kept only + when it names one of them; with an empty collection no JSON object is + a call. ``None`` means the caller does not know the offered tools: + JSON objects are then read as before (any name), and the caller must + check the names itself. Returns: List of parsed tool calls @@ -186,11 +216,23 @@ def parse_tool_calls(response: str, model_name: Optional[str] = None) -> List[To } parser = parsers.get(tool_format, _parse_any_format) - calls = parser(response) + # JSON objects are read by `_parse_raw_json` alone (as the format's parser or + # in the generic fallback); it keeps only calls to an offered tool. Where a bare + # JSON object IS the declared call syntax (`json` families, unknown models), an + # object with the call's shape naming no offered tool is still returned, so the + # caller reports it as a call to an unavailable tool (`tool_call_error`) instead + # of taking it for the answer. + # With no tools offered nothing is a call: an empty roster keeps no call shape either. + json_declared = (tool_format == ToolFormat.RAW_JSON or not model_name) and bool(tool_names) + json_kwargs = {"tool_names": tool_names, "keep_call_shapes": json_declared} + if parser in (_parse_raw_json, _parse_any_format): + calls = parser(response, **json_kwargs) + else: + calls = parser(response) # Fallback: some models emit tool syntax that doesn't match their expected architecture format # (e.g., `tool: [name]: {...}` or partial tags). Try the generic parser when needed. if not calls and parser is not _parse_any_format: - calls = _parse_any_format(response) + calls = _parse_any_format(response, **json_kwargs) if calls: from .arg_canonicalizer import canonicalize_tool_arguments @@ -1050,13 +1092,29 @@ def _parse_tool_code(response: str) -> List[ToolCall]: return tool_calls -def _parse_raw_json(response: str) -> List[ToolCall]: - """Parse raw JSON tool calls.""" +def _parse_raw_json( + response: str, *, tool_names: Optional[Iterable[str]] = None, keep_call_shapes: bool = False +) -> List[ToolCall]: + """Parse tool calls written as JSON objects (envelope-less, or in a ```json block). + + With `tool_names` (the request's offered tools), an object is a call only when + it names one of them (`offered_tool_name`, the rule the stream applies to + ```json blocks); anything else is the model's answer. `None`: any name (a + caller that does not know the offered tools). `keep_call_shapes`: also keep an + object with the call's shape (`name` plus `arguments` or `parameters`) naming + no offered tool, for a model whose declared syntax is that object. + """ tool_calls = [] + def _offered(tool_data: Dict[str, Any]) -> bool: + if tool_names is None or offered_tool_name(tool_data.get("name"), tool_names) is not None: + return True + return keep_call_shapes and ("arguments" in tool_data or "parameters" in tool_data) + # Try to find JSON objects that look like tool calls - handle nested objects json_pattern = r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*["\']name["\'][^{}]*(?:\{[^{}]*\}[^{}]*)*\}' + read_spans = [] for match in re.finditer(json_pattern, response): try: json_str = match.group(0) @@ -1064,13 +1122,14 @@ def _parse_raw_json(response: str) -> List[ToolCall]: if not isinstance(tool_data, dict): continue - if "name" in tool_data: + if "name" in tool_data and _offered(tool_data): tool_call = ToolCall( name=tool_data.get("name", ""), arguments=tool_data.get("arguments", tool_data.get("parameters", {})), call_id=tool_data.get("id") ) tool_calls.append(tool_call) + read_spans.append(match.span()) except json.JSONDecodeError: continue @@ -1078,13 +1137,16 @@ def _parse_raw_json(response: str) -> List[ToolCall]: # Also try to parse JSON from code blocks code_block_pattern = r'```(?:json|tool_code)?\s*\n(\{.*?\})\s*\n```' for match in re.finditer(code_block_pattern, response, re.DOTALL): + start, end = match.span(1) + if any(s <= start < e or start <= s < end for s, e in read_spans): + continue # the object inside this block was read above: one block, one call try: json_str = match.group(1).strip() tool_data = _loads_dict_like(json_str) if not isinstance(tool_data, dict): continue - if "name" in tool_data: + if "name" in tool_data and _offered(tool_data): tool_call = ToolCall( name=tool_data.get("name", ""), arguments=tool_data.get("arguments", tool_data.get("parameters", {})), @@ -1332,8 +1394,12 @@ def _balance_braces(text: str) -> str: return tool_calls -def _parse_any_format(response: str) -> List[ToolCall]: - """Try all parsing formats with comprehensive fallbacks.""" +def _parse_any_format( + response: str, *, tool_names: Optional[Iterable[str]] = None, keep_call_shapes: bool = False +) -> List[ToolCall]: + """Try all parsing formats with comprehensive fallbacks. + + `tool_names`: see `_parse_raw_json` (JSON objects naming no offered tool are not calls).""" # SANITIZE FIRST: Fix malformed tags before trying any parser response = _sanitize_tool_call_tags(response) @@ -1347,7 +1413,7 @@ def _parse_any_format(response: str) -> List[ToolCall]: _parse_tool_code, _parse_harmony_tool_prefix, _parse_bracket_tool_prefix, - _parse_raw_json + functools.partial(_parse_raw_json, tool_names=tool_names, keep_call_shapes=keep_call_shapes), ] for parser in parsers: @@ -1355,7 +1421,7 @@ def _parse_any_format(response: str) -> List[ToolCall]: found_calls = parser(response) tool_calls.extend(found_calls) except Exception as e: - logger.debug(f"Parser {parser.__name__} failed: {e}") + logger.debug(f"Parser {getattr(parser, '__name__', None) or getattr(parser, 'func', parser).__name__} failed: {e}") # Additional fallback: Look for Python code blocks with common tool names if not tool_calls: diff --git a/abstractcore/tools/syntax_rewriter.py b/abstractcore/tools/syntax_rewriter.py index 08d993dd..e4684b00 100644 --- a/abstractcore/tools/syntax_rewriter.py +++ b/abstractcore/tools/syntax_rewriter.py @@ -59,7 +59,8 @@ def __init__( self, target_format: Union[str, SyntaxFormat], custom_config: Optional[CustomFormatConfig] = None, - model_name: Optional[str] = None + model_name: Optional[str] = None, + tool_names: Optional[Iterable[str]] = None, ): """ Initialize the syntax rewriter. @@ -68,6 +69,9 @@ def __init__( target_format: Target format to convert to custom_config: Configuration for custom formats model_name: Model name for format auto-detection + tool_names: Names of the tools offered on the request whose content is + rewritten: a JSON object is a tool call only when it names one of + them (`parser.parse_tool_calls`). ``None``: not known. """ if isinstance(target_format, str): try: @@ -79,6 +83,7 @@ def __init__( self.custom_config = custom_config self.model_name = model_name + self.tool_names = None if tool_names is None else {str(n) for n in tool_names if n} # Validate custom format configuration if self.target_format == SyntaxFormat.CUSTOM and not custom_config: @@ -110,7 +115,7 @@ def rewrite_content( # Detect tool calls if not provided if detected_tool_calls is None: - detected_tool_calls = parse_tool_calls(content, self.model_name) + detected_tool_calls = parse_tool_calls(content, self.model_name, tool_names=self.tool_names) logger.debug(f"Detected {len(detected_tool_calls)} tool calls in content") else: detected_tool_calls = list(self._coerce_tool_calls(detected_tool_calls)) diff --git a/abstractcore/utils/cli.py b/abstractcore/utils/cli.py index 29438383..f70204ff 100644 --- a/abstractcore/utils/cli.py +++ b/abstractcore/utils/cli.py @@ -2487,7 +2487,14 @@ def _parse_and_strip_tool_calls(self, content: str): # different formats regardless of their architecture try: from ..tools.parser import _parse_any_format - detected_calls = _parse_any_format(content) + offered = set() + for tool in getattr(self.session, "tools", None) or []: + definition = getattr(tool, "_tool_definition", tool) + name = getattr(definition, "name", None) or getattr(tool, "__name__", None) + if isinstance(name, str) and name: + offered.add(name) + # A JSON object is a call only when it names one of the session's tools. + detected_calls = _parse_any_format(content, tool_names=offered) if not detected_calls: return content, [] diff --git a/changelog.d/lfm3-text.md b/changelog.d/lfm3-text.md new file mode 100644 index 00000000..1bb4272b --- /dev/null +++ b/changelog.d/lfm3-text.md @@ -0,0 +1,97 @@ +### Added + +- **LFM3-1.7B runs on MLX and GGUF** (`providers/mlx_provider.py`, `providers/huggingface_provider.py`, + `assets/`). `create_llm("mlx", model="LiquidAI/LFM3-1.7B-MLX-4bit")` loads it through mlx-vlm, because no + mlx-lm release has this architecture yet. The lane is chosen from the checkpoint's `config.json` `model_type` + (never its name), only for a type the registry declares verified there (`mlx_vlm_model_types` in + `architecture_formats.json`: `lfm3`, from mlx-vlm 0.7.12), and it moves back to mlx-lm by itself once mlx-lm + ships the module. Any other type mlx-lm lacks keeps mlx-lm's own error. With mlx-vlm missing or older than the + declared version (0.7.11 has the module but leaks the reasoning into the answer), the load says which version it + needs, which one is installed and what to install. The GGUF (`LiquidAI/LFM3-1.7B-GGUF:Q4_K_M` on the + `huggingface` provider) needs llama-cpp-python 0.3.38 or newer; with an older one the load stops at once and + says which release can load it. Chat, streaming, stopping, two tool calls in one reply, structured output, + thinking on and off, long documents and multi-turn sessions with prompt-cache reuse were checked on real + weights on both. + +### Changed + +- **Attachments that cannot reach the model are refused instead of being dropped or replaced** (all providers, + `media/`, `providers/base.py`). Callers must now catch `UnsupportedFeatureError` (HTTP 400 through + AbstractCore's server) where they used to get a text-only answer, and act on its message, which names the model, + the route, each attachment and what to do next: + - a picture, recording or document that could not be encoded: several providers logged a warning and sent the + text alone (the OpenAI-compatible provider for LM Studio and others, Anthropic, Ollama, the transformers text + lane), and the GGUF lane wrote image markers with no picture behind them (it loads no vision projector: send + images through the MLX, LM Studio or Ollama provider); + - a file that cannot be read (`media/auto_handler.py`): a corrupt PDF or DOCX, or one whose reader is not + installed, reached every model as `[Document: name]`, and a binary file of a type with no reader (`.zip`, + `.bin`, `.doc`) as its raw bytes. The reader's own error now comes back with the file's name and kind (attach + a valid copy, or a text or PDF version); + - a voice note on a route with no audio transport (Ollama, LM Studio, the GGUF lane, the MLX native lane): with + `audio_policy="auto"` the configured speech-to-text (`input.voice`) now serves it, also for a model the + registry says hears; without one the error names `input.voice` and `audio_policy="speech_to_text"`. + MLX keeps reporting what it could not carry in `media_dropped`. Ollama now sends an attachment on a plain prompt + too (it used the route that ignores attachments), and an Ollama or LM Studio vision model given a picture and a + document receives both (the document's text in the message). +- **Through AbstractCore's server a refused request is the caller's error, never a server fault** + (`server/app.py`): a plain request gets HTTP 400 with `type` `invalid_request_error` and code + `unsupported_feature`, where it used to get a 500 that remote clients retried; in process the error keeps its type + (`providers/base.py` wrapped it into a `ProviderAPIError`, which was retried). A streamed request opens at once as + before (the model is called on the stream's own thread, where a busy shared model is waited for); its refusal + arrives as the stream's error event, typed `invalid_request_error` with the code `unsupported_feature` (an invalid + request: `invalid_request_error` / `invalid_request`; any other error keeps the `server_error` event). + AbstractCore's own OpenAI-compatible provider raises `UnsupportedFeatureError`, not retried, for that event as for + the 400 (and `InvalidRequestError` for the invalid-request event); another server's events are read as before. +- **A request stopped while it waited for a busy shared Hugging Face model never starts its generation** + (`providers/huggingface_provider.py`), streamed or not: when an instance serves another run (a host pool, the + server lending a resident model), a caller that stopped in the meantime (its cancel event set, e.g. a client that + left) gets `GenerationCancelledError` instead of a generation started once the model is free. +- **The `abstractcore[apple]` setting needs mlx-vlm 0.7.12 or newer** (still below 0.8.0): the first release + that loads LFM3 without leaking its reasoning into the answer. It brings mlx 0.32.4 and transformers 5.14 or + newer with it. +- **LFM3 registry entries follow the model's own files.** LFM3-1.7B uses the card's sampling (temperature 0.1, + top_k 50, repetition penalty 1.1), allows several tool calls per reply, and switches thinking off with the + template's own `` (it was Qwen's `\n\n\n\n`, which the model was not trained on). + Thinking control is now declared per model, not for the whole LFM3 family (the Audio model has no switch; Omni's is off by default). The + download catalog gives the real sizes, and the memory estimate counts only the 6 full-attention layers + (12,288 bytes per token). +- **The LFM3-1.7B GGUF gets its template's own tool block** (`providers/huggingface_provider.py`). The tools reach the + model exactly as its template writes them (`` JSON lines) instead of AbstractCore's prompted instructions, + as the MLX provider already did, and tool results (`tool` turns) stay on the lane that honours `thinking="off"`. + This is opt-in per model in the registry (`gguf_template_tools` in `model_capabilities.json`, today + LFM3-1.7B only, the model it was run on); every other GGUF keeps the 2.41.0 behaviour. For LFM3 the GGUF context is built with flash attention and + a window-sized sliding-attention cache (at 32K tokens: 320 MiB of cache and 880 MiB of compute buffer less). + The model's chat template is compiled once, not at every render (about 24 ms per render for LFM3's template). +- **The GGUF lane applies the model card's `top_k` and repetition penalty on every request**, not only on + prompt-cached ones; the MLX lane applies the card's repetition penalty when it runs through mlx-vlm. + +### Fixed + +- **A JSON answer is not a tool call** (`tools/parser.py`, `providers/base.py`, `providers/streaming.py`). A + structured answer such as `{"name": "Maria Lopez", "age": 34}` was read as a call to a tool named "Maria + Lopez" and reported as an unavailable tool. A call written as a JSON object, fenced or not, now counts only when + it names one of the request's tools, for every model, streamed or not (`parse_tool_calls(..., tool_names=)`; + without `tool_names` the parser reads any name, as before). Where a bare JSON object is the declared call syntax + (JSON-format families such as Mistral, and unknown models), an object with a call's shape (`name` plus + `arguments`) naming no offered tool is still reported as a call to an unavailable tool. A streamed reply produces + tool calls only when the request offered tools (GPT-OSS Harmony included). A fenced JSON call on a JSON-format + model is one call, not two. +- **Structured output on an MLX model served through mlx-vlm generates once** (`structured/handler.py`). Outlines + constrains only the mlx-lm lane; on the mlx-vlm lane (LFM3, Qwen4-Exp, MTP checkpoints, batching) the "native" + attempt was an unconstrained generation without the schema, so every request ran twice. It now goes straight to + the prompted lane, which gives the model the schema. An explicit `structured_output_method="native_outlines"` + there is refused, as before, instead of turning into prompted output in silence. +- **GGUF structured output generates once.** The schema was sent in the OpenAI `json_schema` shape, which + llama-cpp-python ignores, so the "native" attempt was unconstrained and a request could run twice; it is now + sent as `{"type": "json_object", "schema": ...}`, from which llama.cpp builds a grammar. For a GGUF whose + template opens a thinking block in the generation prompt (LFM3), the grammar would put the JSON inside that + block, so those models take the prompted lane directly: one generation, and like any other request it honours + `thinking="off"` (LFM3-1.7B: 0.4 s instead of 3.4-5.4 s with its default reasoning). +- **Thinking switched off no longer leaves a stray `` in LFM3's streamed answer.** LFM3-1.7B and LFM3-VL + (registry `thinking_off_leaks_close_tag`) sometimes reason in the answer and then close a block they were never + given; that one closing tag is removed from the stream and counted in `metadata["thinking_stray_close_tags"]`. + Every other model's answer keeps every character. Without streaming, the text before that tag is reported as + reasoning. +- **GGUF streams its first words at once** (`providers/huggingface_provider.py`). The lane that serves + prompt-cached and thinking-controlled requests held its text back until 160 characters were decoded (measured on + LFM3-1.7B: first text after 0.39 s, now 0.015-0.045 s). diff --git a/docs/installation.md b/docs/installation.md index d1fd96d6..4e11e32d 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -140,9 +140,14 @@ For Apple silicon Macs (macOS 14 or newer, Python 3.10 or newer; 3.11 or newer e local voice engine). Adds, on top of light: - **MLX provider**: text and image input for MLX checkpoints (mlx, mlx-lm, mlx-vlm), with - native structured output (outlines). + native structured output (outlines). LFM3 (the `model_type` `lfm3` in its `config.json`), which + mlx-lm does not ship, loads through mlx-vlm 0.7.12 or newer; with an older mlx-vlm the load says + so and what to install. Only the architectures the registry declares verified on that lane take + it (`mlx_vlm_model_types` in `architecture_formats.json`); any other one keeps mlx-lm's own error. - **HuggingFace provider**: transformers and GGUF models through llama.cpp, and local embedding - models (sentence-transformers) for `EmbeddingManager`. + models (sentence-transformers) for `EmbeddingManager`. A GGUF whose architecture the installed + llama.cpp does not know fails at load with the release that knows it (LFM3: llama-cpp-python + 0.3.38 or newer). - **Local voice**: speech output and speech input engines (AbstractVoice's Apple engines, OmniVoice). - **Local image and video**: AbstractVision's Apple engines (MLX-Gen, Diffusers, diff --git a/docs/media-handling-system.md b/docs/media-handling-system.md index 056be82a..c15f536d 100644 --- a/docs/media-handling-system.md +++ b/docs/media-handling-system.md @@ -195,7 +195,7 @@ except PDFProcessingError: - **Formats**: common `audio/*` types (WAV, MP3, M4A, …) as attachments via `media=[...]` - **Default behavior**: `audio_policy="native_only"` (fails loudly unless the model supports native audio input) - **Speech-to-text**: `audio_policy="speech_to_text"` runs STT via the capability plugin layer (`llm.audio.transcribe(...)`; typically install `abstractvoice`) and injects a transcript into the main request -- **Auto**: `audio_policy="auto"` uses native audio when supported, otherwise STT when configured, otherwise errors +- **Auto**: `audio_policy="auto"` uses native audio when the model hears AND the provider carries audio to it (no AbstractCore provider does today: Ollama, LM Studio, the GGUF lane and the MLX native lane have no audio transport), otherwise STT when configured, otherwise an error naming `input.voice` and `audio_policy="speech_to_text"` - **Reserved**: `audio_policy="caption"` is not configured in v0 (must error; non-speech audio analysis needs an explicit capability) Transparency: @@ -289,6 +289,25 @@ resp.metadata["media_delivered"] `vision_family_unsupported`, `vision_multi_image_unsupported` or `media_processing_unavailable`. - Streamed responses carry the same record; read it from the final chunk as you would usage. +An attachment a provider cannot carry to the model is an error, never a text-only request: the +provider raises `UnsupportedFeatureError` naming the model, the route and each attachment's kind +(a missing file, an encoding failure, audio on a route that takes none, an image on the GGUF +lane, which loads no vision projector yet). MLX reports what it could not carry in +`media_dropped` and tells the model, as described above. + +A file that cannot be read is refused the same way, with the reader's own cause, never sent as a +`[Document: name]` placeholder: a corrupt PDF or DOCX ("Cannot read document file 'x.pdf': ..."), a +PDF or Office file whose reader is not installed (the error says what to install), and a binary +file of a type AbstractCore has no reader for (`.zip`, `.bin`...). Text files of any extension are +read as text. Through AbstractCore's server a plain request with such a refusal gets HTTP 400 +`invalid_request_error` with the code `unsupported_feature`, so a client never retries it as a server +fault. A streamed +request opens at once; its refusal arrives as the stream's error event with the same type and +code, and AbstractCore's OpenAI-compatible provider raises `UnsupportedFeatureError` for it. + +An Ollama or LM Studio vision model given a picture and a document receives both: the picture as +an image, the document's text in the message, as for a text-only model. + For a single answer, use the shared helper: ```python diff --git a/docs/native-mlx-runtime.md b/docs/native-mlx-runtime.md index a2f3ea27..9ec9b282 100644 --- a/docs/native-mlx-runtime.md +++ b/docs/native-mlx-runtime.md @@ -15,7 +15,7 @@ results and the thinking opener match what the model was trained on; see For a source checkout, install the Apple provider stack with `pip install -e ".[apple]"`. Released packages use `pip install -U "abstractcore[apple]"`; see the [changelog](../CHANGELOG.md) for release availability. -The native runtime requires MLX ≥0.32.2, mlx-lm ≥0.31.3 and mlx-vlm ≥0.7.1,<0.8.0. +The native runtime requires MLX ≥0.32.2, mlx-lm ≥0.31.3 and mlx-vlm ≥0.7.12,<0.8.0. Download target and head weights explicitly before loading; AbstractCore's model cache is offline-first. See [model downloads](api.md#model-downloads-download_model-optional). diff --git a/docs/reasoning-control.md b/docs/reasoning-control.md index 9cbb18c1..92780e8c 100644 --- a/docs/reasoning-control.md +++ b/docs/reasoning-control.md @@ -100,6 +100,7 @@ table shows what reaches the server for `thinking="on"` / `"off"` / `"high"`. | Qwen3.5 / 3.6, Laguna, Qwen3 (`template_kwarg`, assistant prefill; no levels) | `reasoning_effort` `medium` / `none` / `medium` (reported as `on`) | `chat_template_kwargs.enable_thinking` true / false / true, plus `thinking_token_budget` for a level (reported as `on`) | template switch; MLX also the no-think prefill | | Qwen3.8 (`template_kwarg`, `effort_template_kwarg`, levels `low\|medium\|xhigh`) | `reasoning_effort` `medium` / `none` / `medium` (nearest level, warned) | `enable_thinking` plus `reasoning_effort` template kwarg | switch plus the template's effort sentence | | HY V3 / Hy-Memory (effort switch, levels `low\|high`) | `reasoning_effort` `high` / `none` / `high` | `chat_template_kwargs.reasoning_effort` `high` / `no_think` / `high` | the effort variable `no_think\|low\|high` | +| LFM3 1.7B and VL 2B (`template_kwarg`, prefill ``; on by default) | `reasoning_effort` `medium` / `none` / `medium` (reported as `on`) | `chat_template_kwargs.enable_thinking` | template switch (GGUF: the model's own template, rendered by AbstractCore) | | Gemma 4, Nemotron, GLM-5, LongCat (`template_kwarg` only) | `reasoning_effort` `medium` / `none` / `medium` (reported as `on`) | `chat_template_kwargs.enable_thinking`; Nemotron `low_effort` for `low`/`minimal` | HF: template switch; MLX: not mapped (warns) | | DeepSeek V4, Mistral Small 4 (levels incl. `none`, no template surface) | `reasoning_effort` `high` / `none` / `high` | `reasoning_effort` | not mapped (warns) | | GPT-OSS (Harmony, levels `low\|medium\|high`) | `Reasoning:` system line plus `reasoning_effort` | `reasoning_effort` (vLLM builds the Harmony system message from it) plus the system line | `Reasoning:` system line | diff --git a/docs/speculative-decoding.md b/docs/speculative-decoding.md index 01d0f35b..1f3c3a74 100644 --- a/docs/speculative-decoding.md +++ b/docs/speculative-decoding.md @@ -30,7 +30,7 @@ print(r.metadata["speculation"]) ## Qwen3.8-Flash-Next on native MLX -Install `abstractcore[apple]` with MLX ≥0.32.2 and mlx-vlm ≥0.7.1. The `mlx` +Install `abstractcore[apple]` with MLX ≥0.32.2 and mlx-vlm ≥0.7.12. The `mlx` provider executes locally in your Python process; no HTTP endpoint or oMLX installation is used. diff --git a/docs/tool-calling.md b/docs/tool-calling.md index 557e0d44..1186cee4 100644 --- a/docs/tool-calling.md +++ b/docs/tool-calling.md @@ -668,6 +668,17 @@ The body can also be `{"tool_calls": [...]}`, a list of calls, or the OpenAI text: a JSON answer, a block naming a tool the request did not offer, and every ```` ```json ```` block when the request has no tools. +A tool call exists only when the request offered tools: without `tools`, any tool-call markup the +model writes stays in `content`, streamed or not. A call written as a JSON object, fenced or not, +counts only when it names one of the request's tools, for every model, streamed or not: a JSON +answer such as `{"name": "Maria Lopez", "age": 34}` is the answer, with no warning. For models whose +declared call syntax is a bare JSON object (JSON-format families such as Mistral, and unknown +models), an object with a call's shape (`name` plus `arguments` or `parameters`) naming no offered +tool is reported as a call to an unavailable tool (`metadata["tool_call_error"]`). One difference +remains: without streaming, an envelope-less object naming an offered tool is also a call (the +fenced block's text then stays in `content` beside it); streamed, only the fenced block is read, +since holding back every `{` of an answer while tools are offered would stall streamed code. + Native tool calls work the same way. OpenAI and OpenAI-compatible servers (vLLM, LM Studio, OpenRouter, Portkey) stream a call as a named first delta followed by fragments of its arguments. AbstractCore joins the fragments and delivers each call once, complete, on the chunk that carries @@ -708,7 +719,8 @@ chunk.metadata["unparsed_tool_call"] GPT-OSS models write Harmony transcripts. When the backend passes the raw transcript through, the stream is split by channel as it arrives: `final` is text, `analysis` is reasoning (`chunk.metadata["reasoning_delta"]`), `commentary` without a recipient is text, and a message -addressed `to=functions.NAME` is a tool call. The framing tokens (`<|channel|>`, `<|message|>`, +addressed `to=functions.NAME` is a tool call when the request offered tools (without tools it is +text: `to=functions.NAME {...}`). The framing tokens (`<|channel|>`, `<|message|>`, `<|end|>`, ...) never appear in the text. Ollama, LM Studio and vLLM usually split Harmony on the server, in which case the text and reasoning already arrive separately. diff --git a/docs/vision-capabilities.md b/docs/vision-capabilities.md index 7f11bde3..b5667bf4 100644 --- a/docs/vision-capabilities.md +++ b/docs/vision-capabilities.md @@ -52,7 +52,7 @@ abstractcore --set-video-sampling-strategy keyframes Qwen3.8-Flash-Next (`qwen4_exp`) uses the full native MLX vision graph, including image input with embedded MTP and selectable draft depth. It requires MLX ≥0.32.2 -and mlx-vlm ≥0.7.1; see [native MTP setup](speculative-decoding.md#qwen38-flash-next-on-native-mlx). +and mlx-vlm ≥0.7.12; see [native MTP setup](speculative-decoding.md#qwen38-flash-next-on-native-mlx). Its native path accepts multiple images and records measured expanded image tokens in `metadata["media_delivered"]`. Qwen3.8-27B also uses native vision when loaded with its separate MTP head or the scheduled native runtime. See diff --git a/llms-full.txt b/llms-full.txt index 6f213592..938d1028 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -1491,9 +1491,14 @@ For Apple silicon Macs (macOS 14 or newer, Python 3.10 or newer; 3.11 or newer e local voice engine). Adds, on top of light: - **MLX provider**: text and image input for MLX checkpoints (mlx, mlx-lm, mlx-vlm), with - native structured output (outlines). + native structured output (outlines). LFM3 (the `model_type` `lfm3` in its `config.json`), which + mlx-lm does not ship, loads through mlx-vlm 0.7.12 or newer; with an older mlx-vlm the load says + so and what to install. Only the architectures the registry declares verified on that lane take + it (`mlx_vlm_model_types` in `architecture_formats.json`); any other one keeps mlx-lm's own error. - **HuggingFace provider**: transformers and GGUF models through llama.cpp, and local embedding - models (sentence-transformers) for `EmbeddingManager`. + models (sentence-transformers) for `EmbeddingManager`. A GGUF whose architecture the installed + llama.cpp does not know fails at load with the release that knows it (LFM3: llama-cpp-python + 0.3.38 or newer). - **Local voice**: speech output and speech input engines (AbstractVoice's Apple engines, OmniVoice). - **Local image and video**: AbstractVision's Apple engines (MLX-Gen, Diffusers, @@ -7668,6 +7673,17 @@ The body can also be `{"tool_calls": [...]}`, a list of calls, or the OpenAI text: a JSON answer, a block naming a tool the request did not offer, and every ```` ```json ```` block when the request has no tools. +A tool call exists only when the request offered tools: without `tools`, any tool-call markup the +model writes stays in `content`, streamed or not. A call written as a JSON object, fenced or not, +counts only when it names one of the request's tools, for every model, streamed or not: a JSON +answer such as `{"name": "Maria Lopez", "age": 34}` is the answer, with no warning. For models whose +declared call syntax is a bare JSON object (JSON-format families such as Mistral, and unknown +models), an object with a call's shape (`name` plus `arguments` or `parameters`) naming no offered +tool is reported as a call to an unavailable tool (`metadata["tool_call_error"]`). One difference +remains: without streaming, an envelope-less object naming an offered tool is also a call (the +fenced block's text then stays in `content` beside it); streamed, only the fenced block is read, +since holding back every `{` of an answer while tools are offered would stall streamed code. + Native tool calls work the same way. OpenAI and OpenAI-compatible servers (vLLM, LM Studio, OpenRouter, Portkey) stream a call as a named first delta followed by fragments of its arguments. AbstractCore joins the fragments and delivers each call once, complete, on the chunk that carries @@ -7708,7 +7724,8 @@ chunk.metadata["unparsed_tool_call"] GPT-OSS models write Harmony transcripts. When the backend passes the raw transcript through, the stream is split by channel as it arrives: `final` is text, `analysis` is reasoning (`chunk.metadata["reasoning_delta"]`), `commentary` without a recipient is text, and a message -addressed `to=functions.NAME` is a tool call. The framing tokens (`<|channel|>`, `<|message|>`, +addressed `to=functions.NAME` is a tool call when the request offered tools (without tools it is +text: `to=functions.NAME {...}`). The framing tokens (`<|channel|>`, `<|message|>`, `<|end|>`, ...) never appear in the text. Ollama, LM Studio and vLLM usually split Harmony on the server, in which case the text and reasoning already arrive separately. @@ -13785,7 +13802,7 @@ print(r.metadata["speculation"]) ## Qwen3.8-Flash-Next on native MLX -Install `abstractcore[apple]` with MLX ≥0.32.2 and mlx-vlm ≥0.7.1. The `mlx` +Install `abstractcore[apple]` with MLX ≥0.32.2 and mlx-vlm ≥0.7.12. The `mlx` provider executes locally in your Python process; no HTTP endpoint or oMLX installation is used. @@ -14206,7 +14223,7 @@ results and the thinking opener match what the model was trained on; see For a source checkout, install the Apple provider stack with `pip install -e ".[apple]"`. Released packages use `pip install -U "abstractcore[apple]"`; see the [changelog](CHANGELOG.md) for release availability. -The native runtime requires MLX ≥0.32.2, mlx-lm ≥0.31.3 and mlx-vlm ≥0.7.1,<0.8.0. +The native runtime requires MLX ≥0.32.2, mlx-lm ≥0.31.3 and mlx-vlm ≥0.7.12,<0.8.0. Download target and head weights explicitly before loading; AbstractCore's model cache is offline-first. See [model downloads](docs/api.md#model-downloads-download_model-optional). @@ -14847,6 +14864,7 @@ table shows what reaches the server for `thinking="on"` / `"off"` / `"high"`. | Qwen3.5 / 3.6, Laguna, Qwen3 (`template_kwarg`, assistant prefill; no levels) | `reasoning_effort` `medium` / `none` / `medium` (reported as `on`) | `chat_template_kwargs.enable_thinking` true / false / true, plus `thinking_token_budget` for a level (reported as `on`) | template switch; MLX also the no-think prefill | | Qwen3.8 (`template_kwarg`, `effort_template_kwarg`, levels `low\|medium\|xhigh`) | `reasoning_effort` `medium` / `none` / `medium` (nearest level, warned) | `enable_thinking` plus `reasoning_effort` template kwarg | switch plus the template's effort sentence | | HY V3 / Hy-Memory (effort switch, levels `low\|high`) | `reasoning_effort` `high` / `none` / `high` | `chat_template_kwargs.reasoning_effort` `high` / `no_think` / `high` | the effort variable `no_think\|low\|high` | +| LFM3 1.7B and VL 2B (`template_kwarg`, prefill ``; on by default) | `reasoning_effort` `medium` / `none` / `medium` (reported as `on`) | `chat_template_kwargs.enable_thinking` | template switch (GGUF: the model's own template, rendered by AbstractCore) | | Gemma 4, Nemotron, GLM-5, LongCat (`template_kwarg` only) | `reasoning_effort` `medium` / `none` / `medium` (reported as `on`) | `chat_template_kwargs.enable_thinking`; Nemotron `low_effort` for `low`/`minimal` | HF: template switch; MLX: not mapped (warns) | | DeepSeek V4, Mistral Small 4 (levels incl. `none`, no template surface) | `reasoning_effort` `high` / `none` / `high` | `reasoning_effort` | not mapped (warns) | | GPT-OSS (Harmony, levels `low\|medium\|high`) | `Reasoning:` system line plus `reasoning_effort` | `reasoning_effort` (vLLM builds the Harmony system message from it) plus the system line | `Reasoning:` system line | @@ -23046,7 +23064,7 @@ except PDFProcessingError: - **Formats**: common `audio/*` types (WAV, MP3, M4A, …) as attachments via `media=[...]` - **Default behavior**: `audio_policy="native_only"` (fails loudly unless the model supports native audio input) - **Speech-to-text**: `audio_policy="speech_to_text"` runs STT via the capability plugin layer (`llm.audio.transcribe(...)`; typically install `abstractvoice`) and injects a transcript into the main request -- **Auto**: `audio_policy="auto"` uses native audio when supported, otherwise STT when configured, otherwise errors +- **Auto**: `audio_policy="auto"` uses native audio when the model hears AND the provider carries audio to it (no AbstractCore provider does today: Ollama, LM Studio, the GGUF lane and the MLX native lane have no audio transport), otherwise STT when configured, otherwise an error naming `input.voice` and `audio_policy="speech_to_text"` - **Reserved**: `audio_policy="caption"` is not configured in v0 (must error; non-speech audio analysis needs an explicit capability) Transparency: @@ -23140,6 +23158,25 @@ resp.metadata["media_delivered"] `vision_family_unsupported`, `vision_multi_image_unsupported` or `media_processing_unavailable`. - Streamed responses carry the same record; read it from the final chunk as you would usage. +An attachment a provider cannot carry to the model is an error, never a text-only request: the +provider raises `UnsupportedFeatureError` naming the model, the route and each attachment's kind +(a missing file, an encoding failure, audio on a route that takes none, an image on the GGUF +lane, which loads no vision projector yet). MLX reports what it could not carry in +`media_dropped` and tells the model, as described above. + +A file that cannot be read is refused the same way, with the reader's own cause, never sent as a +`[Document: name]` placeholder: a corrupt PDF or DOCX ("Cannot read document file 'x.pdf': ..."), a +PDF or Office file whose reader is not installed (the error says what to install), and a binary +file of a type AbstractCore has no reader for (`.zip`, `.bin`...). Text files of any extension are +read as text. Through AbstractCore's server a plain request with such a refusal gets HTTP 400 +`invalid_request_error` with the code `unsupported_feature`, so a client never retries it as a server +fault. A streamed +request opens at once; its refusal arrives as the stream's error event with the same type and +code, and AbstractCore's OpenAI-compatible provider raises `UnsupportedFeatureError` for it. + +An Ollama or LM Studio vision model given a picture and a document receives both: the picture as +an image, the document's text in the message, as for a text-only model. + For a single answer, use the shared helper: ```python @@ -23725,7 +23762,7 @@ abstractcore --set-video-sampling-strategy keyframes Qwen3.8-Flash-Next (`qwen4_exp`) uses the full native MLX vision graph, including image input with embedded MTP and selectable draft depth. It requires MLX ≥0.32.2 -and mlx-vlm ≥0.7.1; see [native MTP setup](docs/speculative-decoding.md#qwen38-flash-next-on-native-mlx). +and mlx-vlm ≥0.7.12; see [native MTP setup](docs/speculative-decoding.md#qwen38-flash-next-on-native-mlx). Its native path accepts multiple images and records measured expanded image tokens in `metadata["media_delivered"]`. Qwen3.8-27B also uses native vision when loaded with its separate MTP head or the scheduled native runtime. See diff --git a/pyproject.toml b/pyproject.toml index 93dbe3bf..a9b7876f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -146,12 +146,14 @@ abstractcore-deepsearch = "abstractcore.apps.deepsearch:main" # sighted Qwen3.x checkpoints without mlx-vlm accepts images and silently drops # them (`mlx_vlm_not_installed`), and the model describes screenshots it never # received. mlx-vlm 0.7.1 provides Qwen4-Exp, embedded MTP and native recurrent -# APC; MLX 0.32.2 is the tested execution floor for that graph. +# APC; MLX 0.32.2 is the tested execution floor for that graph. mlx-vlm 0.7.12 is +# the floor because it loads LFM3 (no mlx-lm release does) with the reasoning-leak +# fix of 0.7.12; it requires mlx>=0.32.4 and transformers>=5.14.0 itself. apple = [ # MLX text + vision provider. "mlx>=0.32.2,<1.0.0", "mlx-lm>=0.31.3,<1.0.0", - "mlx-vlm>=0.7.1,<0.8.0", # image input and native MTP + "mlx-vlm>=0.7.12,<0.8.0", # image input, native MTP, and model types mlx-lm lacks (LFM3: 0.7.12) "outlines>=0.1.0", # native structured output # HuggingFace provider (transformers / GGUF via llama.cpp) and local embeddings. # Pins stay aligned with abstractvoice[all-apple] and abstractvision[all-apple] @@ -283,7 +285,7 @@ all = [ "omnivoice>=0.1.5", "mlx>=0.32.2,<1.0.0", "mlx-lm>=0.31.3,<1.0.0", - "mlx-vlm>=0.7.1,<0.8.0", + "mlx-vlm>=0.7.12,<0.8.0", "vllm>=0.6.0,<1.0.0", ] mlx-bench = ["matplotlib>=3.8.0,<4.0.0"] diff --git a/tests/assets/test_architecture_formats_schema.py b/tests/assets/test_architecture_formats_schema.py index 6c275fbe..b4355508 100644 --- a/tests/assets/test_architecture_formats_schema.py +++ b/tests/assets/test_architecture_formats_schema.py @@ -138,6 +138,14 @@ def test_architecture_entries_conform_to_v0_template(): "inference_parameters", "prompt_cache_position_strategy", "decision", + # The BOS token the model's template writes first (LFM3 `<|startoftext|>`), + # for the hand-built renderers. + "bos_token", + # llama.cpp context options measured for the architecture (GGUF provider). + "llama_cpp_context", + # config.json model_types mlx-lm has no module for that load through mlx-vlm, + # verified on real weights: {model_type: minimum mlx-vlm version} (MLX provider). + "mlx_vlm_model_types", } allowed_keys = required_keys | prefix_suffix_keys | optional_keys @@ -147,6 +155,19 @@ def test_architecture_entries_conform_to_v0_template(): extra = set(cfg) - allowed_keys assert not extra, f"architectures[{arch_name}] contains unknown keys: {sorted(extra)}" + if "bos_token" in cfg: + assert _non_empty_str(cfg["bos_token"]), f"architectures[{arch_name}].bos_token must be a token string" + if "mlx_vlm_model_types" in cfg: + types_ = cfg["mlx_vlm_model_types"] + assert isinstance(types_, dict) and types_ and all( + _non_empty_str(k) and _non_empty_str(v) and all(p.isdigit() for p in v.split(".")) + for k, v in types_.items() + ), f"architectures[{arch_name}].mlx_vlm_model_types must map model_type to a version like 0.7.12" + if "llama_cpp_context" in cfg: + ctx = cfg["llama_cpp_context"] + assert isinstance(ctx, dict) and ctx and set(ctx) <= {"flash_attn", "swa_full"} and all( + isinstance(v, bool) for v in ctx.values() + ), f"architectures[{arch_name}].llama_cpp_context must map flash_attn/swa_full to booleans" missing = required_keys - set(cfg) assert not missing, f"architectures[{arch_name}] is missing required keys: {sorted(missing)}" diff --git a/tests/assets/test_model_capabilities_schema.py b/tests/assets/test_model_capabilities_schema.py index 148fe3ee..67264721 100644 --- a/tests/assets/test_model_capabilities_schema.py +++ b/tests/assets/test_model_capabilities_schema.py @@ -216,6 +216,11 @@ def _validate_model_entry_v0(*, model_key: str, cfg: Mapping[str, Any]) -> None: # Add new research-only keys either under an existing bucket (e.g. `benchmarks`) # or by explicitly extending this allowlist + docs. optional_keys = { + # With thinking off the model writes a closing thinking tag it was never given (LFM3); + # the stream removes that one tag (`BaseProvider._strips_stray_close_tag`). + "thinking_off_leaks_close_tag", + # GGUF lane: the template's own tool block and `tool` turns, opted in per model (run on real weights). + "gguf_template_tools", "active_parameters", "adaptive_resolution", "adaptive_windowing", diff --git a/tests/assets/test_registry_sampling_keeps_mtp.py b/tests/assets/test_registry_sampling_keeps_mtp.py new file mode 100644 index 00000000..fc1a2b6e --- /dev/null +++ b/tests/assets/test_registry_sampling_keeps_mtp.py @@ -0,0 +1,44 @@ +"""A registry sampling default must never switch a model's MTP speculation off (LFM3 fix round, 2026-12-01). + +The MLX provider's native (mlx-vlm) lane applies the registry's `inference_parameters.repeat_penalty` +as a default when the caller sets none (`MLXProvider._prepare_native_sampling`, LFM3 card 1.1), and +mlx-vlm's MTP loop cannot apply a logit processor: any repetition, presence or frequency penalty other +than neutral switches MTP off for every call (or raises with `require_acceleration`). So an entry that +declares `speculation.native_mtp` must not also declare a non-neutral penalty: copying a card's value +into such an entry would silently cost it its speculation on every call. This test refuses that entry. +""" +from __future__ import annotations + +import copy +import json +from pathlib import Path +from typing import Any, Dict, List + +REGISTRY = Path(__file__).resolve().parents[2] / "abstractcore" / "assets" / "model_capabilities.json" +# mlx-vlm logit processors (see MLXProvider._prepare_native_sampling: `neutral`) +NEUTRAL = {"repeat_penalty": (1, 1.0), "presence_penalty": (0, 0.0), "frequency_penalty": (0, 0.0)} + + +def _conflicts(models: Dict[str, Any]) -> List[str]: + found = [] + for name, entry in models.items(): + if not isinstance(entry, dict) or not (entry.get("speculation") or {}).get("native_mtp"): + continue + params = entry.get("inference_parameters") or {} + for key, neutral in NEUTRAL.items(): + if key in params and params[key] is not None and params[key] not in neutral: + found.append(f"{name}: inference_parameters.{key}={params[key]} would switch its MTP off") + return found + + +def test_no_mtp_model_declares_a_penalty_that_switches_mtp_off(): + models = json.loads(REGISTRY.read_text())["models"] + assert _conflicts(models) == [] + + +def test_the_check_fires_on_such_an_entry(): + models = json.loads(REGISTRY.read_text())["models"] + mtp = next(name for name, e in models.items() if (e.get("speculation") or {}).get("native_mtp")) + mutated = copy.deepcopy(models) + mutated[mtp].setdefault("inference_parameters", {})["repeat_penalty"] = 1.05 + assert _conflicts(mutated) == [f"{mtp}: inference_parameters.repeat_penalty=1.05 would switch its MTP off"] diff --git a/tests/config/test_recommended_text_tiers.py b/tests/config/test_recommended_text_tiers.py index 60613575..451c15af 100644 --- a/tests/config/test_recommended_text_tiers.py +++ b/tests/config/test_recommended_text_tiers.py @@ -614,6 +614,9 @@ def test_every_upstream_artifact_is_eight_bit_or_a_tier_or_a_reverified_id(): "unsloth/LFM2.5-1.2B-Instruct-GGUF:Q4_K_M", "unsloth/LFM2.5-1.2B-Thinking-GGUF:Q4_K_M", } + # LFM3-1.7B (2026-11-30): sizes and revisions read from the Hugging Face API, and both builds + # run end to end through AbstractCore (MLX via mlx-vlm 0.7.12, GGUF via llama-cpp-python 0.3.38). + reverified |= {"LiquidAI/LFM3-1.7B-GGUF:Q4_K_M", "LiquidAI/LFM3-1.7B-MLX-4bit"} # GGUF builds for the curated rows that had none (backlog 0863, 2026-10-29): a host whose only # engine is llama.cpp is offered a build it runs. Every repo id, size and revision read from # the Hugging Face API (`?blobs=true`, the files the `*QUANT*.gguf` download pattern fetches). diff --git a/tests/fixtures/lfm3/raw_outputs.json b/tests/fixtures/lfm3/raw_outputs.json new file mode 100644 index 00000000..cd6d6f76 --- /dev/null +++ b/tests/fixtures/lfm3/raw_outputs.json @@ -0,0 +1,7 @@ +{ + "_source": "Raw LFM3-1.7B outputs recorded on mlx-vlm 0.7.12/0.8.1 (LiquidAI/LFM3-1.7B-MLX-4bit, card sampling, seed 0), decoded with special tokens, 2026-11-30: untracked/lfm3/ground-truth/out/mlx-LFM3-1.7B-MLX-4bit.json. The prompt of each ended with the template's generation prompt: `` (thinking on) or `` (thinking off).", + "two_calls_thinking_on": "We need to get the weather in Tokyo and the current local time there. The user specified \"Asia/Tokyo\" as the timezone for the time query.\n\nWe have two tools:\n1. `get_weather` - requires city and optionally unit.\n2. `get_time` - requires timezone.\n\nFor the weather, I'll call `get_weather` with city \"Tokyo\". The unit parameter is optional; the user didn't specify, so I can omit it or choose a default. The tool schema shows `unit` is an enum but not required. I'll just provide city.\n\nFor the time, I'll call `get_time` with timezone \"Asia/Tokyo\".\n\nLet's make the calls.\n\n\nTokyo\n\n\n\n\n\n\n\nAsia/Tokyo\n\n\n<|im_end|>", + "two_calls_thinking_off_stray_close": "We need to get the weather in Tokyo and the current local time there. The user specified the timezone as Asia/Tokyo.\n\nFor weather, we can use `get_weather` with city \"Tokyo\". The tool has an optional parameter `unit`, but it's not required. We can omit it or choose a default; since the user didn't specify unit, we'll just provide city.\n\nFor time, we can use `get_time` with timezone \"Asia/Tokyo\".\n\nLet's call both tools.\n\n\nTokyo\n\n\n\n\n\n\n\nAsia/Tokyo\n\n\n<|im_end|>", + "json_answer_thinking_off": "{\n \"name\": \"Maria Lopez\",\n \"age\": 34,\n \"hobbies\": [\n \"climbing\",\n \"painting\",\n \"chess\"\n ]\n}<|im_end|>", + "json_answer_thinking_on": "We need to parse the text: \"Maria Lopez is 34 years old. She enjoys climbing, painting and chess.\"\n\nWe need to extract a JSON object matching the given schema: \n{\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\"},\n \"age\": {\"type\": \"integer\"},\n \"hobbies\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}\n },\n \"required\": [\"name\", \"age\", \"hobbies\"],\n \"additionalProperties\": false\n}\n\nSo we need to output a JSON object with keys: name, age, hobbies.\n\nFrom text:\n- Name: Maria Lopez (string)\n- Age: 34 years old -> integer 34.\n- Hobbies: \"climbing, painting and chess.\" So three items: climbing, painting, chess. They are separated by commas. We need to produce an array of strings: [\"climbing\", \"painting\", \"chess\"] (case? The text uses lowercase: climbing, painting and chess. So we should preserve exactly as given? Usually we can keep the same case: \"climbing\", \"painting\", \"chess\". The text says \"She enjoys climbing, painting and chess.\" So we can extract those as strings.\n\nThus final JSON:\n\n{\n \"name\": \"Maria Lopez\",\n \"age\": 34,\n \"hobbies\": [\"climbing\", \"painting\", \"chess\"]\n}\n\nWe need to output only the JSON object. Ensure it's valid JSON, with double quotes around keys and string values.\n\nThus final answer: {\"name\":\"Maria Lopez\",\"age\":34,\"hobbies\":[\"climbing\",\"painting\",\"chess\"]}\n\nWe should maybe include spaces after commas? Usually JSON doesn't require but it's fine.\n\nLet's output exactly that.{\n \"name\": \"Maria Lopez\",\n \"age\": 34,\n \"hobbies\": [\"climbing\", \"painting\", \"chess\"]\n}<|im_end|>" +} \ No newline at end of file diff --git a/tests/fixtures/lfm3/rendered_prompts.json b/tests/fixtures/lfm3/rendered_prompts.json new file mode 100644 index 00000000..763fd3f0 --- /dev/null +++ b/tests/fixtures/lfm3/rendered_prompts.json @@ -0,0 +1,813 @@ +{ + "_source": "Prompts rendered by the official LFM3-1.7B chat templates for the cases of tests/providers/test_lfm3_prompt_parity_unit.py, and the inputs AbstractCore hands each lane's renderer. Templates (read from the local Hugging Face cache, not copied): GGUF embedded template sha256 f45005c50cd2a97329722bf3a2dee9f16c04cdf825a589b280fb7e99e6827818, MLX chat_template.jinja sha256 306497f109439afcfa248f4ef5800601de24942e2981d632ae63fc5c070ceb12. Regenerate: python tests/providers/test_lfm3_prompt_parity_unit.py --regenerate", + "cases": { + "multi_turn": { + "gguf_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.<|im_end|>\n<|im_start|>user\nMy name is Ada and I keep three cats. Name a fourth?<|im_end|>\n<|im_start|>assistant\nHow about Juniper?<|im_end|>\n<|im_start|>user\nHow many cats will I have, and what is my name?<|im_end|>\n<|im_start|>assistant\n", + "mlx_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.<|im_end|>\n<|im_start|>user\nMy name is Ada and I keep three cats. Name a fourth?<|im_end|>\n<|im_start|>assistant\nHow about Juniper?<|im_end|>\n<|im_start|>user\nHow many cats will I have, and what is my name?<|im_end|>\n<|im_start|>assistant\n", + "gguf_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "My name is Ada and I keep three cats. Name a fourth?" + }, + { + "role": "assistant", + "content": "How about Juniper?" + }, + { + "role": "user", + "content": "How many cats will I have, and what is my name?" + } + ], + "tools": null, + "enable_thinking": null, + "add_generation_prompt": true + }, + "mlx_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "My name is Ada and I keep three cats. Name a fourth?" + }, + { + "role": "assistant", + "content": "How about Juniper?" + }, + { + "role": "user", + "content": "How many cats will I have, and what is my name?" + } + ], + "tools": null, + "enable_thinking": null, + "add_generation_prompt": true + } + }, + "no_system_tools": { + "gguf_prompt": "<|startoftext|><|im_start|>system\n\n{\"name\": \"get_weather\", \"description\": \"Get the current weather for a city.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\", \"description\": \"City name\"}, \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"], \"default\": \"celsius\"}}, \"required\": [\"city\"]}}\n{\"name\": \"get_time\", \"description\": \"Get the current local time in an IANA time zone.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"timezone\": {\"type\": \"string\", \"description\": \"IANA zone, e.g. Europe/Paris\"}}, \"required\": [\"timezone\"]}}\n<|im_end|>\n<|im_start|>user\nWhat is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools.<|im_end|>\n<|im_start|>assistant\n", + "mlx_prompt": "<|startoftext|><|im_start|>system\n\n{\"name\": \"get_weather\", \"description\": \"Get the current weather for a city.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\", \"description\": \"City name\"}, \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"], \"default\": \"celsius\"}}, \"required\": [\"city\"]}}\n{\"name\": \"get_time\", \"description\": \"Get the current local time in an IANA time zone.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"timezone\": {\"type\": \"string\", \"description\": \"IANA zone, e.g. Europe/Paris\"}}, \"required\": [\"timezone\"]}}\n<|im_end|>\n<|im_start|>user\nWhat is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools.<|im_end|>\n<|im_start|>assistant\n", + "gguf_inputs": { + "messages": [ + { + "role": "user", + "content": "What is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools." + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a city.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "City name" + }, + "unit": { + "type": "string", + "enum": [ + "celsius", + "fahrenheit" + ], + "default": "celsius" + } + }, + "required": [ + "city" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "get_time", + "description": "Get the current local time in an IANA time zone.", + "parameters": { + "type": "object", + "properties": { + "timezone": { + "type": "string", + "description": "IANA zone, e.g. Europe/Paris" + } + }, + "required": [ + "timezone" + ] + } + } + } + ], + "enable_thinking": null, + "add_generation_prompt": true + }, + "mlx_inputs": { + "messages": [ + { + "role": "user", + "content": "What is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools." + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a city.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "City name" + }, + "unit": { + "type": "string", + "enum": [ + "celsius", + "fahrenheit" + ], + "default": "celsius" + } + }, + "required": [ + "city" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "get_time", + "description": "Get the current local time in an IANA time zone.", + "parameters": { + "type": "object", + "properties": { + "timezone": { + "type": "string", + "description": "IANA zone, e.g. Europe/Paris" + } + }, + "required": [ + "timezone" + ] + } + } + } + ], + "enable_thinking": null, + "add_generation_prompt": true + } + }, + "system_user_default": { + "gguf_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.<|im_end|>\n<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n", + "mlx_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.<|im_end|>\n<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n", + "gguf_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "hi" + } + ], + "tools": null, + "enable_thinking": null, + "add_generation_prompt": true + }, + "mlx_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "hi" + } + ], + "tools": null, + "enable_thinking": null, + "add_generation_prompt": true + } + }, + "thinking_off": { + "gguf_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.<|im_end|>\n<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n", + "mlx_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.<|im_end|>\n<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n", + "gguf_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "hi" + } + ], + "tools": null, + "enable_thinking": false, + "add_generation_prompt": true + }, + "mlx_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "hi" + } + ], + "tools": null, + "enable_thinking": false, + "add_generation_prompt": true + } + }, + "thinking_on": { + "gguf_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.<|im_end|>\n<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n", + "mlx_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.<|im_end|>\n<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n", + "gguf_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "hi" + } + ], + "tools": null, + "enable_thinking": true, + "add_generation_prompt": true + }, + "mlx_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "hi" + } + ], + "tools": null, + "enable_thinking": true, + "add_generation_prompt": true + } + }, + "tool_results": { + "gguf_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.\n\n\n{\"name\": \"get_weather\", \"description\": \"Get the current weather for a city.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\", \"description\": \"City name\"}, \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"], \"default\": \"celsius\"}}, \"required\": [\"city\"]}}\n{\"name\": \"get_time\", \"description\": \"Get the current local time in an IANA time zone.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"timezone\": {\"type\": \"string\", \"description\": \"IANA zone, e.g. Europe/Paris\"}}, \"required\": [\"timezone\"]}}\n<|im_end|>\n<|im_start|>user\nWhat is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools.<|im_end|>\n<|im_start|>assistant\n\n\n\nTokyo\n\n\n\n\n\n\n\nAsia/Tokyo\n\n\n<|im_end|>\n<|im_start|>tool\n\n{\"city\": \"Tokyo\", \"temperature\": 14, \"unit\": \"celsius\", \"sky\": \"light rain\"}\n<|im_end|>\n<|im_start|>tool\n\n{\"timezone\": \"Asia/Tokyo\", \"time\": \"06:42\"}\n<|im_end|>\n<|im_start|>assistant\n", + "mlx_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.\n\n\n{\"name\": \"get_weather\", \"description\": \"Get the current weather for a city.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\", \"description\": \"City name\"}, \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"], \"default\": \"celsius\"}}, \"required\": [\"city\"]}}\n{\"name\": \"get_time\", \"description\": \"Get the current local time in an IANA time zone.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"timezone\": {\"type\": \"string\", \"description\": \"IANA zone, e.g. Europe/Paris\"}}, \"required\": [\"timezone\"]}}\n<|im_end|>\n<|im_start|>user\nWhat is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools.<|im_end|>\n<|im_start|>assistant\n\n\n\nTokyo\n\n\n\n\n\n\n\nAsia/Tokyo\n\n\n<|im_end|>\n<|im_start|>tool\n\n{\"city\": \"Tokyo\", \"temperature\": 14, \"unit\": \"celsius\", \"sky\": \"light rain\"}\n<|im_end|>\n<|im_start|>tool\n\n{\"timezone\": \"Asia/Tokyo\", \"time\": \"06:42\"}\n<|im_end|>\n<|im_start|>assistant\n", + "gguf_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "What is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools." + }, + { + "role": "assistant", + "content": "", + "tool_calls": [ + { + "id": "call_0", + "type": "function", + "function": { + "name": "get_weather", + "arguments": { + "city": "Tokyo" + } + } + }, + { + "id": "call_1", + "type": "function", + "function": { + "name": "get_time", + "arguments": { + "timezone": "Asia/Tokyo" + } + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "call_0", + "name": "get_weather", + "content": "{\"city\": \"Tokyo\", \"temperature\": 14, \"unit\": \"celsius\", \"sky\": \"light rain\"}" + }, + { + "role": "tool", + "tool_call_id": "call_1", + "name": "get_time", + "content": "{\"timezone\": \"Asia/Tokyo\", \"time\": \"06:42\"}" + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a city.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "City name" + }, + "unit": { + "type": "string", + "enum": [ + "celsius", + "fahrenheit" + ], + "default": "celsius" + } + }, + "required": [ + "city" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "get_time", + "description": "Get the current local time in an IANA time zone.", + "parameters": { + "type": "object", + "properties": { + "timezone": { + "type": "string", + "description": "IANA zone, e.g. Europe/Paris" + } + }, + "required": [ + "timezone" + ] + } + } + } + ], + "enable_thinking": null, + "add_generation_prompt": true + }, + "mlx_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "What is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools." + }, + { + "role": "assistant", + "content": "", + "tool_calls": [ + { + "type": "function", + "function": { + "name": "get_weather", + "arguments": { + "city": "Tokyo" + } + }, + "id": "call_0" + }, + { + "type": "function", + "function": { + "name": "get_time", + "arguments": { + "timezone": "Asia/Tokyo" + } + }, + "id": "call_1" + } + ] + }, + { + "role": "tool", + "content": "{\"city\": \"Tokyo\", \"temperature\": 14, \"unit\": \"celsius\", \"sky\": \"light rain\"}", + "tool_call_id": "call_0", + "name": "get_weather" + }, + { + "role": "tool", + "content": "{\"timezone\": \"Asia/Tokyo\", \"time\": \"06:42\"}", + "tool_call_id": "call_1", + "name": "get_time" + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a city.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "City name" + }, + "unit": { + "type": "string", + "enum": [ + "celsius", + "fahrenheit" + ], + "default": "celsius" + } + }, + "required": [ + "city" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "get_time", + "description": "Get the current local time in an IANA time zone.", + "parameters": { + "type": "object", + "properties": { + "timezone": { + "type": "string", + "description": "IANA zone, e.g. Europe/Paris" + } + }, + "required": [ + "timezone" + ] + } + } + } + ], + "enable_thinking": null, + "add_generation_prompt": true + } + }, + "tool_results_thinking_off": { + "gguf_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.\n\n\n{\"name\": \"get_weather\", \"description\": \"Get the current weather for a city.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\", \"description\": \"City name\"}, \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"], \"default\": \"celsius\"}}, \"required\": [\"city\"]}}\n{\"name\": \"get_time\", \"description\": \"Get the current local time in an IANA time zone.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"timezone\": {\"type\": \"string\", \"description\": \"IANA zone, e.g. Europe/Paris\"}}, \"required\": [\"timezone\"]}}\n<|im_end|>\n<|im_start|>user\nWhat is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools.<|im_end|>\n<|im_start|>assistant\n\n\n\nTokyo\n\n\n\n\n\n\n\nAsia/Tokyo\n\n\n<|im_end|>\n<|im_start|>tool\n\n{\"city\": \"Tokyo\", \"temperature\": 14, \"unit\": \"celsius\", \"sky\": \"light rain\"}\n<|im_end|>\n<|im_start|>tool\n\n{\"timezone\": \"Asia/Tokyo\", \"time\": \"06:42\"}\n<|im_end|>\n<|im_start|>assistant\n", + "mlx_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.\n\n\n{\"name\": \"get_weather\", \"description\": \"Get the current weather for a city.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\", \"description\": \"City name\"}, \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"], \"default\": \"celsius\"}}, \"required\": [\"city\"]}}\n{\"name\": \"get_time\", \"description\": \"Get the current local time in an IANA time zone.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"timezone\": {\"type\": \"string\", \"description\": \"IANA zone, e.g. Europe/Paris\"}}, \"required\": [\"timezone\"]}}\n<|im_end|>\n<|im_start|>user\nWhat is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools.<|im_end|>\n<|im_start|>assistant\n\n\n\nTokyo\n\n\n\n\n\n\n\nAsia/Tokyo\n\n\n<|im_end|>\n<|im_start|>tool\n\n{\"city\": \"Tokyo\", \"temperature\": 14, \"unit\": \"celsius\", \"sky\": \"light rain\"}\n<|im_end|>\n<|im_start|>tool\n\n{\"timezone\": \"Asia/Tokyo\", \"time\": \"06:42\"}\n<|im_end|>\n<|im_start|>assistant\n", + "gguf_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "What is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools." + }, + { + "role": "assistant", + "content": "", + "tool_calls": [ + { + "id": "call_0", + "type": "function", + "function": { + "name": "get_weather", + "arguments": { + "city": "Tokyo" + } + } + }, + { + "id": "call_1", + "type": "function", + "function": { + "name": "get_time", + "arguments": { + "timezone": "Asia/Tokyo" + } + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "call_0", + "name": "get_weather", + "content": "{\"city\": \"Tokyo\", \"temperature\": 14, \"unit\": \"celsius\", \"sky\": \"light rain\"}" + }, + { + "role": "tool", + "tool_call_id": "call_1", + "name": "get_time", + "content": "{\"timezone\": \"Asia/Tokyo\", \"time\": \"06:42\"}" + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a city.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "City name" + }, + "unit": { + "type": "string", + "enum": [ + "celsius", + "fahrenheit" + ], + "default": "celsius" + } + }, + "required": [ + "city" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "get_time", + "description": "Get the current local time in an IANA time zone.", + "parameters": { + "type": "object", + "properties": { + "timezone": { + "type": "string", + "description": "IANA zone, e.g. Europe/Paris" + } + }, + "required": [ + "timezone" + ] + } + } + } + ], + "enable_thinking": false, + "add_generation_prompt": true + }, + "mlx_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "What is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools." + }, + { + "role": "assistant", + "content": "", + "tool_calls": [ + { + "type": "function", + "function": { + "name": "get_weather", + "arguments": { + "city": "Tokyo" + } + }, + "id": "call_0" + }, + { + "type": "function", + "function": { + "name": "get_time", + "arguments": { + "timezone": "Asia/Tokyo" + } + }, + "id": "call_1" + } + ] + }, + { + "role": "tool", + "content": "{\"city\": \"Tokyo\", \"temperature\": 14, \"unit\": \"celsius\", \"sky\": \"light rain\"}", + "tool_call_id": "call_0", + "name": "get_weather" + }, + { + "role": "tool", + "content": "{\"timezone\": \"Asia/Tokyo\", \"time\": \"06:42\"}", + "tool_call_id": "call_1", + "name": "get_time" + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a city.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "City name" + }, + "unit": { + "type": "string", + "enum": [ + "celsius", + "fahrenheit" + ], + "default": "celsius" + } + }, + "required": [ + "city" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "get_time", + "description": "Get the current local time in an IANA time zone.", + "parameters": { + "type": "object", + "properties": { + "timezone": { + "type": "string", + "description": "IANA zone, e.g. Europe/Paris" + } + }, + "required": [ + "timezone" + ] + } + } + } + ], + "enable_thinking": false, + "add_generation_prompt": true + } + }, + "tools_ask": { + "gguf_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.\n\n\n{\"name\": \"get_weather\", \"description\": \"Get the current weather for a city.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\", \"description\": \"City name\"}, \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"], \"default\": \"celsius\"}}, \"required\": [\"city\"]}}\n{\"name\": \"get_time\", \"description\": \"Get the current local time in an IANA time zone.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"timezone\": {\"type\": \"string\", \"description\": \"IANA zone, e.g. Europe/Paris\"}}, \"required\": [\"timezone\"]}}\n<|im_end|>\n<|im_start|>user\nWhat is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools.<|im_end|>\n<|im_start|>assistant\n", + "mlx_prompt": "<|startoftext|><|im_start|>system\nYou are a concise assistant. Answer in plain sentences.\n\n\n{\"name\": \"get_weather\", \"description\": \"Get the current weather for a city.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\", \"description\": \"City name\"}, \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"], \"default\": \"celsius\"}}, \"required\": [\"city\"]}}\n{\"name\": \"get_time\", \"description\": \"Get the current local time in an IANA time zone.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"timezone\": {\"type\": \"string\", \"description\": \"IANA zone, e.g. Europe/Paris\"}}, \"required\": [\"timezone\"]}}\n<|im_end|>\n<|im_start|>user\nWhat is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools.<|im_end|>\n<|im_start|>assistant\n", + "gguf_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "What is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools." + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a city.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "City name" + }, + "unit": { + "type": "string", + "enum": [ + "celsius", + "fahrenheit" + ], + "default": "celsius" + } + }, + "required": [ + "city" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "get_time", + "description": "Get the current local time in an IANA time zone.", + "parameters": { + "type": "object", + "properties": { + "timezone": { + "type": "string", + "description": "IANA zone, e.g. Europe/Paris" + } + }, + "required": [ + "timezone" + ] + } + } + } + ], + "enable_thinking": null, + "add_generation_prompt": true + }, + "mlx_inputs": { + "messages": [ + { + "role": "system", + "content": "You are a concise assistant. Answer in plain sentences." + }, + { + "role": "user", + "content": "What is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools." + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a city.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "City name" + }, + "unit": { + "type": "string", + "enum": [ + "celsius", + "fahrenheit" + ], + "default": "celsius" + } + }, + "required": [ + "city" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "get_time", + "description": "Get the current local time in an IANA time zone.", + "parameters": { + "type": "object", + "properties": { + "timezone": { + "type": "string", + "description": "IANA zone, e.g. Europe/Paris" + } + }, + "required": [ + "timezone" + ] + } + } + } + ], + "enable_thinking": null, + "add_generation_prompt": true + } + } + } +} diff --git a/tests/media_handling/test_audio_auto_policy_unit.py b/tests/media_handling/test_audio_auto_policy_unit.py new file mode 100644 index 00000000..0a4ca0ee --- /dev/null +++ b/tests/media_handling/test_audio_auto_policy_unit.py @@ -0,0 +1,70 @@ +"""`audio_policy='auto'` for a model the registry says hears, on a provider with no audio route +(re-check N6, 2026-12-01). + +34 registry entries hear (Gemma 4, gemma3n, LFM3-Audio/Omni...), but no AbstractCore provider carries +an audio attachment to a model (Ollama, LM Studio and the GGUF lane have no audio transport; the MLX +native lane takes image frames). Under `auto` the native path was chosen anyway because the model +hears, and the request was refused ("needs a route that carries audio") although speech-to-text was +configured. Now `auto` takes the native path only when the provider carries audio +(`BaseProvider._carries_native_audio`), otherwise the configured speech-to-text; without one, the +error names the settings that serve the request. No model, no network. +""" +from __future__ import annotations + +from pathlib import Path + +import pytest + +from abstractcore.core.types import GenerateResponse +from abstractcore.exceptions import UnsupportedFeatureError +from tests.provider_stubs import StaticProvider + +MODEL = "gemma-4-e4b-it" # the registry says it hears + + +class _Hearing(StaticProvider): + seen = [] + + def _generate_internal(self, prompt, messages=None, system_prompt=None, tools=None, media=None, stream=False, + response_model=None, execute_tools=None, media_metadata=None, **kwargs): + type(self).seen.append({"prompt": prompt, "kinds": [getattr(m.media_type, "value", None) for m in (media or [])]}) + return GenerateResponse(content="ok", model=self.model, finish_reason="stop") + + +class _HearingWithSTT(_Hearing): + @property + def audio(self): + return _FakeSTT() + + +class _FakeSTT: + backend_id = "fake-stt" + + def transcribe(self, audio, language=None, **kw): + return "turn the lights off" + + +def _voice(tmp_path: Path) -> str: + f = tmp_path / "voice.wav" + f.write_bytes(b"RIFF$\x00\x00\x00WAVEfmt " + b"\x00" * 32) + return str(f) + + +def test_the_model_hears_and_speech_to_text_serves_the_request(tmp_path): + p = _HearingWithSTT(MODEL) + assert p.model_capabilities.get("audio_support") is True + p._abstractcore_capability_defaults = {"input.voice": {"provider": "fake", "model": "stt"}} + _Hearing.seen.clear() + r = p.generate("What is said?", media=[_voice(tmp_path)], audio_policy="auto") + assert r.content == "ok" + assert _Hearing.seen[-1]["kinds"] == [] and "turn the lights off" in _Hearing.seen[-1]["prompt"] + + +def test_without_speech_to_text_the_error_names_the_settings(tmp_path): + p = _Hearing(MODEL) + p._abstractcore_capability_defaults = {"input.voice": {"source": "not_configured"}} + with pytest.raises(UnsupportedFeatureError) as e: + p.generate("What is said?", media=[_voice(tmp_path)], audio_policy="auto") + message = str(e.value) + assert "has no route that carries audio" in message + assert "input.voice" in message and "audio_policy='speech_to_text'" in message diff --git a/tests/media_handling/test_local_vision_message_documents_unit.py b/tests/media_handling/test_local_vision_message_documents_unit.py new file mode 100644 index 00000000..b26e0db1 --- /dev/null +++ b/tests/media_handling/test_local_vision_message_documents_unit.py @@ -0,0 +1,65 @@ +"""Ollama / LM Studio vision model + a picture AND a document (LFM3 fix round, 2026-12-01). + +The first LFM3 change refused the whole request ("could not encode the image(s)...") when a +document came beside a picture for an Ollama vision model, blaming the image. The document's +text is servable: it now goes into the message text in the `--- Content from ---` +form the text-only path uses (as `OpenAIMediaHandler` already does for LM Studio vision +models). What still cannot go (an audio file on these formats) raises, naming THAT file. +""" +from __future__ import annotations + +from pathlib import Path + +import pytest + +from abstractcore.architectures import get_model_capabilities +from abstractcore.media.base import MediaProcessingError +from abstractcore.media.handlers import LocalMediaHandler +from abstractcore.media.types import ContentFormat, MediaContent, MediaType + +VISION = "qwen2.5vl:7b" + + +def _image() -> MediaContent: + png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" + return MediaContent(media_type=MediaType.IMAGE, content=png, content_format=ContentFormat.BASE64, + mime_type="image/png", metadata={"file_name": "red.png"}) + + +def _document() -> MediaContent: + return MediaContent(media_type=MediaType.DOCUMENT, content="Quarterly revenue: 42.", content_format=ContentFormat.TEXT, + mime_type="application/pdf", metadata={"file_name": "report.pdf"}) + + +def _audio(tmp_path: Path) -> MediaContent: + f = tmp_path / "voice.wav" + f.write_bytes(b"RIFF....WAVEfmt ") + return MediaContent(media_type=MediaType.AUDIO, content=str(f), content_format=ContentFormat.FILE_PATH, + mime_type="audio/wav", file_path=str(f), metadata={"file_name": "voice.wav"}) + + +def _handler(provider: str) -> LocalMediaHandler: + return LocalMediaHandler(provider, get_model_capabilities(VISION), model_name=VISION) + + +def test_ollama_vision_message_carries_the_picture_and_the_document(): + message = _handler("ollama").create_multimodal_message("Compare them.", [_image(), _document()]) + assert message["images"] == [_image().content] + assert message["content"].startswith("Compare them.") + assert "--- Content from report.pdf ---\nQuarterly revenue: 42.\n--- End of report.pdf ---" in message["content"] + + +def test_lmstudio_vision_message_carries_the_picture_and_the_document(): + message = _handler("lmstudio").create_multimodal_message("Compare them.", [_image(), _document()]) + kinds = [part["type"] for part in message["content"]] + assert kinds.count("image_url") == 1 + assert any("Quarterly revenue: 42." in part.get("text", "") for part in message["content"]) + + +@pytest.mark.parametrize("provider", ["ollama", "lmstudio"]) +def test_what_still_cannot_go_is_named_not_the_picture(provider, tmp_path): + with pytest.raises(MediaProcessingError) as e: + _handler(provider).create_multimodal_message("What is said?", [_image(), _audio(tmp_path)]) + message = str(e.value) + assert "voice.wav" in message + assert "red.png" not in message and "encode the image" not in message diff --git a/tests/media_handling/test_media_never_dropped_unit.py b/tests/media_handling/test_media_never_dropped_unit.py new file mode 100644 index 00000000..440cd394 --- /dev/null +++ b/tests/media_handling/test_media_never_dropped_unit.py @@ -0,0 +1,270 @@ +"""An attachment is never dropped in silence (2026-11-30). + +Before: the OpenAI-compatible lane caught any error while encoding media, logged a +warning and sent the text alone (finding: an audio file for LM Studio raised +"Unsupported media type for OpenAI: AUDIO" and the IMAGE beside it vanished too); the +Anthropic and Ollama lanes did the same; the GGUF lane built image markers with no pixels +behind them (no projector is loaded) and also sent the text alone on any error; the +transformers text lane kept only the text of an image-bearing message; the shared media +reader skipped files it could not read; the local text embedder wrote an audio file's path +into the prompt. Each now raises an error that names the model, the route and the kind of +attachment. No model, no network: every provider's client is a stub that fails the test if +it is called. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pytest + +from abstractcore.exceptions import UnsupportedFeatureError +from abstractcore.media.types import ContentFormat, MediaContent, MediaType + + +def _audio(tmp_path: Path) -> MediaContent: + f = tmp_path / "question.wav" + f.write_bytes(b"RIFF....WAVEfmt ") + return MediaContent(media_type=MediaType.AUDIO, content=str(f), content_format=ContentFormat.FILE_PATH, + mime_type="audio/wav", file_path=str(f), metadata={"file_name": "question.wav"}) + + +def _image(tmp_path: Path) -> MediaContent: + from PIL import Image + + f = tmp_path / "sign.png" + Image.new("RGB", (8, 8), "white").save(f) + return MediaContent(media_type=MediaType.IMAGE, content=str(f), content_format=ContentFormat.FILE_PATH, + mime_type="image/png", file_path=str(f), metadata={"file_name": "sign.png"}) + + +class _Boom: + """A media handler whose encoding fails, as OpenAIMediaHandler does for audio.""" + + def __init__(self, *a, **k): + pass + + def create_multimodal_message(self, *a, **k): + raise RuntimeError("Unsupported media type for this API: MediaType.AUDIO") + + +def _no_network(*a, **k): + raise AssertionError("the request was sent although its attachment could not be delivered") + + +def _assert_named(err: Exception, model: str, *, route: str, kind: str): + msg = str(err) + assert model in msg and route in msg and kind in msg and "not sent without it" in msg, msg + + +def test_openai_compatible_refuses_instead_of_sending_text_alone(tmp_path, monkeypatch): + from abstractcore.providers.openai_compatible_provider import OpenAICompatibleProvider + + p = OpenAICompatibleProvider(model="lfm3-omni-2b", base_url="http://127.0.0.1:9/v1") + monkeypatch.setattr(p, "_get_media_handler_for_model", lambda model: _Boom()) + monkeypatch.setattr(p, "_process_media_content", lambda media, **k: list(media)) + monkeypatch.setattr(p.client, "post", _no_network) + with pytest.raises(UnsupportedFeatureError) as e: + p._generate_internal("What is said here?", media=[_audio(tmp_path), _image(tmp_path)]) + _assert_named(e.value, "lfm3-omni-2b", route="OpenAI-compatible chat API", kind="audio 'question.wav'") + assert "image 'sign.png'" in str(e.value) + + +def test_openai_compatible_async_refuses_too(tmp_path, monkeypatch): + from abstractcore.providers.openai_compatible_provider import OpenAICompatibleProvider + + p = OpenAICompatibleProvider(model="lfm3-omni-2b", base_url="http://127.0.0.1:9/v1") + monkeypatch.setattr(p, "_get_media_handler_for_model", lambda model: _Boom()) + monkeypatch.setattr(p, "_process_media_content", lambda media, **k: list(media)) + + async def run(): + out = await p._agenerate_internal("What is said here?", None, None, None, [_audio(tmp_path)], False, None) + if hasattr(out, "__aiter__"): + async for _ in out: + pass + + with pytest.raises(UnsupportedFeatureError) as e: + asyncio.run(run()) + _assert_named(e.value, "lfm3-omni-2b", route="OpenAI-compatible chat API", kind="audio") + + +def test_ollama_refuses_instead_of_sending_text_alone(tmp_path, monkeypatch): + from abstractcore.media import handlers + from abstractcore.providers.ollama_provider import OllamaProvider + + p = OllamaProvider(model="qwen3-vl:4b", base_url="http://127.0.0.1:9") + monkeypatch.setattr(handlers, "LocalMediaHandler", _Boom) + monkeypatch.setattr(p, "_process_media_content", lambda media, **k: list(media)) + monkeypatch.setattr(p.client, "post", _no_network) + with pytest.raises(UnsupportedFeatureError) as e: + p._generate_internal("Describe it.", media=[_image(tmp_path)]) + _assert_named(e.value, "qwen3-vl:4b", route="Ollama chat API", kind="image 'sign.png'") + + +def test_anthropic_refuses_instead_of_sending_text_alone(tmp_path, monkeypatch): + pytest.importorskip("anthropic") + from abstractcore.media import handlers + from abstractcore.providers.anthropic_provider import AnthropicProvider + + p = AnthropicProvider(model="claude-haiku-4-5", api_key="test-key-not-used") + monkeypatch.setattr(handlers, "AnthropicMediaHandler", _Boom) + monkeypatch.setattr(p, "_process_media_content", lambda media, **k: list(media)) + monkeypatch.setattr(p.client.messages, "create", _no_network) + with pytest.raises(UnsupportedFeatureError) as e: + p._generate_internal("Describe it.", media=[_image(tmp_path)]) + _assert_named(e.value, "claude-haiku-4-5", route="Anthropic messages API", kind="image") + + +class _FakeLlama: + chat_format = "chat_template.default" + metadata = {} + + def __bool__(self): + return True + + def create_chat_completion(self, **k): + _no_network() + + +def _gguf(model: str): + from abstractcore.architectures import detect_architecture, get_architecture_format, get_model_capabilities + from abstractcore.providers.huggingface_provider import HuggingFaceProvider + from abstractcore.tools import UniversalToolHandler + import logging + + p = HuggingFaceProvider.__new__(HuggingFaceProvider) + p.model = model + p.model_type = "gguf" + p.logger = logging.getLogger("test") + p.__dict__["_llm_own"] = _FakeLlama() + p.tool_handler = UniversalToolHandler(model) + p.architecture = detect_architecture(model) + p.architecture_config = get_architecture_format(p.architecture) + p.model_capabilities = get_model_capabilities(model) + return p + + +def test_gguf_refuses_an_image_it_has_no_projector_for(tmp_path): + """A sighted GGUF got `{"type": "image"}` parts the template rendered as markers with + nothing behind them: the model was told a picture was there and never saw it.""" + p = _gguf("LiquidAI/LFM3-VL-2B-GGUF") + with pytest.raises(UnsupportedFeatureError) as e: + p._generate_gguf("What does the sign say?", media=[_image(tmp_path)]) + _assert_named(e.value, "LiquidAI/LFM3-VL-2B-GGUF", route="GGUF through llama-cpp-python", kind="image 'sign.png'") + + +def test_gguf_refuses_audio_for_any_model(tmp_path): + p = _gguf("LiquidAI/LFM3-1.7B-GGUF") + with pytest.raises(UnsupportedFeatureError) as e: + p._generate_gguf("What is said?", media=[_audio(tmp_path)]) + _assert_named(e.value, "LiquidAI/LFM3-1.7B-GGUF", route="GGUF through llama-cpp-python", kind="audio") + + +def test_local_text_embedding_never_writes_an_audio_path_as_content(tmp_path): + from abstractcore.media.base import UnsupportedMediaTypeError + from abstractcore.media.handlers import LocalMediaHandler + + h = LocalMediaHandler("huggingface", None, model_name="LiquidAI/LFM3-1.7B") + with pytest.raises(UnsupportedMediaTypeError, match="audio attachment 'question.wav'") as e: + h.create_multimodal_message("What is said?", [_audio(tmp_path)]) + assert "audio_policy='speech_to_text'" in str(e.value) # what to do next (re-check N12) + + +def test_an_unreadable_attachment_is_an_error_not_a_skip(tmp_path): + from abstractcore.providers.openai_compatible_provider import OpenAICompatibleProvider + + p = OpenAICompatibleProvider(model="some-model", base_url="http://127.0.0.1:9/v1") + with pytest.raises(UnsupportedFeatureError) as e: + p._process_media_content([str(tmp_path / "missing.png")]) + assert "missing.png" in str(e.value) and "some-model" in str(e.value) + + +def test_ollama_plain_prompt_with_media_uses_the_route_that_carries_it(tmp_path, monkeypatch): + """Without tools, messages or thinking, Ollama used `/api/generate`, which never sends + attachments: the picture was ignored without a word.""" + from abstractcore.providers.ollama_provider import OllamaProvider + + p = OllamaProvider(model="qwen3-vl:4b", base_url="http://127.0.0.1:9") + seen = {} + + def fake_single(endpoint, payload, *a, **k): + seen["endpoint"], seen["payload"] = endpoint, payload + from abstractcore.core.types import GenerateResponse + + return GenerateResponse(content="ok", model="qwen3-vl:4b") + + monkeypatch.setattr(p, "_single_generate", fake_single) + media = p._process_media_content([str(_image(tmp_path).file_path)]) + p._generate_internal("Describe it.", media=media) + assert seen["endpoint"] == "/api/chat" + assert any(m.get("images") for m in seen["payload"]["messages"]), seen["payload"] + + +def test_a_vision_message_that_cannot_carry_an_attachment_raises(tmp_path): + """Ollama's message format carries base64 images only: a file-path image (or a + document beside a picture) used to be left out with a warning in the log.""" + from abstractcore.architectures import get_model_capabilities + from abstractcore.media.base import MediaProcessingError + from abstractcore.media.handlers import LocalMediaHandler + h = LocalMediaHandler("ollama", get_model_capabilities("qwen3-vl:4b"), model_name="qwen3-vl:4b") + with pytest.raises(MediaProcessingError, match="image 'sign.png' \\(file_path\\)"): + h.create_multimodal_message("Describe it.", [_image(tmp_path)]) + + +# --- Streamed requests refuse at the call, before any iteration (review 2nd pass, 2026-12-01) --- +# Core's server prepares a streamed request by calling the provider before the response starts, so a +# refusal must be raised by the `generate(..., stream=True)` call itself, never at the first `next()`. + + +def test_openai_compatible_stream_refuses_at_the_call(tmp_path, monkeypatch): + from abstractcore.providers.openai_compatible_provider import OpenAICompatibleProvider + + p = OpenAICompatibleProvider(model="lfm3-omni-2b", base_url="http://127.0.0.1:9/v1") + monkeypatch.setattr(p, "_get_media_handler_for_model", lambda model: _Boom()) + monkeypatch.setattr(p, "_process_media_content", lambda media, *a, **k: list(media)) + monkeypatch.setattr(p.client, "post", _no_network) + monkeypatch.setattr(p.client, "stream", _no_network, raising=False) + with pytest.raises(UnsupportedFeatureError): + p.generate("What is in it?", media=[_image(tmp_path)], stream=True) # no iteration + + +def test_ollama_stream_refuses_at_the_call(tmp_path, monkeypatch): + from abstractcore.media import handlers + from abstractcore.providers.ollama_provider import OllamaProvider + + p = OllamaProvider(model="qwen3-vl:4b", base_url="http://127.0.0.1:9") + monkeypatch.setattr(handlers, "LocalMediaHandler", _Boom) + monkeypatch.setattr(p, "_process_media_content", lambda media, *a, **k: list(media)) + monkeypatch.setattr(p.client, "post", _no_network) + monkeypatch.setattr(p.client, "stream", _no_network, raising=False) + with pytest.raises(UnsupportedFeatureError): + p.generate("Describe it.", media=[_image(tmp_path)], stream=True) + + +def test_anthropic_stream_refuses_at_the_call(tmp_path, monkeypatch): + pytest.importorskip("anthropic") + from abstractcore.media import handlers + from abstractcore.providers.anthropic_provider import AnthropicProvider + + p = AnthropicProvider(model="claude-haiku-4-5", api_key="test-key-not-used") + monkeypatch.setattr(handlers, "AnthropicMediaHandler", _Boom) + monkeypatch.setattr(p, "_process_media_content", lambda media, *a, **k: list(media)) + monkeypatch.setattr(p.client.messages, "create", _no_network) + monkeypatch.setattr(p.client.messages, "stream", _no_network, raising=False) + with pytest.raises(UnsupportedFeatureError): + p.generate("Describe it.", media=[_image(tmp_path)], stream=True) + + +def test_gguf_stream_refuses_at_the_call(tmp_path): + p = _gguf("LiquidAI/LFM3-1.7B-GGUF") + with pytest.raises(UnsupportedFeatureError): + p._generate_gguf("What is said?", media=[_audio(tmp_path)], stream=True) + + +def test_a_missing_file_refuses_at_the_call_for_a_streamed_request(tmp_path): + from abstractcore.providers.openai_compatible_provider import OpenAICompatibleProvider + + p = OpenAICompatibleProvider(model="some-model", base_url="http://127.0.0.1:9/v1") + with pytest.raises(UnsupportedFeatureError): + p.generate("hi", media=[str(tmp_path / "missing.png")], stream=True) diff --git a/tests/media_handling/test_unreadable_attachment_unit.py b/tests/media_handling/test_unreadable_attachment_unit.py new file mode 100644 index 00000000..131f5845 --- /dev/null +++ b/tests/media_handling/test_unreadable_attachment_unit.py @@ -0,0 +1,115 @@ +"""A file that cannot be read is an error, never a placeholder (LFM3 fix round, 2026-12-01). + +Before: `AutoMediaHandler` caught every processor failure and returned `[Document: name]` +(or `[Image: name]`) with success, so every provider sent that placeholder to the model as +the file's content: a corrupt PDF or DOCX, a PDF without its reader, a DOCX without its +reader (then read as text: the zip archive's bytes). A binary file of a type AbstractCore +has no reader for (.zip, .bin, .tgs) was read as text too: its raw bytes went in. +Now the reader's own error comes back, naming the file, its kind and the cause, and the +provider refuses the request (`UnsupportedFeatureError`) before anything is sent. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from abstractcore.exceptions import UnsupportedFeatureError +from abstractcore.media.auto_handler import AutoMediaHandler + + +def _provider(): + from abstractcore.providers.openai_compatible_provider import OpenAICompatibleProvider + + return OpenAICompatibleProvider(model="some-model", base_url="http://127.0.0.1:9/v1") + + +def _refused(path: Path) -> str: + result = AutoMediaHandler(enable_glyph_compression=False).process_file(path) + assert not result.success, f"{path.name} was 'read' as {result.media_content.content!r}" + with pytest.raises(UnsupportedFeatureError) as e: + _provider()._process_media_content([str(path)]) + message = str(e.value) + assert path.name in message and "some-model" in message and "not sent without it" in message + return message + + +def test_a_corrupt_pdf_is_refused(tmp_path): + f = tmp_path / "report.pdf" + f.write_bytes(b"%PDF-1.7\nthis is not a pdf body") + message = _refused(f) + assert "Cannot read document file 'report.pdf': Failed to process PDF" in message + assert "Attach a valid copy (or a text or PDF version), or remove it" in message # what to do next + assert "the attached file 'report.pdf'" in message # not "the attached attachment" + + +def _office_reader_without_importing_unstructured(monkeypatch, *, available: bool): + """The OfficeProcessor imports `unstructured`'s partitioners when it is built, and unstructured 0.18 + (what Python 3.9/3.10 resolve) downloads NLTK data from raw.githubusercontent.com at that import: + a unit test must not. The reader's availability is set here instead; its parse is the stub below.""" + from abstractcore.media.processors.office_processor import OfficeProcessor + + monkeypatch.setattr(OfficeProcessor, "_check_dependencies", + lambda self: setattr(self, "_unstructured_available", available)) + + def _parse_fails(self, file_path, **kwargs): + # What unstructured's partition_docx raises for a file that is not a ZIP container. + raise ValueError(f"not a ZIP archive (so not a DOCX file): {str(file_path)!r}") + + monkeypatch.setattr(OfficeProcessor, "_process_docx", _parse_fails) + + +def test_a_corrupt_docx_is_refused(tmp_path, monkeypatch): + _office_reader_without_importing_unstructured(monkeypatch, available=True) + f = tmp_path / "notes.docx" + f.write_bytes(b"PK\x03\x04 not really a docx") + message = _refused(f) + assert "Cannot read document file 'notes.docx'" in message and "not a ZIP archive" in message + + +def test_a_pdf_without_its_reader_says_what_to_install(tmp_path, monkeypatch): + import abstractcore.media.processors.pdf_processor as pdf + + def _missing(): + raise pdf.MediaProcessingError(f"pypdf is required for default PDF processing. {pdf.PYPDF_INSTALL_HINT}") + + monkeypatch.setattr(pdf, "_load_pypdf_reader", _missing) + f = tmp_path / "report.pdf" + f.write_bytes(b"%PDF-1.7\n") + message = _refused(f) + assert "pypdf is required" in message and "pip install" in message + + +def test_a_docx_without_its_reader_says_what_to_install(tmp_path, monkeypatch): + _office_reader_without_importing_unstructured(monkeypatch, available=False) + f = tmp_path / "notes.docx" + f.write_bytes(b"PK\x03\x04 a zip archive") + message = _refused(f) + assert "Unstructured library not available" in message and "pip install" in message + assert "PK" not in message + + +@pytest.mark.parametrize("name,data", [("a.zip", b"PK\x03\x04\x00\x00\x00binary"), ("blob.bin", b"\x00\x01\x02\xff" * 8)]) +def test_an_unknown_binary_type_is_refused(tmp_path, name, data): + f = tmp_path / name + f.write_bytes(data) + suffix = Path(name).suffix + message = _refused(f) + assert f"AbstractCore has no reader for binary {suffix} files. Remove it, or attach a text or PDF version" in message + + +def test_a_broken_image_is_refused(tmp_path): + f = tmp_path / "broken.png" + f.write_bytes(b"\x89PNG\r\n\x1a\n not an image") + assert "Cannot read image file 'broken.png'" in _refused(f) + + +def test_readable_files_still_read(tmp_path): + """The text reader still serves text documents, known or not by extension.""" + for name, text in (("note.txt", "hello"), ("letter.rtf", "{\\rtf1 hello}"), ("data.unknownext", "plain hello")): + f = tmp_path / name + f.write_text(text) + result = AutoMediaHandler(enable_glyph_compression=False).process_file(f) + assert result.success, (name, result.error_message) + assert "hello" in str(result.media_content.content), name diff --git a/tests/providers/test_gguf_boundary_snapshot_unit.py b/tests/providers/test_gguf_boundary_snapshot_unit.py index bd05ac52..452d22bc 100644 --- a/tests/providers/test_gguf_boundary_snapshot_unit.py +++ b/tests/providers/test_gguf_boundary_snapshot_unit.py @@ -461,7 +461,7 @@ def test_generation_prompt_boundary_is_derived_from_the_renderer(): full = _turn(2) head = full[: _generation_boundary(2)] - def _render(*, messages, add_generation_prompt, enable_thinking=None, reasoning_effort=None): + def _render(*, messages, add_generation_prompt, enable_thinking=None, reasoning_effort=None, tools=None): return ("", full if add_generation_prompt else head) p._gguf_render_prompt_tokens = _render # type: ignore[assignment] diff --git a/tests/providers/test_gguf_structured_response_format_unit.py b/tests/providers/test_gguf_structured_response_format_unit.py new file mode 100644 index 00000000..c3dec2ca --- /dev/null +++ b/tests/providers/test_gguf_structured_response_format_unit.py @@ -0,0 +1,158 @@ +"""GGUF native structured output is constrained by llama.cpp (LFM3 fix round, 2026-12-01). + +`_generate_gguf` sent `response_format={"type": "json_schema", "json_schema": {...}}`. llama-cpp-python's +chat handlers build a grammar only for `{"type": "json_object"}`, from its `schema` key +(`llama_chat_format._grammar_for_response_format`, 0.3.38), so the "native" request was an +unconstrained generation and the structured handler re-ran every request on the prompted lane +(measured on LFM3-1.7B: 3 native + 3 prompted generations for 3 requests). No model: the llama +object is a stub that records what it is asked. +""" +from __future__ import annotations + +import logging + +import pytest +from pydantic import BaseModel + + +class Person(BaseModel): + name: str + age: int + + +class _RecordingLlama: + chat_format = "chat_template.default" + metadata = {} + + def __init__(self): + self.seen = {} + + def __bool__(self): + return True + + def create_chat_completion(self, **k): + self.seen.update(k) + return {"choices": [{"message": {"role": "assistant", "content": '{"name": "Ada", "age": 36}'}, + "finish_reason": "stop"}], + "usage": {"prompt_tokens": 5, "completion_tokens": 9, "total_tokens": 14}} + + +def _gguf(model: str): + from abstractcore.architectures import detect_architecture, get_architecture_format, get_model_capabilities + from abstractcore.providers.huggingface_provider import HuggingFaceProvider + from abstractcore.tools import UniversalToolHandler + + p = HuggingFaceProvider.__new__(HuggingFaceProvider) + p.model = model + p.model_type = "gguf" + p.logger = logging.getLogger("test") + p.__dict__["_llm_own"] = _RecordingLlama() + p.tool_handler = UniversalToolHandler(model) + p.architecture = detect_architecture(model) + p.architecture_config = get_architecture_format(p.architecture) + p.model_capabilities = get_model_capabilities(model) + p.max_tokens, p.max_output_tokens, p.temperature, p.top_p, p.seed = 8192, 256, 0.0, 1.0, None + p.max_input_tokens = None + return p + + +def test_the_response_format_is_the_shape_llama_cpp_constrains(): + p = _gguf("bartowski/Llama-3.2-3B-Instruct-GGUF") + p._generate_gguf("Ada is 36. Extract the person.", response_model=Person) + rf = p.__dict__["_llm_own"].seen["response_format"] + assert rf == {"type": "json_object", "schema": Person.model_json_schema()} + chat_format = pytest.importorskip("llama_cpp.llama_chat_format") + assert chat_format._grammar_for_response_format(rf) is not None + # the shape sent before: no grammar at all + assert chat_format._grammar_for_response_format( + {"type": "json_schema", "json_schema": {"name": "Person", "schema": Person.model_json_schema()}}) is None + + +# --- N2 (re-check 2026-12-01): a template that opens costs ONE generation --------- + +from abstractcore.structured.handler import StructuredOutputHandler + +# Ours, a few lines: ChatML turns and a generation prompt that opens a thinking block, as LFM3's template +# does by default (`enable_thinking | default(true)` -> ``). That is all this test needs. +_OPENS_THINKING_TEMPLATE = ( + "{{ bos_token }}{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{% endfor %}" + "{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}" +) + + +class _TemplateLlama(_RecordingLlama): + """Answers like a grammar-constrained llama.cpp: the JSON from the first token when a + response_format is given; otherwise a short reasoning closed by the model, then the JSON.""" + + def __init__(self, template): + super().__init__() + self.metadata = {"tokenizer.chat_template": template} if template else {} + self.calls = [] + + def token_bos(self): + return 1 + + def token_eos(self): + return 2 + + def detokenize(self, toks, special=False): + return {1: b"<|startoftext|>", 2: b"<|im_end|>"}.get(toks[0], b"") + + def tokenize(self, b, add_bos=False, special=True): + return [5] + + def create_chat_completion(self, **k): + self.calls.append(bool(k.get("response_format"))) + content = '{"name": "Ada", "age": 36}' if k.get("response_format") or not self.metadata else \ + 'Ada is 36.{"name": "Ada", "age": 36}' + return {"choices": [{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 5, "completion_tokens": 9, "total_tokens": 14}} + + +@pytest.mark.parametrize("model,template,constrained", [ + ("LiquidAI/LFM3-1.7B-GGUF", _OPENS_THINKING_TEMPLATE, False), # the prompt opens : one prompted generation + ("bartowski/Llama-3.2-3B-Instruct-GGUF", "", True), # no thinking block: one constrained generation +]) +def test_structured_output_is_one_generation(model, template, constrained): + if template: + # Whether the prompt opens a thinking block is read by rendering the template through + # llama-cpp-python's Jinja2ChatFormatter (the CI's [test] install has no llama-cpp-python). + pytest.importorskip("llama_cpp") + p = _gguf(model) + p.__dict__["_llm_own"] = _TemplateLlama(template) + out = StructuredOutputHandler().generate_structured(p, "Ada is 36. Extract the person.", Person) + assert out == Person(name="Ada", age=36) + assert p.__dict__["_llm_own"].calls == [constrained] + + +# --- Review 2nd pass S3: the prompted structured request keeps the thinking control --------- + + +class _ChatLlama(_TemplateLlama): + """With what the control plane's render needs (token texts).""" + + class _Model: + @staticmethod + def token_get_text(token_id): + return {1: "<|startoftext|>", 2: "<|im_end|>"}[token_id] + + _model = _Model() + + +def test_a_structured_request_behind_a_thinking_template_can_switch_thinking_off(): + """LFM3 GGUF: the structured request takes the prompted lane (the template opens ), an ordinary + text request, so `thinking="off"` is honoured on it like on any other (it was declined because a + structured request used to mean llama.cpp's constrained output, and LFM3 then reasoned ~4 s first).""" + pytest.importorskip("llama_cpp") + p = _gguf("LiquidAI/LFM3-1.7B-GGUF") + p.__dict__["_llm_own"] = _ChatLlama(_OPENS_THINKING_TEMPLATE) + assert p.gguf_constrained_output_lands_in_thinking() is True + new_kwargs, handling = p._apply_provider_thinking_kwargs( + enabled=False, level=None, kwargs={}, request_shape={"has_response_model": True}) + assert handling.handled_enable_disable is True and new_kwargs.get("_acore_gguf_enable_thinking") is False + # A template whose prompt opens no thinking block keeps the constrained lane, where the switch has no + # transport: declined, as before. + q = _gguf("bartowski/Llama-3.2-3B-Instruct-GGUF") + _, handling = q._apply_provider_thinking_kwargs( + enabled=False, level=None, kwargs={}, request_shape={"has_response_model": True}) + assert handling.handled_enable_disable is False diff --git a/tests/providers/test_gguf_template_tools_declared_format_unit.py b/tests/providers/test_gguf_template_tools_declared_format_unit.py new file mode 100644 index 00000000..a534b2de --- /dev/null +++ b/tests/providers/test_gguf_template_tools_declared_format_unit.py @@ -0,0 +1,65 @@ +"""Which GGUF families get their template's own tool block and `tool` turns (LFM3 fix round, 2026-12-01). + +The first LFM3 change handed every GGUF whose embedded template renders `tools` the template's own +tool block, and let `tool` turns ride the controlled lane for every embedded-template GGUF; it was +proved on LFM3 only. The parsers read a family's calls in the syntax its registry declares, which is +not always what its template teaches (Llama 3.1 teaches a bare JSON object, which the stream does not +detect; Mistral `[TOOL_CALLS]...`). So both are now opt-in per MODEL, declared in +`model_capabilities.json` (`gguf_template_tools: true`, today LFM3-1.7B only: its VL, Audio and Omni +siblings' templates differ or were never run with tools); every other GGUF keeps +AbstractCore's prompted block and the 2.41.0 lanes. No model, no llama.cpp: the llama object is a stub +whose `chat_format` is the one llama-cpp-python gives a GGUF whose name has no "qwen"/"coder" +(`chat_template.default`); Qwen-named GGUFs load as `chatml-function-calling` and never reach this. +""" +from __future__ import annotations + +import types + +import pytest + +from abstractcore.architectures import detect_architecture, get_architecture_format, get_model_capabilities +from abstractcore.providers.huggingface_provider import HuggingFaceProvider +from abstractcore.tools.handler import create_handler + +TEMPLATE = "{% if tools %}{% for t in tools %}{{ t | tojson }}{% endfor %}{% endif %}<|im_start|>{{ messages }}<|im_end|>" +TOOLS = [{"name": "get_weather", "description": "w", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}}] + + +def _provider(model: str) -> HuggingFaceProvider: + p = object.__new__(HuggingFaceProvider) + p.model = model + p.llm = types.SimpleNamespace(chat_format="chat_template.default", metadata={"tokenizer.chat_template": TEMPLATE}) + p.tool_handler = create_handler(model) + p.architecture_config = get_architecture_format(detect_architecture(model)) + p.model_capabilities = get_model_capabilities(model) + return p + + +def test_the_opted_in_family_gets_the_template_tool_block_and_tool_turns(monkeypatch): + p = _provider("LiquidAI/LFM3-1.7B-GGUF") + tools = p._gguf_template_tools(TOOLS) + assert tools and tools[0]["function"]["name"] == "get_weather" + monkeypatch.setattr(p, "_gguf_prompt_cache_control_plane_chat_format", lambda: "llama-cpp-chat-template") + assert "tool" in p._gguf_control_plane_roles() + + +@pytest.mark.parametrize("model", [ + "LiquidAI/LFM3-VL-2B-GGUF", "LiquidAI/LFM3-Omni-2B-GGUF", "LiquidAI/LFM3-Audio-2B-GGUF", + "unsloth/gemma-4-E4B-it-GGUF", "bartowski/Llama-3.2-3B-Instruct-GGUF", "bartowski/Mistral-7B-Instruct-v0.3-GGUF", + "bartowski/granite-3.3-8b-instruct-GGUF", "some-org/unknown-model-GGUF", +]) +def test_every_other_family_keeps_the_prompted_block_and_the_2_41_lanes(model, monkeypatch): + p = _provider(model) + assert p.model_capabilities.get("gguf_template_tools") is None + assert p._gguf_template_tools(TOOLS) is None + monkeypatch.setattr(p, "_gguf_prompt_cache_control_plane_chat_format", lambda: "llama-cpp-chat-template") + assert "tool" not in p._gguf_control_plane_roles() + + +def test_only_lfm3_1_7b_is_opted_in_today(): + from abstractcore.architectures import detection + + detection._load_json_assets() + opted = sorted(k for k, v in detection._model_capabilities["models"].items() if v.get("gguf_template_tools")) + assert opted == ["lfm3-1.7b"] + assert not any(v.get("gguf_template_tools") for v in detection._architecture_formats["architectures"].values()) diff --git a/tests/providers/test_hf_instance_worker_cancel_unit.py b/tests/providers/test_hf_instance_worker_cancel_unit.py new file mode 100644 index 00000000..b659346a --- /dev/null +++ b/tests/providers/test_hf_instance_worker_cancel_unit.py @@ -0,0 +1,78 @@ +"""A call stopped while it waited for a busy shared Hugging Face model never generates (2026-12-01). + +`_InstanceGenerationWorker` runs every operation on one provider instance's model on one worker thread. +A shared instance (a host pool serving two runs, the server lending a resident model) makes a call +wait behind another run. A caller that stopped meanwhile (its cancel event set: a client that left) +used to start its generation anyway once the worker was free. Now the queued call raises +`GenerationCancelledError` without running, streamed (`stream`) and not (`run`). No model. +""" +from __future__ import annotations + +import threading + +import pytest + +from abstractcore.exceptions import GenerationCancelledError +from abstractcore.providers.huggingface_provider import _InstanceGenerationWorker +from tests.timing import patient + +LIMIT = patient(20.0) + + +def _hold(worker: _InstanceGenerationWorker): + """Another run holds the worker until the returned event is set (deterministic: no sleeps).""" + released, holding = threading.Event(), threading.Event() + + def run(): + holding.set() + released.wait(LIMIT) + + holder = threading.Thread(target=lambda: worker.run(run), daemon=True) + holder.start() + assert holding.wait(LIMIT) + return released, holder + + +@pytest.mark.parametrize("streamed", [False, True], ids=["run", "stream"]) +def test_a_call_cancelled_while_queued_never_runs(streamed): + worker = _InstanceGenerationWorker("test-cancel-queued") + released, holder = _hold(worker) + ran, outcome = [], {} + cancel = threading.Event() + + def call(): + ran.append(1) + return iter(["x"]) if streamed else "x" + + def caller(): + try: + result = worker.stream(call, cancel_event=cancel) if streamed else worker.run(call, cancel_event=cancel) + outcome["result"] = list(result) if streamed else result + except GenerationCancelledError as exc: + outcome["cancelled"] = exc + + t = threading.Thread(target=caller, daemon=True) + t.start() + cancel.set() # the caller stops while the holder still has the model (queued or about to queue) + released.set() + holder.join(LIMIT) + t.join(LIMIT) + assert ran == [] and "cancelled" in outcome, outcome + + +@pytest.mark.parametrize("streamed", [False, True], ids=["run", "stream"]) +def test_a_call_not_cancelled_still_runs_after_the_holder(streamed): + worker = _InstanceGenerationWorker("test-not-cancelled") + released, holder = _hold(worker) + out = {} + + def caller(): + result = worker.stream(lambda: iter(["x"])) if streamed else worker.run(lambda: "x") + out["result"] = list(result) if streamed else result + + t = threading.Thread(target=caller, daemon=True) + t.start() + released.set() + t.join(LIMIT) + holder.join(LIMIT) + assert out["result"] == (["x"] if streamed else "x") diff --git a/tests/providers/test_lfm3_prompt_parity_unit.py b/tests/providers/test_lfm3_prompt_parity_unit.py new file mode 100644 index 00000000..ea5b360c --- /dev/null +++ b/tests/providers/test_lfm3_prompt_parity_unit.py @@ -0,0 +1,431 @@ +"""LFM3-1.7B: the prompt AbstractCore sends equals the model's own chat template (2026-11-30, 2026-12-01). + +Liquid's chat templates are files of model repositories under the LFM Open License, so this repository +holds no copy of them. Two kinds of checks: + +1. Against the OFFICIAL templates, read-only from the operator's local Hugging Face cache (skipped, never + passed, when the model is not downloaded): + - GGUF: the template embedded in `LiquidAI/LFM3-1.7B-GGUF` (`LFM3-1.7B-Q4_K_M.gguf`, metadata + `tokenizer.chat_template`; byte-identical to `chat_template.jinja` of `LiquidAI/LFM3-1.7B`, used when the + `gguf` reader is not installed); + - MLX: `chat_template.jinja` of `LiquidAI/LFM3-1.7B-MLX-4bit`. + Each case is rendered by the official template from canonical OpenAI-shaped input and compared byte for + byte with what AbstractCore renders from its own inputs through each lane's real code path (MLX: + `MLXProvider._build_prompt_fragment` over a tokenizer that renders the template; GGUF: + `_gguf_build_chat_messages` + `_gguf_render_prompt_text` through llama-cpp-python's `Jinja2ChatFormatter`). + +2. Without the cache (CI): `tests/fixtures/lfm3/rendered_prompts.json` records, for the same cases, the + PROMPTS the official templates render (the wire format, a fact about the model, not the template's code) + and the INPUTS AbstractCore hands each lane's renderer (messages, tools, thinking switch). CI checks that + AbstractCore still hands exactly those inputs (captured through a recorder template of our own, written + here, on the same code path), that the hand-built `lfm3` renderer matches the recorded prompt where it + applies, and the wire facts in the recorded prompts. With the cache present, (1) also checks that the + official template renders the recorded inputs into the recorded prompts, so the recording cannot drift. + +Recorded from: `LiquidAI/LFM3-1.7B-GGUF@cd0c74c575b5c416f3011b5b4c298077f26ca8c2` (template sha256 +f45005c5..., also `LiquidAI/LFM3-1.7B@1da06bec6a819da10b54c67e5c90972b46d81871`) and +`LiquidAI/LFM3-1.7B-MLX-4bit@91f34088d6946482cbcae11b85d4657093618c34` (sha256 306497f1...), 2026-12-01. +Regenerate (with both repositories in the local cache): `python tests/providers/test_lfm3_prompt_parity_unit.py +--regenerate`. +""" + +from __future__ import annotations + +import copy +import functools +import glob +import hashlib +import json +import os +import sys +from pathlib import Path +from typing import Any, Dict, List, Optional + +import pytest + +jinja2 = pytest.importorskip("jinja2") +from jinja2.ext import Extension, loopcontrols # noqa: E402 +from jinja2.sandbox import ImmutableSandboxedEnvironment # noqa: E402 + +pytestmark = pytest.mark.real_home( + "reads the LiquidAI/LFM3-1.7B-GGUF and -MLX-4bit chat templates from the Hugging Face cache (read-only); " + "the recorded-prompt tests need no cache" +) + +RECORDED_PATH = Path(__file__).resolve().parents[1] / "fixtures" / "lfm3" / "rendered_prompts.json" +BOS, EOS = "<|startoftext|>", "<|im_end|>" +MLX_MODEL = "LiquidAI/LFM3-1.7B-MLX-4bit" +GGUF_MODEL = "LiquidAI/LFM3-1.7B-GGUF:Q4_K_M" + +# Ours (a few lines written here, no model's code): every input it was given as JSON in a first block, then +# plain ChatML turns, which the GGUF lane's renderability probe requires. Used to capture what AbstractCore +# hands a template, on the real code path, without the official one. +RECORDER_TEMPLATE = ( + '{{ bos_token }}<|im_start|>inputs\n{{ {"messages": messages, "tools": tools, ' + '"enable_thinking": (enable_thinking if enable_thinking is defined else none), ' + '"add_generation_prompt": add_generation_prompt} | tojson }}<|im_end|>\n' + "{% for m in messages %}<|im_start|>{{ m.role }}\n" + "{{ m.content if m.content is string else '' }}<|im_end|>\n{% endfor %}" + "{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}" +) + + +# --- the official templates, from the local cache only ------------------------------------ + + +def _hub() -> str: + """Under pytest the operator's real home (the conftest moves HOME and HF_HUB_CACHE to a tmp folder and + hands the real home over read-only, `real_home`); run as a script (`--regenerate`), HF_HUB_CACHE.""" + real_home = os.environ.get("ABSTRACT_TEST_REAL_HOME") + if real_home: + return os.path.join(real_home, ".cache", "huggingface", "hub") + return os.environ.get("HF_HUB_CACHE") or os.path.join(os.path.expanduser("~"), ".cache", "huggingface", "hub") + + +def _snapshot_file(repo: str, name: str) -> Optional[str]: + root = os.path.join(_hub(), "models--" + repo.replace("/", "--"), "snapshots") + hits = sorted(glob.glob(os.path.join(root, "*", name))) + return hits[0] if hits else None + + +@functools.lru_cache(maxsize=None) +def _gguf_template() -> Optional[str]: + path = _snapshot_file("LiquidAI/LFM3-1.7B-GGUF", "LFM3-1.7B-Q4_K_M.gguf") + if path: + try: + from gguf import GGUFReader + + field = GGUFReader(path).fields["tokenizer.chat_template"] + return bytes(field.parts[field.data[0]]).decode("utf-8") + except ImportError: + pass + path = _snapshot_file("LiquidAI/LFM3-1.7B", "chat_template.jinja") # the same bytes the GGUF embeds + return Path(path).read_text(encoding="utf-8") if path else None + + +@functools.lru_cache(maxsize=None) +def _mlx_template() -> Optional[str]: + path = _snapshot_file("LiquidAI/LFM3-1.7B-MLX-4bit", "chat_template.jinja") + return Path(path).read_text(encoding="utf-8") if path else None + + +def _need(template: Optional[str], repo: str) -> str: + if template is None: + pytest.skip(f"{repo} is not in the local Hugging Face cache ({_hub()}): its chat template is read from " + "there, never copied into this repository") + return template + + +class _Generation(Extension): + """transformers' `{% generation %}` tag: renders its body.""" + + tags = {"generation"} + + def parse(self, parser): + parser.stream.skip(1) + return parser.parse_statements(("name:endgeneration",), drop_needle=True) + + +def official(template: str, messages, *, tools=None, add_generation_prompt=True, **kwargs) -> str: + """Render with the Jinja settings transformers and llama-cpp-python both use.""" + env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, extensions=[_Generation, loopcontrols]) + env.filters["tojson"] = lambda x, ensure_ascii=False, indent=None, separators=None, sort_keys=False: json.dumps( + x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys + ) + + def raise_exception(message): + raise jinja2.exceptions.TemplateError(message) + + env.globals["raise_exception"] = raise_exception + return env.from_string(template).render( + messages=messages, tools=tools, bos_token=BOS, eos_token=EOS, + add_generation_prompt=add_generation_prompt, **kwargs, + ) + + +# --- the conversations ------------------------------------------------------------------ + +SYSTEM = "You are a concise assistant. Answer in plain sentences." +CORE_TOOLS = [ + {"name": "get_weather", "description": "Get the current weather for a city.", + "parameters": {"city": {"type": "string", "description": "City name"}, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "default": "celsius"}}}, + {"name": "get_time", "description": "Get the current local time in an IANA time zone.", + "parameters": {"timezone": {"type": "string", "description": "IANA zone, e.g. Europe/Paris"}}}, +] +OFFICIAL_TOOLS = [ + {"type": "function", "function": { + "name": "get_weather", "description": "Get the current weather for a city.", + "parameters": {"type": "object", "properties": { + "city": {"type": "string", "description": "City name"}, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "default": "celsius"}}, + "required": ["city"]}}}, + {"type": "function", "function": { + "name": "get_time", "description": "Get the current local time in an IANA time zone.", + "parameters": {"type": "object", "properties": { + "timezone": {"type": "string", "description": "IANA zone, e.g. Europe/Paris"}}, + "required": ["timezone"]}}}, +] +ASK = "What is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools." +CALLS = [("call_0", "get_weather", {"city": "Tokyo"}), ("call_1", "get_time", {"timezone": "Asia/Tokyo"})] +RESULTS = [{"city": "Tokyo", "temperature": 14, "unit": "celsius", "sky": "light rain"}, + {"timezone": "Asia/Tokyo", "time": "06:42"}] + + +def _round_trip(arguments_as_json: bool) -> List[Dict[str, Any]]: + """User ask, the assistant's two calls, the two tool results (one `tool` turn each).""" + msgs: List[Dict[str, Any]] = [{"role": "user", "content": ASK}, { + "role": "assistant", "content": "", + "tool_calls": [{"id": cid, "type": "function", + "function": {"name": name, "arguments": json.dumps(args) if arguments_as_json else args}} + for cid, name, args in CALLS]}] + for (cid, name, _), result in zip(CALLS, RESULTS): + msgs.append({"role": "tool", "tool_call_id": cid, "name": name, "content": json.dumps(result)}) + return msgs + + +HISTORY = [{"role": "user", "content": "My name is Ada and I keep three cats. Name a fourth?"}, + {"role": "assistant", "content": "How about Juniper?"}, + {"role": "user", "content": "How many cats will I have, and what is my name?"}] + +# id -> (system, core messages, core tools, official messages, official tools, enable_thinking) +CASES = { + "system_user_default": (SYSTEM, [{"role": "user", "content": "hi"}], None, + [{"role": "system", "content": SYSTEM}, {"role": "user", "content": "hi"}], None, None), + "thinking_off": (SYSTEM, [{"role": "user", "content": "hi"}], None, + [{"role": "system", "content": SYSTEM}, {"role": "user", "content": "hi"}], None, False), + "thinking_on": (SYSTEM, [{"role": "user", "content": "hi"}], None, + [{"role": "system", "content": SYSTEM}, {"role": "user", "content": "hi"}], None, True), + "multi_turn": (SYSTEM, HISTORY, None, [{"role": "system", "content": SYSTEM}] + HISTORY, None, None), + "tools_ask": (SYSTEM, [{"role": "user", "content": ASK}], CORE_TOOLS, + [{"role": "system", "content": SYSTEM}, {"role": "user", "content": ASK}], OFFICIAL_TOOLS, None), + "tool_results": (SYSTEM, _round_trip(True), CORE_TOOLS, + [{"role": "system", "content": SYSTEM}] + _round_trip(False), OFFICIAL_TOOLS, None), + "tool_results_thinking_off": (SYSTEM, _round_trip(True), CORE_TOOLS, + [{"role": "system", "content": SYSTEM}] + _round_trip(False), OFFICIAL_TOOLS, False), + "no_system_tools": (None, [{"role": "user", "content": ASK}], CORE_TOOLS, + [{"role": "user", "content": ASK}], OFFICIAL_TOOLS, None), +} + + +def _official(template: str, case: str) -> str: + _, _, _, msgs, tools, thinking = CASES[case] + kw = {} if thinking is None else {"enable_thinking": thinking} + return official(template, copy.deepcopy(msgs), tools=tools, **kw) + + +# --- each lane's real code path ------------------------------------------------------------ + + +class _Tokenizer: + """The MLX checkpoint's tokenizer, as far as rendering goes. `template=None`: records what it is + handed (the recorder), else renders that template.""" + + bos_token = BOS + + def __init__(self, template: Optional[str]): + self.chat_template = template if template is not None else RECORDER_TEMPLATE + self.recording = template is None + self.inputs: Dict[str, Any] = {} + + def apply_chat_template(self, messages, tokenize=False, add_generation_prompt=False, tools=None, **kwargs): + assert tokenize is False + if self.recording: + self.inputs = {"messages": copy.deepcopy(messages), "tools": copy.deepcopy(tools), + "enable_thinking": kwargs.get("enable_thinking"), "add_generation_prompt": add_generation_prompt} + return BOS + "<|im_start|>recorded<|im_end|>" + return official(self.chat_template, messages, tools=tools, add_generation_prompt=add_generation_prompt, **kwargs) + + +def _mlx_provider(template: Optional[str]): + from abstractcore.architectures import detect_architecture, get_architecture_format, get_model_capabilities + from abstractcore.providers.mlx_provider import MLXProvider + from abstractcore.tools import UniversalToolHandler + + p = MLXProvider.__new__(MLXProvider) + p.model = MLX_MODEL + p.tokenizer = _Tokenizer(template) + p.tool_handler = UniversalToolHandler(MLX_MODEL) + p.architecture = detect_architecture(MLX_MODEL) + p.architecture_config = get_architecture_format(p.architecture) + p.model_capabilities = get_model_capabilities(MLX_MODEL) + return p + + +def _mlx_render(case: str, template: Optional[str]): + system, msgs, tools, _, _, thinking = CASES[case] + p = _mlx_provider(template) + got = p._build_prompt_fragment(prompt="", messages=copy.deepcopy(msgs), system_prompt=system, tools=tools, + add_generation_prompt=True, enable_thinking=thinking) + return got, p.tokenizer.inputs + + +class _FakeModel: + def token_get_text(self, token_id): + return {1: BOS, 2: EOS}[token_id] + + +def _gguf_provider(template: str): + pytest.importorskip("llama_cpp") + from abstractcore.architectures import detect_architecture, get_architecture_format, get_model_capabilities + from abstractcore.providers.huggingface_provider import HuggingFaceProvider + from abstractcore.tools import UniversalToolHandler + + llama = type("_FakeLlama", (), { + "chat_format": "chat_template.default", + "metadata": {"tokenizer.chat_template": template, "general.architecture": "lfm3"}, + "_model": _FakeModel(), "token_bos": lambda self: 1, "token_eos": lambda self: 2, + })() + p = HuggingFaceProvider.__new__(HuggingFaceProvider) + p.model = GGUF_MODEL + p.model_type = "gguf" + p.__dict__["_llm_own"] = llama + p.tool_handler = UniversalToolHandler(GGUF_MODEL) + p.architecture = detect_architecture(GGUF_MODEL) + p.architecture_config = get_architecture_format(p.architecture) + p.model_capabilities = get_model_capabilities(GGUF_MODEL) + return p + + +def _gguf_render(case: str, template: str) -> str: + system, msgs, tools, _, _, thinking = CASES[case] + p = _gguf_provider(template) + assert p._gguf_prompt_cache_control_plane_chat_format() == "llama-cpp-chat-template" + chat = p._gguf_build_chat_messages(system_prompt=system, messages=copy.deepcopy(msgs), tools=tools, + user_message_content=None) + assert p._gguf_control_plane_can_stream(chat) # tool turns ride the controlled lane + return p._gguf_render_prompt_text(messages=chat, add_generation_prompt=True, enable_thinking=thinking, + tools=p._gguf_template_tools(tools)) + + +def _gguf_inputs(case: str) -> Dict[str, Any]: + out = _gguf_render(case, RECORDER_TEMPLATE) + start = out.index("<|im_start|>inputs\n") + len("<|im_start|>inputs\n") + return json.loads(out[start:out.index("<|im_end|>", start)]) # tojson escapes "<": no marker inside + + +def _recorded() -> Dict[str, Any]: + return json.loads(RECORDED_PATH.read_text(encoding="utf-8")) + + +# --- 1. against the official templates (local cache) -------------------------------------- + + +def test_the_reference_renders_what_the_engines_were_given(): + template = _need(_gguf_template(), "LiquidAI/LFM3-1.7B-GGUF") + assert official(template, [{"role": "user", "content": "hi"}]) == ( + "<|startoftext|><|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n") + assert official(template, [{"role": "user", "content": "hi"}], enable_thinking=False).endswith( + "<|im_start|>assistant\n") + + +@pytest.mark.parametrize("case", sorted(CASES)) +def test_mlx_prompt_equals_the_official_template(case): + template = _need(_mlx_template(), "LiquidAI/LFM3-1.7B-MLX-4bit") + got, _ = _mlx_render(case, template) + assert got == _official(template, case) + rec = _recorded()["cases"][case] + assert got == rec["mlx_prompt"] + inputs = rec["mlx_inputs"] + kw = {} if inputs["enable_thinking"] is None else {"enable_thinking": inputs["enable_thinking"]} + assert official(template, inputs["messages"], tools=inputs["tools"], **kw) == rec["mlx_prompt"] + + +@pytest.mark.parametrize("case", sorted(CASES)) +def test_gguf_prompt_equals_the_official_template(case): + template = _need(_gguf_template(), "LiquidAI/LFM3-1.7B-GGUF") + got = _gguf_render(case, template) + assert got == _official(template, case) + assert got == _recorded()["cases"][case]["gguf_prompt"] + + +def test_thinking_off_marker_is_the_templates_own(): + from abstractcore.architectures import get_architecture_format, get_model_capabilities + from abstractcore.architectures.thinking_controls import resolve_thinking_control_surfaces + + template = _need(_gguf_template(), "LiquidAI/LFM3-1.7B-GGUF") + off = official(template, [{"role": "user", "content": "x"}], enable_thinking=False) + marker = off[len(official(template, [{"role": "user", "content": "x"}], add_generation_prompt=False)) + + len("<|im_start|>assistant\n"):] + surfaces = resolve_thinking_control_surfaces( + model_capabilities=get_model_capabilities(MLX_MODEL), architecture_format=get_architecture_format("lfm3")) + assert surfaces.assistant_prefill_disable == marker == "" + assert surfaces.template_kwarg == "enable_thinking" + + +# --- 2. against the recorded prompts (no cache needed) ------------------------------------- + + +@pytest.mark.parametrize("case", sorted(CASES)) +def test_mlx_hands_the_template_the_recorded_inputs(case): + _, inputs = _mlx_render(case, None) + assert inputs == _recorded()["cases"][case]["mlx_inputs"] + + +@pytest.mark.parametrize("case", sorted(CASES)) +def test_gguf_hands_the_template_the_recorded_inputs(case): + assert _gguf_inputs(case) == _recorded()["cases"][case]["gguf_inputs"] + + +def test_the_recorded_prompts_carry_the_wire_format(): + cases = _recorded()["cases"] + for lane in ("gguf_prompt", "mlx_prompt"): + assert cases["system_user_default"][lane].startswith(BOS + "<|im_start|>system\n" + SYSTEM + EOS) + assert cases["system_user_default"][lane].endswith("<|im_start|>assistant\n") + assert cases["thinking_off"][lane].endswith("<|im_start|>assistant\n") + assert '\n{"name": "get_weather"' in cases["tools_ask"][lane] + assert "<|im_start|>tool\n\n" in cases["tool_results"][lane] + + +def test_hand_built_lfm3_format_opens_with_the_declared_bos(): + from abstractcore.architectures.detection import format_messages + + assert format_messages([{"role": "system", "content": "S"}, {"role": "user", "content": "hi"}], "lfm3") == ( + "<|startoftext|><|im_start|>system\nS<|im_end|>\n<|im_start|>user\nhi<|im_end|>\n") + + +def test_the_hand_built_renderer_matches_the_recorded_thinking_off_prompt(): + """A tokenizer without a chat template: the MLX provider's own renderer writes the declared BOS and + the declared thinking-off marker, exactly as the official template does for this case.""" + + class _NoTemplate: + bos_token = BOS + chat_template = None + + system, msgs, tools, _, _, thinking = CASES["thinking_off"] + p = _mlx_provider(None) + p.tokenizer = _NoTemplate() + got = p._build_prompt_fragment(prompt="", messages=copy.deepcopy(msgs), system_prompt=system, tools=tools, + add_generation_prompt=True, enable_thinking=thinking) + assert got == _recorded()["cases"]["thinking_off"]["mlx_prompt"] + + +# --- regeneration -------------------------------------------------------------------------- + + +def _regenerate() -> None: + gguf_t, mlx_t = _gguf_template(), _mlx_template() + if gguf_t is None or mlx_t is None: + raise SystemExit("both LiquidAI/LFM3-1.7B-GGUF and LiquidAI/LFM3-1.7B-MLX-4bit must be in the local cache") + out = {"_source": ( + "Prompts rendered by the official LFM3-1.7B chat templates for the cases of " + "tests/providers/test_lfm3_prompt_parity_unit.py, and the inputs AbstractCore hands each lane's " + "renderer. Templates (read from the local Hugging Face cache, not copied): GGUF embedded template sha256 " + f"{hashlib.sha256(gguf_t.encode()).hexdigest()}, MLX chat_template.jinja sha256 " + f"{hashlib.sha256(mlx_t.encode()).hexdigest()}. Regenerate: python " + "tests/providers/test_lfm3_prompt_parity_unit.py --regenerate"), "cases": {}} + for case in sorted(CASES): + mlx_prompt, _ = _mlx_render(case, mlx_t) + _, mlx_inputs = _mlx_render(case, None) + out["cases"][case] = { + "gguf_prompt": _gguf_render(case, gguf_t), "mlx_prompt": mlx_prompt, + "gguf_inputs": _gguf_inputs(case), "mlx_inputs": mlx_inputs, + } + assert out["cases"][case]["gguf_prompt"] == _official(gguf_t, case) + assert mlx_prompt == _official(mlx_t, case) + RECORDED_PATH.write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") + print(f"wrote {RECORDED_PATH}") + + +if __name__ == "__main__" and "--regenerate" in sys.argv: + _regenerate() diff --git a/tests/providers/test_lfm3_real_weights.py b/tests/providers/test_lfm3_real_weights.py new file mode 100644 index 00000000..7281905a --- /dev/null +++ b/tests/providers/test_lfm3_real_weights.py @@ -0,0 +1,146 @@ +"""LFM3-1.7B on real weights through AbstractCore (opt-in, 2026-11-30). + +MLX lane: `ABSTRACTCORE_RUN_MLX_TESTS=1` (LiquidAI/LFM3-1.7B-MLX-4bit, mlx-vlm >= 0.7.12). +GGUF lane: `ABSTRACTCORE_RUN_GGUF_TESTS=1` (LiquidAI/LFM3-1.7B-GGUF:Q4_K_M, llama-cpp-python >= 0.3.38). +Both read the operator's Hugging Face cache read-only and never download; a lane whose +weights or engine are absent skips with the reason. Small model (about 1 GB), one load per +lane for the whole module. +""" + +from __future__ import annotations + +import json +import os +import threading +from typing import List + +import pytest +from pydantic import BaseModel + +from abstractcore.exceptions import GenerationCancelledError + +pytestmark = pytest.mark.real_home("loads LFM3-1.7B read-only from the operator's Hugging Face hub cache") + +LANES = { + "mlx": ("ABSTRACTCORE_RUN_MLX_TESTS", "mlx", "LiquidAI/LFM3-1.7B-MLX-4bit", {}), + "gguf": ("ABSTRACTCORE_RUN_GGUF_TESTS", "huggingface", "LiquidAI/LFM3-1.7B-GGUF:Q4_K_M", {"max_tokens": 32768}), +} +TOOLS = [ + {"name": "get_weather", "description": "Get the current weather for a city.", + "parameters": {"city": {"type": "string", "description": "City name"}}}, + {"name": "get_time", "description": "Get the current local time in an IANA time zone.", + "parameters": {"timezone": {"type": "string", "description": "IANA zone, e.g. Europe/Paris"}}}, +] +BOTH = "What is the weather in Tokyo, and what time is it there (Asia/Tokyo)? Use the tools." + + +class Person(BaseModel): + name: str + age: int + hobbies: List[str] + + +@pytest.fixture(scope="module", params=sorted(LANES)) +def llm(request): + switch, provider, model, opts = LANES[request.param] + if os.getenv(switch) != "1": + pytest.skip(f"real-weights LFM3 test; set {switch}=1") + # huggingface_hub freezes its cache path at import: import it on the session's tmp home first + # (the conftest refuses one frozen on the real home); AbstractCore's cache lookup reads the + # environment at call time, so pointing it at the real cache below is a read-only lookup. + import huggingface_hub.constants # noqa: F401 + + hub = os.path.join(os.environ["ABSTRACT_TEST_REAL_HOME"], ".cache", "huggingface", "hub") + saved = {k: os.environ.get(k) for k in ("HF_HUB_CACHE", "HF_HUB_OFFLINE")} + os.environ.update(HF_HUB_CACHE=hub, HF_HUB_OFFLINE="1") + try: + from abstractcore import create_llm + + try: + yield create_llm(provider, model=model, **opts) + except Exception as exc: # noqa: BLE001 - not cached / no engine here: say so + pytest.skip(f"{model} unavailable on {provider}: {type(exc).__name__}: {exc}") + finally: + for k, v in saved.items(): + os.environ.pop(k, None) if v is None else os.environ.__setitem__(k, v) + + +def test_chat_answers_and_reasoning_is_separated(llm): + r = llm.generate("What is the capital of Australia? One sentence.") + assert "Canberra" in r.content and "" not in r.content and "" not in r.content + assert (r.metadata or {}).get("reasoning") # thinking is on by default for this model + assert r.usage and r.usage["output_tokens"] > 0 + + +def test_stream_carries_the_answer_without_tags(llm): + chunks = list(llm.generate("What is the capital of Australia? One sentence.", stream=True)) + text = "".join(c.content or "" for c in chunks) + assert "Canberra" in text and "" not in text + + +def test_stop_mid_stream_raises_cancelled_and_the_provider_stays_usable(llm): + ev = threading.Event() + seen = 0 + with pytest.raises(GenerationCancelledError): + for _ in llm.generate("Write 300 words about refrigerators.", stream=True, thinking="off", cancel_event=ev): + seen += 1 + if seen == 8: + ev.set() + assert llm.generate("Say OK.", thinking="off", max_output_tokens=20).content + + +def test_two_tool_round_trip(llm): + r = llm.generate(BOTH, tools=TOOLS) + names = sorted(c["name"] for c in (r.tool_calls or [])) + assert names == ["get_time", "get_weather"], (r.content, r.tool_calls) # registry: parallel_tools + results = {"get_weather": {"city": "Tokyo", "temperature": 14, "sky": "light rain"}, + "get_time": {"timezone": "Asia/Tokyo", "time": "06:42"}} + msgs = [{"role": "user", "content": BOTH}, + {"role": "assistant", "content": "", "tool_calls": [ + {"id": f"call_{i}", "type": "function", + "function": {"name": c["name"], "arguments": json.dumps(c["arguments"])}} + for i, c in enumerate(r.tool_calls)]}] + msgs += [{"role": "tool", "tool_call_id": f"call_{i}", "name": c["name"], "content": json.dumps(results[c["name"]])} + for i, c in enumerate(r.tool_calls)] + final = llm.generate("", messages=msgs, tools=TOOLS) + assert "14" in final.content and "06:42" in final.content and not final.tool_calls + + +def test_structured_output_ten_times(llm): + for _ in range(10): + p = llm.generate("Maria Lopez is 34 years old. She enjoys climbing, painting and chess. Extract the person.", + response_model=Person) + assert isinstance(p, Person) and p.age == 34 and p.name.startswith("Maria") + + +def test_thinking_off_puts_no_tag_in_the_answer_and_on_reasons(llm): + off = llm.generate("Give the steps to make a cup of tea, numbered.", thinking="off", max_output_tokens=600) + assert off.content and "" not in off.content and "" not in off.content + on = llm.generate("What is 17 * 23? Answer with the number.", thinking="on", max_output_tokens=1500) + assert (on.metadata or {}).get("reasoning") and "391" in on.content + + +def test_twenty_thousand_token_document(llm): + filler = " ".join(f"Record {i}: the river of district {i % 37} was inspected on day {(i * 7) % 365}." for i in range(1400)) + doc = "The access code for the north gate is 4417-KESTREL. " + filler + " The ferry to Sandholm leaves at 17:25." + r = llm.generate(doc + "\n\nWhat is the access code for the north gate, and when does the ferry to Sandholm leave?", + thinking="off", max_output_tokens=200) + assert r.usage["input_tokens"] > 18000 + assert "4417" in r.content and "17:25" in r.content + + +def test_four_turn_session_reuses_the_cache(llm): + key = "lfm3-real-session" + msgs, cached = [], [] + for q in ("My name is Ada and I keep three cats.", "Suggest a name for a fourth cat.", + "Why that name?", "How many cats will I have, and what is my name?"): + msgs.append({"role": "user", "content": q}) + # A system turn as real sessions have. Measured on MLX without one: turn 2 of this + # system-less conversation (a first prompt of about 20 tokens) found no stored prefix + # (cached 0, 0, 75, 188); with it, every later turn restores (39, 123, 239). + r = llm.generate("", messages=list(msgs), system_prompt="You are a concise assistant. Answer in plain sentences.", + prompt_cache_key=key, thinking="off", max_output_tokens=200) + cached.append((r.usage or {}).get("cached_input_tokens") or ((r.metadata or {}).get("prompt_cache") or {}).get("cached_tokens") or 0) + msgs.append({"role": "assistant", "content": r.content}) + assert cached[0] == 0 and all(c > 0 for c in cached[1:]), cached + assert "Ada" in msgs[-1]["content"] diff --git a/tests/providers/test_lfm3_recorded_outputs_unit.py b/tests/providers/test_lfm3_recorded_outputs_unit.py new file mode 100644 index 00000000..ed060288 --- /dev/null +++ b/tests/providers/test_lfm3_recorded_outputs_unit.py @@ -0,0 +1,64 @@ +"""AbstractCore's read path over raw LFM3-1.7B outputs recorded on real weights (2026-11-30). + +Fixtures: tests/fixtures/lfm3/raw_outputs.json (special tokens kept). No model, no network. +What each pins: +- two tool calls in one reply parse as two calls (the registry says `parallel_tools`); +- with thinking OFF the model may still reason and then write a stray ``: that text is + reported as reasoning, never discarded, and the calls after it still parse; +- a structured-output answer `{"name": "Maria Lopez", ...}` is an answer, never a call to a + tool named "Maria Lopez" when the request's tools are known (it names none of them); +- a prompt that ended with `` did not open a thinking block, so a plain answer + stays the answer (the flag set for such a prompt turned a whole answer into reasoning). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from abstractcore.architectures import get_architecture_format, get_model_capabilities +from abstractcore.architectures.response_postprocessing import normalize_assistant_text, prompt_opens_thinking +from abstractcore.tools.parser import parse_tool_calls + +RAW = json.loads((Path(__file__).resolve().parents[1] / "fixtures" / "lfm3" / "raw_outputs.json").read_text()) +MODEL = "LiquidAI/LFM3-1.7B-MLX-4bit" +ARCH = get_architecture_format("lfm3") +CAPS = get_model_capabilities(MODEL) +END = "<|im_end|>" + + +def _split(raw: str, prompt_tail: str): + opened = prompt_opens_thinking("<|im_start|>assistant\n" + prompt_tail, architecture_format=ARCH, model_capabilities=CAPS) + return normalize_assistant_text(raw.replace(END, ""), architecture_format=ARCH, model_capabilities=CAPS, + thinking_opened_by_prompt=opened) + + +def test_registry_declares_parallel_calls_and_two_calls_parse(): + assert CAPS["parallel_tools"] is True + content, reasoning = _split(RAW["two_calls_thinking_on"], "") + assert reasoning and reasoning.startswith("We need to get the weather in Tokyo") + calls = parse_tool_calls(content, MODEL) + assert [(c.name, c.arguments) for c in calls] == [ + ("get_weather", {"city": "Tokyo"}), ("get_time", {"timezone": "Asia/Tokyo"})] + + +def test_thinking_off_leak_is_reported_as_reasoning_and_calls_survive(): + content, reasoning = _split(RAW["two_calls_thinking_off_stray_close"], "") + assert reasoning and reasoning.startswith("We need to get the weather in Tokyo") + assert "" not in content + assert [c.name for c in parse_tool_calls(content, MODEL)] == ["get_weather", "get_time"] + + +def test_a_json_answer_is_never_a_tool_call(): + for key in ("json_answer_thinking_off", "json_answer_thinking_on"): + tail = "" if key.endswith("off") else "" + content, _ = _split(RAW[key], tail) + assert json.loads(content)["name"] == "Maria Lopez" + assert parse_tool_calls(content, MODEL, tool_names={"get_weather", "get_time"}) == [] + assert parse_tool_calls(content, MODEL, tool_names=set()) == [] + + +def test_thinking_off_prompt_does_not_open_a_block(): + assert not prompt_opens_thinking("<|im_start|>assistant\n", architecture_format=ARCH, model_capabilities=CAPS) + content, reasoning = _split(RAW["json_answer_thinking_off"], "") + assert content.startswith("{") and reasoning is None diff --git a/tests/providers/test_mlx_vlm_only_model_type_unit.py b/tests/providers/test_mlx_vlm_only_model_type_unit.py new file mode 100644 index 00000000..8d70edb3 --- /dev/null +++ b/tests/providers/test_mlx_vlm_only_model_type_unit.py @@ -0,0 +1,160 @@ +"""A checkpoint whose architecture mlx-lm does not ship but mlx-vlm does loads through mlx-vlm (2026-11-30). + +LFM3 (`model_type: lfm3`): no mlx-lm release has `mlx_lm.models.lfm3`; mlx-vlm >= 0.7.11 has +`mlx_vlm.models.lfm3`. The MLX provider used to hand every text checkpoint to mlx-lm, which raised +"Model type lfm3 not supported". The choice is read from the checkpoint's config.json, never from +the name, and goes back to mlx-lm by itself once mlx-lm ships the module. No weights, no GPU: the +real `MLXProvider._load_model` runs over a fake checkpoint with fake loaders (the MTP lane harness). +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +import types + +import pytest + +from abstractcore.providers import mlx_provider +from tests.providers.test_mlx_mtp_checkpoint_lane_unit import _Loaders, _checkpoint, _provider + + +def _libraries(monkeypatch, *, mlx_lm_has, mlx_vlm_has, mlx_vlm_version="0.7.12"): + """Fake `mlx_lm.utils` / `mlx_vlm.utils`, a `find_spec` that answers for the two packages and + the installed mlx-vlm distribution's version (`importlib.metadata`; None: not installed).""" + import importlib.metadata + + real_version = importlib.metadata.version + + def version(dist): + if dist == "mlx-vlm": + if mlx_vlm_version is None: + raise importlib.metadata.PackageNotFoundError(dist) + return mlx_vlm_version + return real_version(dist) + + monkeypatch.setattr(importlib.metadata, "version", version) + lm_utils = types.ModuleType("mlx_lm.utils") + lm_utils.MODEL_REMAPPING = {"mistral": "llama"} + lm_utils.MODEL_ARCHITECTURE_REMAPPING = {} + vlm_utils = types.ModuleType("mlx_vlm.utils") + vlm_utils.get_model_type = lambda config: str(config.get("model_type") or "").lower() or None + for name, utils in (("mlx_lm", lm_utils), ("mlx_vlm", vlm_utils)): + package = sys.modules.get(name) + if package is None or not isinstance(package, types.ModuleType) or getattr(package, "__file__", None): + package = types.ModuleType(name) # never the real library: its import would load MLX + monkeypatch.setitem(sys.modules, name, package) + monkeypatch.setattr(package, "utils", utils, raising=False) + monkeypatch.setitem(sys.modules, f"{name}.utils", utils) + real = importlib.util.find_spec + + def find_spec(name, *a, **k): + if name.startswith("mlx_lm.models."): + return object() if name.rsplit(".", 1)[1] in mlx_lm_has else None + if name.startswith("mlx_vlm.models."): + return object() if name.rsplit(".", 1)[1] in mlx_vlm_has else None + return real(name, *a, **k) + + monkeypatch.setattr(importlib.util, "find_spec", find_spec) + + +def test_the_decision_reads_the_config_and_both_libraries(monkeypatch): + _libraries(monkeypatch, mlx_lm_has={"llama", "lfm2"}, mlx_vlm_has={"lfm3", "lfm2"}) + pick = mlx_provider._mlx_vlm_only_model_type + assert pick({"model_type": "lfm3"}) == "lfm3" + assert pick({"model_type": "lfm2"}) is None # mlx-lm has it: the ordinary lane + assert pick({"model_type": "mistral"}) is None # mlx-lm's own remapping (mistral -> llama) + assert pick({"model_type": "nothing_has_this"}) is None # mlx-lm raises its own error + assert pick({"model_type": "lfm3", "model_file": "lfm3.py"}) is None # repository code: never run + assert pick(None) is None and pick({}) is None + + +def test_once_mlx_lm_ships_the_module_it_wins(monkeypatch): + _libraries(monkeypatch, mlx_lm_has={"lfm3"}, mlx_vlm_has={"lfm3"}) + assert mlx_provider._mlx_vlm_only_model_type({"model_type": "lfm3"}) is None + + +def test_an_lfm3_checkpoint_loads_through_mlx_vlm(tmp_path, monkeypatch): + loaders = _Loaders(monkeypatch) + _libraries(monkeypatch, mlx_lm_has={"qwen3_5"}, mlx_vlm_has={"lfm3", "qwen3_5"}) + provider = _provider(_checkpoint(tmp_path, mtp=False, model_type="lfm3")) + provider._load_model() + assert loaders.calls == ["vlm(None)"], loaders.calls + + +def test_a_checkpoint_mlx_lm_has_still_loads_through_mlx_lm(tmp_path, monkeypatch): + loaders = _Loaders(monkeypatch) + _libraries(monkeypatch, mlx_lm_has={"qwen3_5"}, mlx_vlm_has={"lfm3", "qwen3_5"}) + _provider(_checkpoint(tmp_path, mtp=False, model_type="qwen3_5"))._load_model() + assert loaders.calls == ["mlx_lm"] + + +def test_the_installed_libraries_agree_with_the_decision(): + """On a machine with the real MLX stack: the decision follows what is installed.""" + pytest.importorskip("mlx_lm") + pytest.importorskip("mlx_vlm") + lm = importlib.util.find_spec("mlx_lm.models.lfm3") is not None + vlm = importlib.util.find_spec("mlx_vlm.models.lfm3") is not None + expected = "lfm3" if (vlm and not lm) else None + assert mlx_provider._mlx_vlm_only_model_type(json.loads('{"model_type": "lfm3"}')) == expected + + +# --- Fix round 2026-12-01: the lane is taken only for a model_type the registry declares --- + + +def test_an_undeclared_type_mlx_vlm_ships_keeps_mlx_lm_s_own_error(monkeypatch): + """mlx-vlm 0.7.12 ships ~190 module names mlx-lm lacks (VLMs, image generators, detectors); + only the declared `lfm3` was run through this lane, so the others still go to mlx-lm.""" + _libraries(monkeypatch, mlx_lm_has={"llama"}, mlx_vlm_has={"lfm3", "deepseek_v4", "llava", "flux2", "lfm3_vl"}) + pick = mlx_provider._mlx_vlm_only_model_type + assert mlx_provider._declared_mlx_vlm_model_types() == {"lfm3": "0.7.12"} + for model_type in ("deepseek_v4", "llava", "flux2", "lfm3_vl"): + assert pick({"model_type": model_type}) is None, model_type + assert pick({"model_type": "lfm3"}) == "lfm3" + + +def test_an_mlx_vlm_too_old_for_a_declared_type_says_so_and_what_to_install(monkeypatch): + """The live environment's mlx-vlm 0.7.2 has no `lfm3` module and no `get_model_type`: the + message names the installed version (it used to say "no mlx-vlm").""" + _libraries(monkeypatch, mlx_lm_has={"llama"}, mlx_vlm_has=set(), mlx_vlm_version="0.7.2") + monkeypatch.delattr(sys.modules["mlx_vlm.utils"], "get_model_type") # as in the real 0.7.2 + with pytest.raises(mlx_provider.MlxVlmTooOldError) as e: + mlx_provider._mlx_vlm_only_model_type({"model_type": "lfm3"}) + message = str(e.value) + assert "mlx-vlm >= 0.7.12" in message and "installed: mlx-vlm 0.7.2" in message + assert 'pip install -U "abstractcore[apple]"' in message and "mlx-lm release" not in message + + +def test_an_mlx_vlm_below_the_declared_version_is_refused_even_with_the_module(monkeypatch): + """mlx-vlm 0.7.11 ships `lfm3` but leaks its reasoning into the answer; the registry declares + 0.7.12, and the declared version is compared, not only printed.""" + _libraries(monkeypatch, mlx_lm_has={"llama"}, mlx_vlm_has={"lfm3"}, mlx_vlm_version="0.7.11") + with pytest.raises(mlx_provider.MlxVlmTooOldError, match="installed: mlx-vlm 0.7.11"): + mlx_provider._mlx_vlm_only_model_type({"model_type": "lfm3"}) + _libraries(monkeypatch, mlx_lm_has={"llama"}, mlx_vlm_has={"lfm3"}, mlx_vlm_version="0.7.13") + assert mlx_provider._mlx_vlm_only_model_type({"model_type": "lfm3"}) == "lfm3" + + +def test_no_mlx_vlm_at_all_for_a_declared_type_says_so(monkeypatch): + _libraries(monkeypatch, mlx_lm_has={"llama"}, mlx_vlm_has={"lfm3"}, mlx_vlm_version=None) + with pytest.raises(mlx_provider.MlxVlmTooOldError, match="installed: no mlx-vlm"): + mlx_provider._mlx_vlm_only_model_type({"model_type": "lfm3"}) + + +def test_no_installed_model_type_changes_lane_except_the_declared_ones(): + """Against the installed libraries, every module name either library ships: the lane is the + 2.41.0 one (mlx-lm's load, which for a type mlx-lm lacks is its own 'not supported' error) + for every type the registry does not declare.""" + pytest.importorskip("mlx_lm") + pytest.importorskip("mlx_vlm") + import pkgutil + + import mlx_lm.models + import mlx_vlm.models + + names = {m.name for m in pkgutil.iter_modules(mlx_lm.models.__path__)} + names |= {m.name for m in pkgutil.iter_modules(mlx_vlm.models.__path__)} + declared = mlx_provider._declared_mlx_vlm_model_types() + moved = {t for t in sorted(names) if mlx_provider._mlx_vlm_only_model_type({"model_type": t}) is not None} + assert moved <= set(declared), sorted(moved - set(declared)) diff --git a/tests/server/test_server_refused_attachment_status.py b/tests/server/test_server_refused_attachment_status.py new file mode 100644 index 00000000..05ef31e8 --- /dev/null +++ b/tests/server/test_server_refused_attachment_status.py @@ -0,0 +1,603 @@ +"""A request the route or model cannot carry is the caller's 400, not a 500 (LFM3 fix round, 2026-12-01). + +The first LFM3 change made Core refuse an attachment it cannot deliver +(`UnsupportedFeatureError`) and, in this round, a file it cannot read (a corrupt PDF, a +binary type with no reader). Through Core's own server those refusals were HTTP 500 +`server_error`: a remote caller could not tell them from a server fault, and +AbstractRuntime's remote client retries a 5xx three times. Now: 400, +`invalid_request_error`, the code `unsupported_feature`, the same message. A streaming +request keeps the 2.41.0 stream path (the response opens at once, the provider is called on +the stream's own thread, where a shared busy model is waited for): its refusal is the +stream's first event, typed `invalid_request_error` / `unsupported_feature`, and Core's own +OpenAI-compatible provider raises the same `UnsupportedFeatureError` for that event as for +the 400. A real server fault stays a 500. No network, no model. +""" +from __future__ import annotations + +import base64 +import json +import importlib + +import pytest +from fastapi.testclient import TestClient + +from abstractcore.core.types import GenerateResponse +from abstractcore.exceptions import UnsupportedFeatureError +from tests.provider_stubs import StaticProvider + +CORRUPT_PDF = "data:application/pdf;base64," + base64.b64encode(b"%PDF-1.7\nnot a pdf body").decode() + + +class _Echo(StaticProvider): + """Answers 'ok'; `refuse` makes it refuse the request the way a route without an audio + transport does (raised while the request is built, before anything is sent).""" + + refuse = False + fault = False + + def _generate_internal(self, prompt, messages=None, system_prompt=None, tools=None, media=None, stream=False, + response_model=None, execute_tools=None, media_metadata=None, **kwargs): + if type(self).refuse: + raise self._media_not_delivered(["clip.wav"], route="this route", cause="it carries no audio") + if type(self).fault: + raise RuntimeError("disk on fire") + if stream: + return iter([GenerateResponse(content="ok", model=self.model), + GenerateResponse(content="", model=self.model, finish_reason="stop")]) + return GenerateResponse(content="ok", model=self.model, finish_reason="stop") + + +@pytest.fixture +def client(monkeypatch): + for name in ("ABSTRACTCORE_AUTH_TOKEN", "OPENAI_API_KEY"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("ABSTRACTCORE_SERVER_ALLOW_UNAUTHENTICATED", "1") + core = importlib.import_module("abstractcore.server.app") + _Echo.refuse = _Echo.fault = False + monkeypatch.setattr(core, "create_llm", lambda provider, model=None, **kw: _Echo(model or "m")) + return TestClient(core.app) + + +def _chat(client, *, stream: bool, content): + return client.post("/v1/chat/completions", json={ + "model": "lmstudio/m", "stream": stream, "messages": [{"role": "user", "content": content}]}) + + +def _responses(client, *, stream: bool, text: str): + return client.post("/v1/responses", json={"model": "lmstudio/m", "stream": stream, "input": text}) + + +def _assert_refused(r, code: str, *needles: str): + if r.headers["content-type"].startswith("text/event-stream"): + # A streamed request: 2.41.0's stream path, the refusal is its typed first error event. + assert r.status_code == 200 + events = [json.loads(line[6:]) for line in r.text.splitlines() if line.startswith("data: {")] + errors = [e["error"] for e in events if "error" in e] + assert errors and errors[0]["type"] == "invalid_request_error" and errors[0]["code"] == code, events + for needle in needles: + assert needle in errors[0]["message"], errors[0]["message"] + return + assert r.status_code == 400, (r.status_code, r.text[:400]) + assert r.headers["content-type"].startswith("application/json"), r.headers["content-type"] + err = r.json()["error"] + assert err["type"] == "invalid_request_error" and err["code"] == code, err + for needle in needles: + assert needle in err["message"], err["message"] + + +@pytest.mark.parametrize("stream", [False, True], ids=["plain", "stream"]) +def test_an_attachment_the_route_cannot_carry_is_a_400(client, stream): + _Echo.refuse = True + _assert_refused(_chat(client, stream=stream, content="what is said?"), "unsupported_feature", + "clip.wav", "it carries no audio") + + +@pytest.mark.parametrize("stream", [False, True], ids=["plain", "stream"]) +def test_an_unreadable_document_is_a_400(client, stream): + content = [{"type": "text", "text": "summarise"}, {"type": "file", "file_url": {"url": CORRUPT_PDF}}] + _assert_refused(_chat(client, stream=stream, content=content), "unsupported_feature", + "Cannot read document file", "Failed to process PDF") + + +@pytest.mark.parametrize("stream", [False, True], ids=["plain", "stream"]) +def test_the_responses_api_refuses_with_a_400_too(client, stream): + _Echo.refuse = True + _assert_refused(_responses(client, stream=stream, text="what is said?"), "unsupported_feature", "clip.wav") + + +def test_a_server_fault_is_still_a_500(client): + _Echo.fault = True + r = _chat(client, stream=False, content="hi") + assert r.status_code == 500 + + +@pytest.mark.parametrize("stream", [False, True], ids=["plain", "stream"]) +def test_an_accepted_request_still_answers(client, stream): + r = _chat(client, stream=stream, content="hi") + assert r.status_code == 200 + assert "ok" in r.text + + +def test_the_responses_stream_still_opens_with_response_created(client): + r = _responses(client, stream=True, text="hi") + assert r.status_code == 200 + events = [line for line in r.text.splitlines() if line.startswith("data: {")] + assert '"response.created"' in events[0] and "ok" in r.text + + +def test_refusal_codes_and_the_shared_status_mapping(): + core = importlib.import_module("abstractcore.server.app") + from abstractcore.media.base import MediaProcessingError + + assert core._provider_exception_status(UnsupportedFeatureError("x")) == 400 + assert core._provider_exception_status(MediaProcessingError("x")) == 400 + assert core._request_refusal_code(MediaProcessingError("x")) == "unsupported_feature" + assert core._provider_exception_status(RuntimeError("x")) == 500 + + +def test_the_syntax_rewriter_reads_a_json_answer_as_text(): + """H2 on the server: a JSON answer naming no tool of the request is not rewritten as a call.""" + core = importlib.import_module("abstractcore.server.app") + from abstractcore.tools.syntax_rewriter import SyntaxFormat + + answer = '{"name": "Maria Lopez", "age": 34}' + tools = [{"type": "function", "function": {"name": "get_weather", "parameters": {}}}] + for request_tools in (tools, None): + rewriter = core.create_syntax_rewriter(SyntaxFormat.QWEN3, "lmstudio/qwen/qwen3-4b", request_tools) + assert rewriter.rewrite_content(answer) == answer + call = '{"name": "get_weather", "arguments": {"city": "Paris"}}' + rewritten = core.create_syntax_rewriter(SyntaxFormat.QWEN3, "lmstudio/qwen/qwen3-4b", tools).rewrite_content(call) + assert "<|tool_call|>" in rewritten + + +@pytest.mark.parametrize("model", ["lmstudio/mistral-7b-instruct", "lmstudio/some-unknown-model"]) +def test_with_no_tools_a_call_shaped_answer_is_not_rewritten_for_json_format_models(model): + """Review 2nd pass S2: with no tools on the request nothing is a call, also for the families + whose declared call syntax is a JSON object (and unknown models).""" + core = importlib.import_module("abstractcore.server.app") + from abstractcore.tools.syntax_rewriter import SyntaxFormat + + answer = '{"name": "resnet50", "parameters": {"lr": 0.01}}' + assert core.create_syntax_rewriter(SyntaxFormat.QWEN3, model, None).rewrite_content(answer) == answer + + +def test_in_process_the_refusal_keeps_its_type_and_is_not_retried(): + """The provider base wrapped an `UnsupportedFeatureError` raised while the request was built + into `ProviderAPIError("API error: ...")`, which the retry layer retries: the same refusal ran + up to three times and reached callers (and the server) as a provider fault.""" + calls = [] + + class _Counting(_Echo): + refuse = True + + def _generate_internal(self, *a, **k): + calls.append(1) + return super()._generate_internal(*a, **k) + + with pytest.raises(UnsupportedFeatureError, match="it carries no audio"): + _Counting("m").generate("what is said?") + assert len(calls) == 1 + + +# --- Streams: 2.41.0 behaviour on a free and on a busy shared model; typed refusal event ------ +# Deterministic (ADR 0050 rule 6): the stub providers and the busy model wait on events the test +# controls, and the tests assert ORDER (headers while the provider is still blocked, the cancel seen +# while it is still blocked, only then released). Waits are bounded by `patient(20)` only to turn a +# hang into a failure. The latencies are reported by `timing_budget`, asserted under +# ABSTRACTCORE_TIMING_STRICT=1 only. + +import asyncio +import json as _json +import logging +import threading +import time as _time + +from abstractcore.core.types import GenerateResponse as _GR +from tests.timing import patient, timing_budget + +LIMIT = patient(20.0) +PATHS = ["/v1/chat/completions", "/v1/responses"] + + +def _install(monkeypatch, provider_cls, *, resident=None): + monkeypatch.setenv("ABSTRACTCORE_SERVER_ALLOW_UNAUTHENTICATED", "1") + for name in ("ABSTRACTCORE_AUTH_TOKEN", "OPENAI_API_KEY"): + monkeypatch.delenv(name, raising=False) + core = importlib.import_module("abstractcore.server.app") + monkeypatch.setattr(core, "create_llm", lambda provider, model=None, **kw: provider_cls(model or "m")) + if resident is not None: + monkeypatch.setattr(core, "_resident_provider_for_request", + lambda provider, model, kw: resident if model == "busy" else None) + return core + + +class _Gate: + """What a gated stub provider reports, and the event that releases its first token.""" + + def __init__(self): + self.entered = threading.Event() # the provider is producing (blocked before its first token) + self.release = threading.Event() # set by the test: produce the first token + self.cancelled = threading.Event() # the provider saw the route's cancel event + self.first_token = threading.Event() # the first token was produced + self.cancel_event = None + + +def _gated_provider(gate: _Gate, *, then_block: bool = False): + """A concurrent provider (the route gives it a cancel event) whose first token waits for + `gate.release`; with `then_block`, it yields one token at once and then waits.""" + + class _Gated(StaticProvider): + def supports_concurrent_generation(self): + return True + + def generate(self, prompt="", **kw): + ev = kw.get("_cancel_event") or kw.get("cancel_event") + gate.cancel_event = ev + model = self.model + + def wait_release_or_cancel() -> bool: + while not gate.release.is_set(): + if ev is not None and ev.wait(0.01): + gate.cancelled.set() + return False + return True + + def gen(): + gate.entered.set() + if then_block: + gate.first_token.set() + yield _GR(content="ok", model=model) + if not wait_release_or_cancel(): + return + if not then_block: + gate.first_token.set() + yield _GR(content="ok", model=model) + yield _GR(content="", model=model, finish_reason="stop") + + return gen() + + return _Gated + + +def _shared_busy_model(state): + """A provider instance lent to the route (the gateway's case) whose calls go through the real + `_InstanceGenerationWorker` of the Hugging Face provider; `_hold(worker)` makes another run hold it.""" + from abstractcore.providers.huggingface_provider import _InstanceGenerationWorker + + worker = _InstanceGenerationWorker("test-busy-model") + + class _Shared(StaticProvider): + def generate(self, prompt="", **kw): + model = self.model + state.setdefault("cancel_events", []).append(kw.get("cancel_event")) + if kw.get("refuse"): + raise self._media_not_delivered(["clip.wav"], route="this route", cause="it carries no audio") + + def call(): + state["generations"] = state.get("generations", 0) + 1 + + def gen(): + yield _GR(content="x", model=model) + yield _GR(content="", model=model, finish_reason="stop") + + return gen() + + return worker.stream(call, cancel_event=kw.get("cancel_event")) + + return _Shared("busy"), worker + + +def _hold(worker): + """Another run holds the shared model until the returned event is set.""" + released, holding = threading.Event(), threading.Event() + + def run(): + holding.set() + released.wait(LIMIT) + + thread = threading.Thread(target=lambda: worker.run(run), daemon=True) + thread.start() + assert holding.wait(LIMIT) + return released, thread + + +def _drained(worker): + """Every call queued on the worker before this one has been handled (the worker is FIFO).""" + worker.run(lambda: None) + + +def _body(path, model): + payload = {"model": f"huggingface/{model}", "stream": True} + payload.update({"input": "hi"} if path.endswith("responses") else {"messages": [{"role": "user", "content": "hi"}]}) + return _json.dumps(payload).encode() + + +class _Client: + """An ASGI client driven by the test: it leaves (http.disconnect) when `leave` is set.""" + + def __init__(self, core, path, model="m"): + self.core, self.path, self.model = core, path, model + self.t0 = _time.monotonic() + self.started = asyncio.Event() + self.created = asyncio.Event() + self.got_body = asyncio.Event() + self.leave = asyncio.Event() + self.started_after = None + self.events = [] + + async def receive(self): + if not hasattr(self, "_sent_body"): + self._sent_body = True + return {"type": "http.request", "body": _body(self.path, self.model), "more_body": False} + await self.leave.wait() + return {"type": "http.disconnect"} + + async def send(self, message): + if message["type"] == "http.response.start": + self.started_after = _time.monotonic() - self.t0 + self.status = message.get("status") + self.started.set() + elif message["type"] == "http.response.body": + body = message.get("body") or b"" + for line in body.decode(errors="replace").splitlines(): + if line.startswith("data: {"): + self.events.append(_json.loads(line[6:])) + if b"response.created" in body: + self.created.set() + if body and b"response.created" not in body: + self.got_body.set() + + def run(self): + scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "POST", + "path": self.path, "raw_path": self.path.encode(), "query_string": b"", + "headers": [(b"content-type", b"application/json"), (b"host", b"t")], + "client": ("127.0.0.1", 1), "server": ("t", 80), "scheme": "http", "root_path": ""} + return asyncio.ensure_future(self.core.app(scope, self.receive, self.send)) + + +async def _until(event: "asyncio.Event", what: str): + try: + await asyncio.wait_for(event.wait(), LIMIT) + except asyncio.TimeoutError: + raise AssertionError(f"never happened: {what}") from None + + +async def _until_thread(event: threading.Event, what: str): + if not await asyncio.to_thread(event.wait, LIMIT): + raise AssertionError(f"never happened: {what}") + + +async def _finish(task): + try: + await asyncio.wait_for(task, LIMIT) + except Exception: + pass + + +# Group 1: a free model ------------------------------------------------------------------------ + + +@pytest.mark.parametrize("path", PATHS) +def test_free_model_answers_before_the_first_token_and_a_stop_then_cancels(monkeypatch, caplog, path): + gate = _Gate() + core = _install(monkeypatch, _gated_provider(gate)) + + async def main(): + client = _Client(core, path) + task = client.run() + await _until(client.started, "response headers") + if path.endswith("responses"): + await _until(client.created, "response.created") + assert client.status == 200 and not gate.first_token.is_set() # answered while the provider waits + timing_budget(client.started_after, 0.3, "stream headers, first token pending") + await _until_thread(gate.entered, "the provider started") + t_leave = _time.monotonic() + client.leave.set() + await _until_thread(gate.cancelled, "the provider saw the cancel") + assert not gate.release.is_set() and not gate.first_token.is_set() # cancelled while still blocked + timing_budget(_time.monotonic() - t_leave, 1.0, "stop before the first token: cancel seen") + gate.release.set() + await _finish(task) + + with caplog.at_level(logging.WARNING): + asyncio.run(main()) + assert not [r for r in caplog.records if r.levelno >= logging.ERROR], [r.getMessage() for r in caplog.records] + + +def test_free_model_stop_after_the_first_token_cancels(monkeypatch): + gate = _Gate() + core = _install(monkeypatch, _gated_provider(gate, then_block=True)) + + async def main(): + client = _Client(core, "/v1/chat/completions") + task = client.run() + await _until(client.got_body, "the first token") + client.leave.set() + await _until_thread(gate.cancelled, "the provider saw the cancel") + assert not gate.release.is_set() + gate.release.set() + await _finish(task) + + asyncio.run(main()) + + +# Group 2: a busy shared model (another run holds it) ------------------------------------------ + + +@pytest.mark.parametrize("path", PATHS) +def test_busy_model_answers_at_once_and_a_stop_during_the_wait_never_generates(monkeypatch, caplog, path): + state = {} + shared, worker = _shared_busy_model(state) + core = _install(monkeypatch, _gated_provider(_Gate()), resident=shared) + released, holder = _hold(worker) + + async def main(): + client = _Client(core, path, model="busy") + task = client.run() + await _until(client.started, "response headers while the model is held") + if path.endswith("responses"): + await _until(client.created, "response.created while the model is held") + assert client.status == 200 and not released.is_set() + timing_budget(client.started_after, 0.3, "stream headers, shared model busy") + await _until_thread(_wait_for_cancel_event(state), "the route handed the provider a cancel event") + client.leave.set() + await _until_thread(state["cancel_events"][0], "the cancel event set by the Stop") + assert not released.is_set() # seen while the model is still held + released.set() + await _finish(task) + + with caplog.at_level(logging.WARNING): + asyncio.run(main()) + holder.join(LIMIT) + _drained(worker) + assert state.get("generations", 0) == 0, state # the queued request never generated + assert not [r for r in caplog.records if r.levelno >= logging.ERROR], [r.getMessage() for r in caplog.records] + + +def _wait_for_cancel_event(state) -> threading.Event: + """Set once the provider was called with its cancel event (the call happens on the stream's thread).""" + seen = threading.Event() + + def poll(): + while not state.get("cancel_events"): + if seen.wait(0.01): + return + seen.set() + + threading.Thread(target=poll, daemon=True).start() + return seen + + +def test_busy_model_queue_does_not_starve_a_stream_to_a_free_model(monkeypatch): + """30 streamed requests wait for the held shared model; an unrelated stream to a free model gets + its first token while the model is still held (no shared pool thread is parked per waiter).""" + state = {} + shared, worker = _shared_busy_model(state) + free_gate = _Gate() + free_gate.release.set() # the free model answers at once + core = _install(monkeypatch, _gated_provider(free_gate), resident=shared) + released, holder = _hold(worker) + + async def main(): + waiting = [_Client(core, "/v1/chat/completions", model="busy") for _ in range(30)] + tasks = [c.run() for c in waiting] + for c in waiting: + await _until(c.started, "a queued stream answered") + free = _Client(core, "/v1/chat/completions", model="free") + t0 = _time.monotonic() + free_task = free.run() + await _until(free.got_body, "the free model's first token while the shared model is held") + assert not released.is_set() + timing_budget(_time.monotonic() - t0, 0.5, "free stream first token, 30 queued on a busy model") + await _finish(free_task) + for c in waiting: + c.leave.set() + released.set() + for t in tasks: + await _finish(t) + + asyncio.run(main()) + holder.join(LIMIT) + + +# Group 3: a refusal is reported at once, typed, never delayed by a busy model ----------------- + + +@pytest.mark.parametrize("path", PATHS) +def test_a_refused_stream_is_a_typed_first_error_while_the_model_is_held(monkeypatch, path): + state = {} + shared, worker = _shared_busy_model(state) + original = type(shared).generate + monkeypatch.setattr(type(shared), "generate", lambda self, prompt="", **kw: original(self, prompt, refuse=True, **kw)) + core = _install(monkeypatch, _gated_provider(_Gate()), resident=shared) + released, holder = _hold(worker) + + async def main(): + client = _Client(core, path, model="busy") + task = client.run() + await _finish(task) # the stream ends on its error event + errors = [e["error"] for e in client.events if "error" in e] + assert errors and not released.is_set() # reported while the model is still held + err = errors[0] + assert err["type"] == "invalid_request_error" and err["code"] == "unsupported_feature" + assert "clip.wav" in err["message"] + timing_budget(client.started_after, 0.3, "refused stream answered, shared model busy") + + asyncio.run(main()) + released.set() + holder.join(LIMIT) + + +def test_cores_own_provider_raises_the_same_refusal_for_the_event_and_the_400(monkeypatch): + """AbstractCore's OpenAI-compatible provider pointed at an AbstractCore server: the streamed + refusal event and the non-streamed 400 both raise `UnsupportedFeatureError`, called once (not + retried).""" + calls = [] + + class _Refusing(_Echo): + refuse = True + + def _generate_internal(self, *a, **k): + calls.append(1) + return super()._generate_internal(*a, **k) + + core = _install(monkeypatch, _Refusing) + from abstractcore.providers.openai_compatible_provider import OpenAICompatibleProvider + + p = OpenAICompatibleProvider(model="lmstudio/m", base_url="http://127.0.0.1:9/v1") + p.base_url = "http://testserver/v1" + p.client = TestClient(core.app) # the server in process, no socket + with pytest.raises(UnsupportedFeatureError, match="it carries no audio"): + p.generate("what is said?") + assert len(calls) == 1 + calls.clear() + with pytest.raises(UnsupportedFeatureError, match="it carries no audio"): + for _ in p.generate("what is said?", stream=True): + pass + assert len(calls) == 1 + + +@pytest.mark.parametrize("error,expected", [ + ({"message": "m", "type": "invalid_request_error", "code": "unsupported_feature"}, "UnsupportedFeatureError"), + ({"message": "m", "type": "invalid_request_error", "code": "invalid_request"}, "InvalidRequestError"), + ({"message": "m", "type": "invalid_request_error", "code": "context_length_exceeded"}, "ProviderAPIError"), + ({"message": "m", "type": "invalid_request_error"}, "ProviderAPIError"), + ({"message": "m", "type": "server_error"}, "ProviderAPIError"), +], ids=["core-unsupported", "core-invalid", "other-code", "no-code", "server-error"]) +def test_only_cores_own_codes_change_how_a_stream_error_event_is_raised(error, expected): + """Review 4th pass U1: another server's event typed `invalid_request_error` (another code, or none) + is handled as on 2.41.0 (a retried `ProviderAPIError`); only AbstractCore's two codes are typed.""" + from abstractcore.providers.openai_compatible_provider import OpenAICompatibleProvider + + p = OpenAICompatibleProvider(model="m", base_url="http://127.0.0.1:9/v1") + with pytest.raises(Exception) as e: + p._raise_on_stream_error_event({"error": error}) + assert type(e.value).__name__ == expected + + +@pytest.mark.parametrize("path", PATHS) +def test_an_error_after_the_stream_opened_is_a_typed_event(monkeypatch, path): + class _LateRefusal(StaticProvider): + def generate(self, prompt="", **kw): + model, provider = self.model, self + + def gen(): + yield _GR(content="partial ", model=model) + raise provider._media_not_delivered(["clip.wav"], route="this route", cause="it carries no audio") + + return gen() + + core = _install(monkeypatch, _LateRefusal) + r = TestClient(core.app).post(path, json={"model": "lmstudio/m", "stream": True, + **({"input": "hi"} if path.endswith("responses") else + {"messages": [{"role": "user", "content": "hi"}]})}) + assert r.status_code == 200 + events = [_json.loads(line[6:]) for line in r.text.splitlines() if line.startswith("data: {")] + errors = [e["error"] for e in events if "error" in e] + assert errors and errors[0]["type"] == "invalid_request_error" and errors[0]["code"] == "unsupported_feature" + + +def test_a_late_server_fault_keeps_the_2_41_event(): + core = importlib.import_module("abstractcore.server.app") + assert core._stream_error_event(RuntimeError("disk on fire")) == { + "error": {"message": "disk on fire", "type": "server_error"}} diff --git a/tests/streaming/test_critical_streaming_tool_fix.py b/tests/streaming/test_critical_streaming_tool_fix.py index 7fd65e87..e559d679 100644 --- a/tests/streaming/test_critical_streaming_tool_fix.py +++ b/tests/streaming/test_critical_streaming_tool_fix.py @@ -438,7 +438,7 @@ def test_content_after_tool_streams_correctly(self): ] stream = (GenerateResponse(content=c, model="test") for c in chunks) - results = list(processor.process_stream(stream)) + results = list(processor.process_stream(stream, [{"name": "test", "description": "", "parameters": {}}])) all_content = "".join([r.content for r in results if r.content]) @@ -567,7 +567,7 @@ def test_mixed_content_and_tools(self): ] stream = (GenerateResponse(content=c, model="test") for c in chunks) - results = list(processor.process_stream(stream)) + results = list(processor.process_stream(stream, [{"name": "read_file", "description": "", "parameters": {}}, {"name": "analyze", "description": "", "parameters": {}}])) all_content = "".join([r.content for r in results if r.content]) diff --git a/tests/streaming/test_unified_streaming.py b/tests/streaming/test_unified_streaming.py index 07d105d8..03318e13 100644 --- a/tests/streaming/test_unified_streaming.py +++ b/tests/streaming/test_unified_streaming.py @@ -478,7 +478,9 @@ def test_process_stream_xmlish_direct_tool_tag_yields_tool_call_without_raw_mark "", "", ] - results = list(processor.process_stream(self.create_test_stream(chunks))) + results = list(processor.process_stream( + self.create_test_stream(chunks), [{"name": "web_search", "description": "", "parameters": {}}] + )) visible = "".join(result.content or "" for result in results) all_tool_calls = [] @@ -527,7 +529,7 @@ def test_streaming_with_tool_detection_jsonish(self): ] stream = self.create_test_stream(chunks) - results = list(processor.process_stream(stream)) + results = list(processor.process_stream(stream, [{"name": "calc", "description": "", "parameters": {}}])) all_tool_calls = [] for result in results: @@ -1057,3 +1059,21 @@ def test_tool_detection_overhead(self): if __name__ == "__main__": pytest.main([__file__, "-v", "--tb=short"]) + + +def test_no_tool_call_is_yielded_for_a_request_that_offered_no_tools(): + """A tool call exists only for a tool the request offered (LFM3 integration, + 2026-11-30): without tools the model's markup is its content, exactly as the + non-streamed passthrough returns it. Without the fix the call was yielded and the + markup removed from the content.""" + markup = "\n\n\nParis\n\n\n" + processor = UnifiedStreamProcessor("LiquidAI/LFM3-1.7B-MLX-4bit", execute_tools=False) + chunks = [GenerateResponse(content=markup[i:i + 7], model="m") for i in range(0, len(markup), 7)] + results = list(processor.process_stream(iter(chunks), None)) + assert "".join(r.content or "" for r in results) == markup + assert not [tc for r in results for tc in (r.tool_calls or [])] + + offered = [{"name": "get_weather", "description": "", "parameters": {}}] + chunks = [GenerateResponse(content=markup[i:i + 7], model="m") for i in range(0, len(markup), 7)] + results = list(processor.__class__("LiquidAI/LFM3-1.7B-MLX-4bit").process_stream(iter(chunks), offered)) + assert [tc["name"] for r in results for tc in (r.tool_calls or [])] == ["get_weather"] diff --git a/tests/structured/test_structured_output.py b/tests/structured/test_structured_output.py index 7ac6fd7b..f51ce13b 100644 --- a/tests/structured/test_structured_output.py +++ b/tests/structured/test_structured_output.py @@ -152,6 +152,24 @@ class TestProviderPrompted: assert handler._has_native_support(TestProviderNative()) is True assert handler._has_native_support(TestProviderPrompted()) is False + def test_mlx_vlm_lane_is_not_native(self): + """Outlines constrains the MLX provider's mlx-lm lane only. On the mlx-vlm lane (LFM3, + Qwen4-Exp, MTP checkpoints) a "native" attempt was an unconstrained generation without + the schema, so every structured request generated twice (2026-11-30).""" + pytest.importorskip("outlines") + handler = StructuredOutputHandler() + + class MLXProvider: # the handler keys on the provider class name + def __init__(self, processor, method="auto"): + self._mtp_processor = processor + self.structured_output_method = method + + assert handler._has_native_support(MLXProvider(None)) is True + assert handler._has_native_support(MLXProvider(object())) is False + # An explicit native_outlines is never switched to prompted in silence: it reaches the + # provider, whose mlx-vlm lane refuses it ("does not support Outlines' mlx-lm adapter"). + assert handler._has_native_support(MLXProvider(object(), "native_outlines")) is True + def test_create_schema_prompt(self): """Test schema prompt generation.""" handler = StructuredOutputHandler() diff --git a/tests/test_incremental_thinking_tag_stripper.py b/tests/test_incremental_thinking_tag_stripper.py index 36da5a2b..2f3ec1ad 100644 --- a/tests/test_incremental_thinking_tag_stripper.py +++ b/tests/test_incremental_thinking_tag_stripper.py @@ -1,5 +1,7 @@ from __future__ import annotations +import pytest + from abstractcore.architectures.response_postprocessing import IncrementalThinkingTagStripper @@ -81,3 +83,88 @@ def test_incremental_thinking_tag_stripper_assume_visible_start_still_strips_ful assert out == "Answer: 42" assert reasoning == "internal reasoning" + + +@pytest.mark.parametrize("step", [1, 5, 1000]) +def test_thinking_off_stream_never_shows_a_stray_closing_tag(step): + """Recorded LFM3-1.7B reply with thinking OFF (`` prefill, mlx-vlm and + llama.cpp, 2026-11-30): it reasons in the answer, then writes a closing tag it was never + given an opening for, then its tool calls. The streamed content used to carry the literal + ``; the tag is markup and never part of the answer.""" + raw = ( + "We need to get the weather in Tokyo and the current local time there." + "\n\n\nTokyo\n\n\n" + ) + s = IncrementalThinkingTagStripper(start_tag="", end_tag="", assume_visible_start=True, strip_stray_close=True) + out = "".join(s.process(raw[i:i + step]) for i in range(0, len(raw), step)) + tail, reasoning = s.finalize() + assert "" not in out + tail + assert (out + tail).startswith("We need to get the weather") and "" in out + tail + assert s.stray_close_tags == 1 and reasoning is None + + +@pytest.mark.parametrize("step", [1, 5, 1000]) +def test_thinking_off_stream_keeps_an_answer_that_discusses_the_tag(step): + """Only the format's one closing tag (the end of leaked reasoning, where the non-streamed + path splits) is markup; an answer that then writes about `` keeps every character + (fix round 2026-12-01: every `` before an opened block used to be deleted).""" + raw = "Reasoning here.A block is closed with , and Qwen writes too." + s = IncrementalThinkingTagStripper(start_tag="", end_tag="", assume_visible_start=True, strip_stray_close=True) + out = "".join(s.process(raw[i:i + step]) for i in range(0, len(raw), step)) + tail, _ = s.finalize() + assert out + tail == "Reasoning here.A block is closed with , and Qwen writes too." + assert s.stray_close_tags == 1 + + +def test_without_the_declared_leak_every_tag_of_the_answer_stays(): + """Re-check N8: the removal is switched on only for a model whose registry entry declares the + leak (LFM3); for any other model with thinking off, an answer that writes the tag keeps it.""" + raw = "The closing tag is and it ends the block." + s = IncrementalThinkingTagStripper(start_tag="", end_tag="", assume_visible_start=True) + out = "".join(s.process(raw[i:i + 4]) for i in range(0, len(raw), 4)) + assert out + s.finalize()[0] == raw and s.stray_close_tags == 0 + + +@pytest.mark.parametrize("model,expected", [ + ("LiquidAI/LFM3-1.7B-GGUF", True), ("LiquidAI/LFM3-VL-2B-GGUF", True), ("qwen/qwen3-4b", False), ("google/gemma-4-e4b", False), +]) +def test_only_models_declaring_the_leak_strip_it(model, expected): + import logging + + from abstractcore.architectures import get_model_capabilities + from abstractcore.providers.base import BaseProvider + + class _P: + model_capabilities = get_model_capabilities(model) + + strips = BaseProvider._strips_stray_close_tag + assert strips(_P(), True, False) is expected + assert strips(_P(), False, False) is False + assert strips(_P(), True, True) is False # LM Studio's separated reasoning + + +def test_the_stray_tag_count_reaches_the_streamed_metadata(): + """Review 2nd pass S8: the removal is reported, `metadata["thinking_stray_close_tags"]`, on the chunk + whose text lost the tag (streamed through the provider base, thinking off, LFM3).""" + from abstractcore.core.types import GenerateResponse + from abstractcore.providers.base import ThinkingControlHandling + from tests.provider_stubs import StaticProvider + + class _LeakingLFM3(StaticProvider): + def _apply_provider_thinking_kwargs(self, *, enabled, level, kwargs, request_shape=None): + return dict(kwargs or {}), ThinkingControlHandling(handled_enable_disable=True) + + def _generate_internal(self, prompt, messages=None, system_prompt=None, tools=None, media=None, stream=False, + response_model=None, execute_tools=None, media_metadata=None, **kwargs): + text = "The user asks for a greeting.Hello! The tag closes a block." + pieces = [GenerateResponse(content=text[i:i + 6], model=self.model) for i in range(0, len(text), 6)] + pieces.append(GenerateResponse(content="", model=self.model, finish_reason="stop")) + return iter(pieces) + + p = _LeakingLFM3("LiquidAI/LFM3-1.7B-GGUF") + chunks = list(p.generate("Say hello.", stream=True, thinking="off")) + text = "".join(c.content or "" for c in chunks) + assert text == "The user asks for a greeting.Hello! The tag closes a block." + counts = [c.metadata["thinking_stray_close_tags"] for c in chunks + if isinstance(c.metadata, dict) and "thinking_stray_close_tags" in c.metadata] + assert counts == [1] diff --git a/tests/test_packaging_extras.py b/tests/test_packaging_extras.py index 27df4fa8..058ea67d 100644 --- a/tests/test_packaging_extras.py +++ b/tests/test_packaging_extras.py @@ -33,7 +33,7 @@ def test_every_abstractvoice_pin_carries_the_engine_runtime_floor() -> None: def test_mlx_vlm_ships_with_mlx_lm_in_apple() -> None: # A gateway with mlx-lm but no mlx-vlm accepts images and silently drops them. apple = EXTRAS["apple"] - for dep in ("mlx>=0.32.2,<1.0.0", "mlx-lm>=0.31.3,<1.0.0", "mlx-vlm>=0.7.1,<0.8.0", "outlines>=0.1.0"): + for dep in ("mlx>=0.32.2,<1.0.0", "mlx-lm>=0.31.3,<1.0.0", "mlx-vlm>=0.7.12,<0.8.0", "outlines>=0.1.0"): assert dep in apple assert "vllm>=0.6.0,<1.0.0; sys_platform == 'linux'" in EXTRAS["gpu"] # Linux only upstream (backlog 0988) diff --git a/tests/test_user_scenario_validation.py b/tests/test_user_scenario_validation.py index b3828448..f785e4e9 100644 --- a/tests/test_user_scenario_validation.py +++ b/tests/test_user_scenario_validation.py @@ -137,7 +137,8 @@ def test_no_rewriting_without_custom_tags(): def test_stream(): yield GenerateResponse(content=content, model="test-model") - results = list(processor.process_stream(test_stream())) + # The request offered the tool: a call exists only for an offered tool (2026-11-30). + results = list(processor.process_stream(test_stream(), [{"name": "test", "description": "", "parameters": {}}])) full_output = "".join([r.content for r in results if r.content]) # Without custom tags, the streaming processor strips tool markup from `content` diff --git a/tests/tools/test_json_tool_call_offered_tools_unit.py b/tests/tools/test_json_tool_call_offered_tools_unit.py new file mode 100644 index 00000000..35a431cd --- /dev/null +++ b/tests/tools/test_json_tool_call_offered_tools_unit.py @@ -0,0 +1,150 @@ +"""One rule for a tool call written as a JSON object, streamed or not (LFM3 fix round, 2026-12-01). + +A JSON object (envelope-less, or in a ```json block) is a tool call only when it names a +tool OFFERED on this request; anything else is the model's answer. The rule is the same +for every family (no family switch) and on both paths: + +- non-streamed: `BaseProvider._normalize_tool_calls_passthrough` hands the offered names + to the parser (`parse_tool_calls(..., tool_names=...)`); +- streamed: `UnifiedStreamProcessor` checks the names of a ```json block (the same + `parser.offered_tool_name`). + +Regression pinned: the first LFM3 change removed the JSON reader from the parser's fallback +for every family that declares an envelope (Qwen, Gemma 4, Phi, LFM3, ~30 families), so a +fenced call to an offered tool became a call streamed and none non-streamed. The defect it +was fixing stays fixed: a JSON answer `{"name": "Maria Lopez", ...}` is not a call and +raises no `unavailable_tool` warning. +""" + +from __future__ import annotations + +import logging +from typing import Any, Dict, List, Optional + +import pytest + +from abstractcore.core.types import GenerateResponse +from abstractcore.providers.base import BaseProvider +from abstractcore.providers.huggingface_provider import HuggingFaceProvider +from abstractcore.providers.streaming import UnifiedStreamProcessor +from abstractcore.tools.handler import create_handler + +MODELS = [ + "Qwen/Qwen3-8B", # special_token + "google/gemma-4-e4b", # special_token (Gemma 4) + "phi-4", # xml + "LiquidAI/LFM3-1.7B-MLX-4bit", # xml (lfm3) + "mistralai/Mistral-7B-Instruct-v0.3", # json + "llama3.2:3b", # prompted (llama3 header) +] + +TOOLS = [{"name": "get_weather", "description": "w", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}}] + +FENCED_CALL = 'I will check.\n```json\n{"name": "get_weather", "arguments": {"city": "Paris"}}\n```' +FENCED_ANSWER = 'Here you go.\n```json\n{"name": "Maria Lopez", "age": 34}\n```' +BARE_ANSWER = '{"name": "Maria Lopez", "age": 34, "skills": ["python", "sql"]}' +BARE_CALL = '{"name": "get_weather", "arguments": {"city": "Paris"}}' + + +def _provider(model: str) -> HuggingFaceProvider: + p = object.__new__(HuggingFaceProvider) + p.model = model + p.logger = logging.getLogger("test.json_tool_rule") + p.tool_handler = create_handler(model) + return p + + +def _non_streamed(model: str, text: str, tools: Optional[List[Dict[str, Any]]]) -> GenerateResponse: + return BaseProvider._normalize_tool_calls_passthrough( + _provider(model), response=GenerateResponse(content=text, model=model), tools=tools, tool_call_tags=None + ) + + +def _streamed(model: str, text: str, tools: Optional[List[Dict[str, Any]]]): + proc = UnifiedStreamProcessor(model, execute_tools=False) + chunks = [GenerateResponse(content=text[i:i + 7], model=model) for i in range(0, len(text), 7)] + chunks[-1].finish_reason = "stop" + out = list(proc.process_stream(iter(chunks), tools)) + calls = [tc["name"] if isinstance(tc, dict) else tc.name for r in out for tc in (r.tool_calls or [])] + content = "".join(r.content or "" for r in out) + warned = any((r.metadata or {}).get("tool_call_error") for r in out) + return calls, content, warned + + +def _names(response: GenerateResponse) -> List[str]: + return [tc["name"] for tc in (response.tool_calls or [])] + + +@pytest.mark.parametrize("model", MODELS) +def test_a_fenced_call_to_an_offered_tool_is_one_call_streamed_and_not(model: str) -> None: + response = _non_streamed(model, FENCED_CALL, TOOLS) + assert _names(response) == ["get_weather"] + assert response.tool_calls[0]["arguments"] == {"city": "Paris"} + # (Non-streamed, the block stays in `content` beside the call, as in 2.41.0: the cleaner + # removes envelopes, not JSON objects. Streamed, the block is withheld.) + calls, content, _ = _streamed(model, FENCED_CALL, TOOLS) + assert calls == ["get_weather"] + assert content.strip() == "I will check." + + +@pytest.mark.parametrize("model", MODELS) +@pytest.mark.parametrize("text", [FENCED_ANSWER, BARE_ANSWER], ids=["fenced", "bare"]) +def test_a_json_answer_naming_no_offered_tool_is_text_without_a_warning(model: str, text: str) -> None: + response = _non_streamed(model, text, TOOLS) + assert not response.tool_calls + assert response.content == text + assert not (response.metadata or {}).get("tool_call_error") + assert not (response.metadata or {}).get("warnings") + calls, content, warned = _streamed(model, text, TOOLS) + assert calls == [] and content == text and not warned + + +@pytest.mark.parametrize("model", MODELS) +def test_an_envelope_less_call_to_an_offered_tool_is_a_call_non_streamed(model: str) -> None: + """As in 2.41.0. Streamed, an envelope-less object is not detected at all (unchanged since + 2.41.0: the stream would have to hold back every `{` of an answer while tools are offered).""" + assert _names(_non_streamed(model, BARE_CALL, TOOLS)) == ["get_weather"] + + +@pytest.mark.parametrize("model", MODELS) +@pytest.mark.parametrize("text", [FENCED_CALL, BARE_CALL], ids=["fenced", "bare"]) +def test_no_call_when_the_request_offered_no_tools(model: str, text: str) -> None: + response = _non_streamed(model, text, None) + assert not response.tool_calls and response.content == text + calls, content, _ = _streamed(model, text, None) + assert calls == [] and content == text + + +def test_harmony_stream_yields_no_call_when_no_tools_were_offered() -> None: + """GPT-OSS raw transcript: a `to=functions.x` message is a call only for an offered tool; + without tools its text is content (framing tokens removed, as on the rest of the lane).""" + model = "openai/gpt-oss-20b" + text = '<|channel|>commentary to=functions.get_weather <|constrain|>json<|message|>{"city":"Paris"}<|call|>' + calls, content, _ = _streamed(model, text, None) + assert calls == [] + assert content == 'to=functions.get_weather {"city":"Paris"}' + calls, content, _ = _streamed(model, text, TOOLS) + assert calls == ["get_weather"] and content == "" + + +def test_one_fenced_block_is_one_call_for_a_json_format_model() -> None: + """The JSON reader read the object inside a ```json block twice (once bare, once fenced): + two calls for one block, non-streamed, on `json`-format models (Mistral).""" + from abstractcore.tools.parser import parse_tool_calls + + assert [c.name for c in parse_tool_calls(FENCED_CALL, "mistralai/Mistral-7B-Instruct-v0.3")] == ["get_weather"] + + +@pytest.mark.parametrize("model", ["mistralai/Mistral-7B-Instruct-v0.3", "some-org/unknown-model-7b"]) +@pytest.mark.parametrize("text", [ + '{"name": "lookup_weather", "arguments": {"city": "Paris"}}', + 'Calling it.\n```json\n{"name": "lookup_weather", "parameters": {"city": "Paris"}}\n```', +], ids=["bare", "fenced"]) +def test_a_call_to_an_unknown_tool_is_still_reported_where_json_is_the_declared_syntax(model, text): + """Re-check N4: for families whose declared call syntax IS a JSON object (and unknown models), + an object with the call's shape naming no offered tool is a call to an unavailable tool + (`tool_call_error`, which AbstractAgent feeds back), not the final answer. An object that is + not call-shaped stays an answer (`BARE_ANSWER` above).""" + response = _non_streamed(model, text, TOOLS) + assert not response.tool_calls + assert (response.metadata or {}).get("tool_call_error", {}).get("code") == "unavailable_tool" diff --git a/tests/tools/test_offered_names_reach_every_parser_unit.py b/tests/tools/test_offered_names_reach_every_parser_unit.py new file mode 100644 index 00000000..97623279 --- /dev/null +++ b/tests/tools/test_offered_names_reach_every_parser_unit.py @@ -0,0 +1,136 @@ +"""Every caller that parses tool calls hands the parser the request's offered tools (re-check N9, 2026-12-01). + +The JSON tool-call rule (a JSON object is a call only when it names an offered tool) depends on each +caller passing the names. The first fix round's tests covered the passthrough, the stream and the +server's rewriter; these cover the other call sites, each of which went unnoticed when reverted: +the reasoning recovery, provider-side prompted tool execution (base and Ollama), the CLI, the stream's +end-of-output guards, and the retry layer's list of request errors it must not retry. +""" +from __future__ import annotations + +import logging +import types + +import pytest + +from abstractcore.core.types import GenerateResponse +from abstractcore.providers.base import BaseProvider +from abstractcore.providers.huggingface_provider import HuggingFaceProvider +from abstractcore.tools.handler import create_handler + +MODEL = "Qwen/Qwen3-8B" +TOOLS = [{"name": "get_weather", "description": "w", "parameters": {"type": "object", "properties": {}}}] + + +class _SpyHandler: + """Records the `tool_names` every parse is given, then parses for real.""" + + def __init__(self, model): + self.real = create_handler(model) + self.supports_prompted = True + self.seen = [] + + def parse_response(self, content, mode="prompted", tool_names=None): + self.seen.append(None if tool_names is None else set(tool_names)) + return self.real.parse_response(content, mode=mode, tool_names=tool_names) + + +def _provider(cls=HuggingFaceProvider, model=MODEL): + p = object.__new__(cls) + p.model = model + p.logger = logging.getLogger("test.names") + p.tool_handler = _SpyHandler(model) + p.execute_tools = False + return p + + +def test_the_reasoning_recovery_passes_the_offered_names(): + p = _provider() + r = GenerateResponse(content="", model=MODEL, metadata={ + "reasoning": 'Let me call it.\n\n{"name": "get_weather", "arguments": {}}\n'}) + out = BaseProvider._normalize_tool_calls_passthrough(p, response=r, tools=TOOLS, tool_call_tags=None) + assert [c["name"] for c in out.tool_calls] == ["get_weather"] + assert {"get_weather"} in p.tool_handler.seen and None not in p.tool_handler.seen + + +def test_provider_side_prompted_execution_passes_the_offered_names(): + p = _provider() + r = GenerateResponse(content='{"name": "Maria Lopez", "arguments": {"age": 34}}', model=MODEL) + out = BaseProvider._handle_prompted_tool_execution(p, r, TOOLS, execute_tools_param=False) + assert out is r and p.tool_handler.seen == [{"get_weather"}] + + +def test_ollama_prompted_execution_passes_the_offered_names(): + from abstractcore.providers.ollama_provider import OllamaProvider + + p = _provider(OllamaProvider, "qwen3:4b") + r = GenerateResponse(content='{"name": "Maria Lopez", "arguments": {"age": 34}}', model="qwen3:4b") + out = OllamaProvider._handle_tool_execution(p, r, TOOLS) + assert out is r and p.tool_handler.seen == [{"get_weather"}] + + +def test_the_cli_reads_a_json_object_as_a_call_only_for_a_session_tool(): + from abstractcore.utils.cli import SimpleCLI + + def get_weather(city: str) -> str: + """Weather.""" + return city + + from abstractcore.tools import ToolDefinition + + cli = object.__new__(SimpleCLI) + cli.session = types.SimpleNamespace(tools=[ToolDefinition.from_function(get_weather)]) + cli.model_name = MODEL + cli.debug_mode = False + answer = '{"name": "Maria Lopez", "arguments": {"age": 34}}' + assert cli._parse_and_strip_tool_calls(answer) == (answer, []) + _, calls = cli._parse_and_strip_tool_calls('{"name": "get_weather", "arguments": {"city": "Paris"}}') + assert calls == [{"name": "get_weather", "arguments": {"city": "Paris"}}] + + +@pytest.mark.parametrize("terminal", [True, False], ids=["provider-finish", "end-of-output"]) +def test_an_unclosed_envelope_at_the_end_of_a_stream_without_tools_is_no_call(terminal): + """With tag rewriting on and no tools offered, the detector still runs; what it settles when + the stream ends must not become a call (`streaming.py` `_drain` and the final drain).""" + from abstractcore.providers.streaming import UnifiedStreamProcessor + + proc = UnifiedStreamProcessor(MODEL, execute_tools=False, tool_call_tags="qwen3") + text = 'Sure.<|tool_call|>{"name": "get_weather", "arguments": {}}' + chunks = [GenerateResponse(content=text[i:i + 6], model=MODEL) for i in range(0, len(text), 6)] + if terminal: + chunks[-1].finish_reason = "stop" + out = list(proc.process_stream(iter(chunks), None)) + assert not [tc for r in out for tc in (r.tool_calls or [])] + + +@pytest.mark.parametrize("error", ["MediaProcessingError", "UnsupportedMediaTypeError", "FileSizeExceededError"]) +def test_an_unreadable_attachment_is_not_retried(error): + from abstractcore.core.retry import RetryConfig, RetryManager + from abstractcore.media import base as media_base + + manager = RetryManager(RetryConfig()) + exc = getattr(media_base, error)("Cannot read document file 'x.json': network json timeout") + assert manager.should_retry(exc, 1) is False + + +def test_the_mlx_stream_cleanup_passes_the_offered_names(monkeypatch): + """`MLXProvider._stream_generate_with_tools` re-parses the streamed text to cut the tool results + after it (scheduled lane); that parse gets the offered names too (review 2nd pass, the one H2 + call site left without a test).""" + from abstractcore.providers.mlx_provider import MLXProvider + + p = _provider(MLXProvider, MODEL) + text = 'Calling.<|tool_call|>{"name": "get_weather", "arguments": {}}' + + def fake_stream(*a, **k): + yield GenerateResponse(content=text, model=MODEL) + yield GenerateResponse(content="", model=MODEL, finish_reason="stop") + + monkeypatch.setattr(p, "_stream_generate", fake_stream, raising=False) + monkeypatch.setattr(p, "supports_concurrent_generation", lambda: True, raising=False) + cleaned = p.tool_handler.real.parse_response(text, mode="prompted", tool_names={"get_weather"}).content or "" + monkeypatch.setattr(p, "_handle_prompted_tool_execution", + lambda response, tools, **k: GenerateResponse(content=cleaned + "\nRESULT", model=MODEL), raising=False) + out = list(MLXProvider._stream_generate_with_tools(p, "prompt", 64, 0.0, 1.0, tools=TOOLS)) + assert p.tool_handler.seen == [{"get_weather"}] + assert "".join(c.content or "" for c in out).endswith("\nRESULT") diff --git a/tests/tools/test_tool_parsing_cross_family_regressions.py b/tests/tools/test_tool_parsing_cross_family_regressions.py index f54d2ab5..37f2721c 100644 --- a/tests/tools/test_tool_parsing_cross_family_regressions.py +++ b/tests/tools/test_tool_parsing_cross_family_regressions.py @@ -281,3 +281,22 @@ def test_hy_stream_still_strips_the_wrapper(step: int) -> None: assert _calls(calls) == [("save_memory", {"fact": "Alex is allergic to peanuts"})] assert content.strip() == "Saving." assert unparsed is None + + +# --- A structured answer is not a tool call (LFM3 integration, 2026-11-30) --- + + +def test_a_json_answer_naming_no_offered_tool_is_not_a_call() -> None: + """Recorded LFM3-1.7B structured-output answer: with the request's tools known, a JSON + object is a call only when it names one of them (the stream's rule for ```json blocks), + for every family. The pin above (no tools given: `tool_names=None`) keeps reading any + name, for a caller that does not know the offered tools.""" + answer = '{"name": "Maria Lopez", "age": 34, "skills": ["python", "sql"]}' + for model in ("LiquidAI/LFM3-1.7B-MLX-4bit", "Qwen/Qwen3-8B", "mistralai/Mistral-7B-Instruct-v0.3", None): + assert parse_tool_calls(answer, model, tool_names={"get_weather"}) == [] + assert parse_tool_calls(answer, model, tool_names=set()) == [] + # the envelope itself still parses + call = '\n\n\nParis\n\n\n' + assert _calls(parse_tool_calls(call, "LiquidAI/LFM3-1.7B-MLX-4bit", tool_names={"get_weather"})) == [ + ("get_weather", {"city": "Paris"}) + ] diff --git a/tests/utils/test_llamacpp_update_for_unknown_architecture_unit.py b/tests/utils/test_llamacpp_update_for_unknown_architecture_unit.py index 81780739..06953ffb 100644 --- a/tests/utils/test_llamacpp_update_for_unknown_architecture_unit.py +++ b/tests/utils/test_llamacpp_update_for_unknown_architecture_unit.py @@ -17,11 +17,11 @@ def test_the_newest_release_table_is_shipped_and_knows_the_server_models(): data = json.loads(ASSET.read_text(encoding="utf-8")) archs = set(data["architectures"]) - assert data["llama_cpp_python"] == "0.3.36" + assert data["llama_cpp_python"] == "0.3.38" # spark2_5 (XHToken/Spark-X2.6-4B on the OVH server) and every catalog GGUF architecture # (checked against the Hub's gguf.architecture on 2026-10-29) for a in ("spark2_5", "qwen35", "qwen35moe", "gemma4", "lfm2", "lfm2moe", "qwen3vl", "granitehybrid", "hy_v3", - "minimax-m2", "gpt-oss", "deepseek2", "nomic-bert", "gemma3n"): + "minimax-m2", "gpt-oss", "deepseek2", "nomic-bert", "gemma3n", "lfm3"): assert a in archs, a @@ -32,9 +32,9 @@ def old_install(monkeypatch): def test_an_architecture_the_newest_release_knows_offers_the_update(old_install): - assert mc.llamacpp_update_for("spark2_5") == {"architecture": "spark2_5", "installed": "0.3.35", "update_to": "0.3.36"} + assert mc.llamacpp_update_for("spark2_5") == {"architecture": "spark2_5", "installed": "0.3.35", "update_to": "0.3.38"} reason = mc.gguf_unloadable_reason("spark2_5") - assert "llama-cpp-python 0.3.36 can: update llama.cpp" in reason, "MUTANT: no update hint -> only greyed -> RED" + assert "llama-cpp-python 0.3.38 can: update llama.cpp" in reason, "MUTANT: no update hint -> only greyed -> RED" def test_an_architecture_no_release_knows_stays_greyed_with_the_sentence(old_install): @@ -45,3 +45,13 @@ def test_an_architecture_no_release_knows_stays_greyed_with_the_sentence(old_ins def test_a_loadable_architecture_says_nothing(monkeypatch): monkeypatch.setattr(mc, "llamacpp_knows_architecture", lambda a: True) assert mc.gguf_unloadable_reason("spark2_5") is None and mc.llamacpp_update_for("spark2_5") is None + + +def test_lfm3_on_an_older_llamacpp_names_the_release_that_loads_it(old_install): + """LFM3 GGUFs need llama-cpp-python 0.3.38 (the first release with a Metal wheel whose + llama.cpp names `lfm3`). The GGUF provider raises this sentence at load, before any + context is allocated.""" + assert mc.gguf_unloadable_reason("lfm3") == ( + "This computer's llama.cpp (llama-cpp-python 0.3.35) cannot load the lfm3 architecture; " + "llama-cpp-python 0.3.38 can: update llama.cpp." + )