Skip to content

Automation foundation model for tiny devices: 2-bit, 8-29 MB, tool calls, ASR, structured extraction and embeddings on phones, wearables, smart homes, robots, cars and microcontrollers.

Enhance Needle framework with new features and improvements

HenryNdubuaku3413a930f6af
diff --git a/README.md b/README.md
index 30bb788..58ee290 100644
--- a/README.md
+++ b/README.md
@@ -141,12 +141,16 @@ The base is Needle 3, a depth ladder: every rung from 2 layers up to the full st
needle finetune data.jsonl --epochs 10 --layers 8
```
-**3. Build a tuned `.cact`.** Merge the adapter into the base and quantize. The base auto-downloads if absent.
+**3. Build a tuned `.cact`.** Merge the adapter into the base and quantize. The checkpoint is optional: `needle build` uses the base the adapter was trained on, and auto-downloads the Needle 3 base if absent.
```sh
-needle build checkpoints/needle3.safetensors --lora checkpoints/needle_lora.safetensors --out my_needle.cact
+needle build --lora checkpoints/needle_lora.safetensors --out my_needle.cact
+needle build checkpoints/needle3_enterprise.safetensors --lora adapter.safetensors --out my_needle.cact # 20L base
+needle build --layers 4 --out needle3_4l.cact # untuned 4-layer rung
```
+The engine is weights-agnostic and never rebuilt: one engine library per platform (under 1MB) runs any archive, and the archive shrinks with the rung (about 9MB at 2 layers, 29MB at 16). `needle download needle3` fetches the base 16-layer archive by itself, `needle download needle3.safetensors` (or `needle3_enterprise.safetensors`) the checkpoint to fine-tune.
+
Add `--bits 2` for a smaller model (by default the export follows the checkpoint's declared per-layer bit map, falling back to 4 when the checkpoint declares none), or set `NEEDLE_HF_REPO=<you>/<model>` and pass `--upload` to publish the `.cact`. The counterpart `needle download <you>/<model>/my_needle.cact` pulls a published archive on any machine, and `needle download <platform>` (e.g. `macos-arm64`) fetches that platform's engine runner.
**4. Run it.** The engine is weights-agnostic, so a tuned `.cact` runs on it directly - no recompilation:
@@ -154,6 +158,7 @@ Add `--bits 2` for a smaller model (by default the export follows the checkpoint
```python
import needle
agent = needle.Needle(weights="my_needle.cact", tools=[...])
+agent = needle.Needle(tools=[...], generation=3) # the base Needle 3 archive, fetched once and cached
agent.run("...")
```
diff --git a/doc/apis.md b/doc/apis.md
index cf49129..ad45130 100644
--- a/doc/apis.md
+++ b/doc/apis.md
@@ -3,13 +3,13 @@
| Call | What it does |
| --- | --- |
| `needle.Needle(tools=None, system=None, weights=None, tool_index_path=None, buffer_size=65536)` | Create an agent bound to one toolset. `tools` takes decorated functions, Pydantic models, raw JSON schema dicts, or a JSON string. `system` carries environment facts. `weights` loads a tuned `.cact`. `tool_index_path` persists tool embeddings for large catalogues. |
-| `agent.complete(text="", max_new_tokens=256, audio=None, audio_format="wav", sample_rate=0, channels=1)` | Complete a text, speech, or mixed turn. `audio` accepts WAV bytes or a path; PCM16 and float32 buffers use the accompanying format, rate, and channel fields. |
+| `agent.complete(text="", max_new_tokens=512, audio=None, audio_format="wav", sample_rate=0, channels=1)` | Complete a text, speech, or mixed turn. `audio` accepts WAV bytes or a path; PCM16 and float32 buffers use the accompanying format, rate, and channel fields. |
| `agent.embed(text="", audio=None, audio_format="wav", sample_rate=0, channels=1)` | Embed text, serialized tool schemas, audio, or a mixed input with the Needle 3 retrieval head. |
-| `agent.run(query="", max_steps=8, max_new_tokens=256, audio=None, audio_format="wav", sample_rate=0, channels=1, strict=True)` | Full agentic loop: the model picks calls, Needle executes your Python functions and feeds results back, and the final response carries the executed tool results as `results`. |
+| `agent.run(query="", max_steps=8, max_new_tokens=512, audio=None, audio_format="wav", sample_rate=0, channels=1, strict=True)` | Full agentic loop: the model picks calls, Needle executes your Python functions and feeds results back, and the final response carries the executed tool results as `results`. |
| `agent.reset()` | Rewind the conversation, keep the tools loaded. |
| `needle.tool` | Decorator that turns a function into a tool schema (attached as `fn._needle_tool`). |
| `needle.Field(...)` | Per argument constraints, attached inline with `typing.Annotated` or passed as a default. |
-| `needle.extract(text, schema, system=None, max_new_tokens=256, weights=None, strict=True)` | One shot extraction. Returns a Pydantic instance if `schema` is a model, else a dict, or `None` if nothing matched. Strict mode rejects temporal values that contradict literal source years and engine-reported ungrounded values. |
+| `needle.extract(text, schema, system=None, max_new_tokens=512, weights=None, strict=True)` | One shot extraction. Returns a Pydantic instance if `schema` is a model, else a dict, or `None` if nothing matched. Strict mode rejects temporal values that contradict literal source years and engine-reported ungrounded values. |
Audio tokenization is internal. Pass a WAV path or WAV bytes directly:
@@ -119,8 +119,10 @@ Needle solves every problem as a function call. The context declares what may be
- A request no declared tool can serve is refused with the empty call `[]`. That is the whole contract for off-topic input; there is no free-text fallback.
- Arguments contain only values evidenced by the input. An optional field with no evidence is omitted, not guessed; omission is the field-level `[]`.
+- An escalated call is withheld by the engine: `function_calls` is empty and `suppressed_calls` carries it. The agent prefixes the local `date:` fact to `system` automatically (`auto_date=False` opts out) so relative dates resolve.
- A date argument whose year matches none of the years written in the conversation so far or in the `system` facts is reported in `validation.ungrounded` as `tool.field`, alongside anything the engine itself flags as ungrounded. `run()` does not execute such a call; its result is `{"error": "ungrounded field"}` and the model continues from it. Pass `strict=False` to execute anyway.
-- `extract()` caps the engine at one call per turn, so a record schema never yields a second record; `escalate` is also raised when the request negates the tool's verb, quotes a command reported by someone else, or a required enumerated value has no support in the request.
+- Speech: `complete(text, audio=clip)` transcribes the clip in a clean context, then answers a text turn that carries the transcript wrapped in `<context>` followed by `text` (or "Fulfill the spoken request." when `text` is empty); the speech codes are not part of that turn and the transcript is returned as `transcript` with `transcript_confidence` (geometric mean token probability of the transcription decode).
+- `extract()` declares the record as the only tool; a turn with a single declared tool is a record extraction, so an escalated record is returned with the `escalate` flag rather than withheld, and `strict` handles grounding.
- Arguments arrive after the engine's deterministic repair step, which grounds them in the request text (first/last name split, phone completion, verbatim quoted titles, place queries with their street address, weekday and explicit dates resolved against the `date:` fact, empty optionals and duplicate calls dropped). Enumerated parameters are never altered.
- `reasoning` is the model's short derivation of each argument from its source span (`'ten minutes' -> minutes 10`). It is generated unconstrained; only the call itself is grammar-constrained, so the JSON cannot be malformed while the derivation stays legible.
- After you execute a call, pass the result back as the next `complete()`. The model continues from it, and later arguments may depend on earlier results: `search_for_contact` first, then `send_instant_message` with the returned `contact_id`. A final `"type": "respond"` with empty `function_calls` signals the loop is done; the answer is the tool results themselves, which `run()` collects on the final response as `results`. No free text is generated.
@@ -176,7 +178,7 @@ Calibration holds for the base model only. Fine-tuning does not update the head,
## Offline devices
-Each generation's engine is fetched once and cached under `~/.cache/cactus-needle/v2/` or `v3/`. Inference itself never touches the network, so an air gapped device only needs the matching file in place. Three ways to get it there:
+Each generation's engine is fetched once and cached under `~/.cache/cactus-needle/v2/` or `v3/`; Needle 3 also caches its base archive `needle3.cact` there, since the engine carries no weights (`needle download needle3` fetches it explicitly). Inference itself never touches the network, so an air gapped device only needs the matching files in place. Three ways to get them there:
1. `needle fetch --generation 2|3` downloads that engine for the current machine into the cache and prints the path. `--out <dir>` places it elsewhere. `--platform-tag manylinux2014_aarch64` fetches the build for a different device; tags follow the wheel names on the Hugging Face repo (`macosx_11_0_arm64`, `manylinux2014_x86_64`, `musllinux_1_2_aarch64`, `win_amd64`, `win_arm64`). For the standalone engine runner, `needle download <platform> --generation 2|3 [--out <dir>]` (platform folders include `macos-arm64`, `linux-x86_64`, `wasm`, and `wasm-component`; the CLI prints the full list on an invalid name) copies that platform's engine files into `<out>/<platform>/` and marks a native `needle` runner executable when present. The `wasm-component` target contains `needle.component.wasm` and the `cactus:needle/[email protected]` WIT contract.
2. Copy the file to the same cache path on the device, or drop it inside the installed `needle/` package directory, which wins over the cache.
diff --git a/llms.txt b/llms.txt
index ff38dbd..c6ff3f1 100644
--- a/llms.txt
+++ b/llms.txt
@@ -20,12 +20,12 @@ pip install "cactus-needle[train]" # adds JAX + training deps for finetune
- `system`: optional environment-facts string (see System facts).
- `weights`: path to a tuned `.cact` to load instead of the baked base model.
- `tool_index_path`: path to persist tool embeddings when you declare many tools.
-- `agent.run(query, max_steps=8, max_new_tokens=256) -> dict` - full agentic loop: model picks calls, Needle executes your Python functions, feeds results back, returns the final response with the executed tool results attached as `results`.
-- `agent.complete(text, max_new_tokens=256) -> dict` - one turn; you execute the call and feed the result back yourself via the next `complete(...)`.
+- `agent.run(query, max_steps=8, max_new_tokens=512) -> dict` - full agentic loop: model picks calls, Needle executes your Python functions, feeds results back, returns the final response with the executed tool results attached as `results`.
+- `agent.complete(text, max_new_tokens=512) -> dict` - one turn; you execute the call and feed the result back yourself via the next `complete(...)`.
- `agent.reset()` - rewind the conversation, keep the tools loaded.
- `needle.tool` - decorator that turns a function into a tool schema (attached as `fn._needle_tool`).
- `needle.Field(default=..., *, description, enum, const, ge, le, gt, lt, multiple_of, min_length, max_length, pattern, format, min_items, max_items, unique_items)` - per-argument constraints; attach inline with `typing.Annotated`.
-- `needle.extract(text, schema, system=None, max_new_tokens=256, weights=None)` - one-shot extraction; returns a Pydantic instance if `schema` is a model, else a dict (or `None` if nothing matched). `weights` selects a tuned `.cact` and defaults to whatever the engine already has loaded, so extraction inherits the active tuned model unless you pass another path.
+- `needle.extract(text, schema, system=None, max_new_tokens=512, weights=None)` - one-shot extraction; returns a Pydantic instance if `schema` is a model, else a dict (or `None` if nothing matched). `weights` selects a tuned `.cact` and defaults to whatever the engine already has loaded, so extraction inherits the active tuned model unless you pass another path.
## Defining tools (three equivalent ways)
@@ -103,8 +103,11 @@ Every turn returns one dict:
- `function_calls` is a list of `{"name", "arguments"}`. Read `arguments` directly; it is grammar-guaranteed to match your schema.
- `reasoning` is a short unconstrained derivation of each argument from its source span.
- `confidence` is a calibrated score in [0,1] (see Confidence gating).
+- `suppressed_calls` holds a call the engine withheld because `escalate` is true (confidence below 0.1 or a grounding gate fired); `function_calls` is then empty. Show it to the user to confirm, or treat the turn as a refusal.
+- `Needle(system=...)` prefixes the local `date:` fact automatically unless the text already carries a date; pass `auto_date=False` to opt out.
- `validation.ungrounded`, when present, lists `tool.field` names whose value is not grounded in the input, including date arguments whose year matches nothing in the conversation or the `system` facts. `run()` refuses those calls with `{"error": "ungrounded field"}` unless `strict=False`.
-- `extract()` caps the engine at one call per turn (`needle_set_max_calls`), so a record schema never yields a second record.
+- Speech: `complete(text, audio=clip)` transcribes the clip in a clean context, then answers a text turn that carries the transcript wrapped in `<context>` followed by `text` (or "Fulfill the spoken request." when `text` is empty); the speech codes are not part of that turn and the transcript is returned as `transcript` with `transcript_confidence` (geometric mean token probability of the transcription decode).
+- `extract()` declares the record as the only tool; a turn with a single declared tool is a record extraction, so an escalated record is returned with the `escalate` flag rather than withheld, and `strict` handles grounding.
- Arguments arrive after the engine's deterministic repair step, which grounds them in the request text: a full name in one of a first/last pair is split, a truncated phone number is completed, quoted titles are restored verbatim, place queries recover dropped words and a following street address, weekday and `March 4th` style dates resolve against the `date:` fact, empty optional strings and duplicate calls are dropped. Enumerated parameters are never altered.
## Behaviour contract (important for correct code)
@@ -203,10 +206,10 @@ Adapt by swapping the Literal values for your own and keeping the shapes: closed
## CLI summary
- `needle run --checkpoint <base.safetensors or .pkl> --query "..." --tools tools.json` - JAX reference inference from a checkpoint (dev path; normal inference is the Python `Needle` API above).
-- `needle generate-data` / `needle finetune` / `needle build` - the fine-tuning pipeline.
+- `needle generate-data` / `needle finetune [--layers N]` / `needle build [checkpoint] [--lora adapter] [--layers N]` - the fine-tuning pipeline; `build` defaults to the adapter's base (auto-downloaded Needle 3 base otherwise) and exports only the chosen rung.
- `needle playground` - browser UI.
- `needle fetch [--platform-tag <tag>] [--out <dir>]` - pre-download the inference engine for this machine (or another platform) into the cache; prints the path. For air-gapped devices, also see `NEEDLE_LIB_PATH` and `HF_HUB_OFFLINE` in doc/apis.md.
-- `needle download <org>/<repo>[/<file>.cact] | <platform> [--out <dir>]` - pull a published `.cact` (single-archive repos need only `<org>/<repo>`), or pass a platform folder name (`macos-arm64`, `linux-x86_64`, `wasm`, `wasm-component`, ...) to fetch that platform's engine files into `<out>/<platform>/`. Native runners are marked executable; `wasm-component` contains the WASI Preview 2 component and WIT contract.
+- `needle download needle3 | needle3.safetensors | needle3_enterprise.safetensors | <org>/<repo>[/<file>.cact] | <platform> [--out <dir>]` - pull the base Needle 3 archive, a checkpoint to fine-tune, a published `.cact` (single-archive repos need only `<org>/<repo>`), or pass a platform folder name (`macos-arm64`, `linux-x86_64`, `wasm`, `wasm-component`, ...) to fetch that platform's engine files into `<out>/<platform>/`. Native runners are marked executable; `wasm-component` contains the WASI Preview 2 component and WIT contract.
## Common mistakes to avoid
@@ -214,7 +217,7 @@ Adapt by swapping the Literal values for your own and keeping the shapes: closed
- Do not read `arguments` keys that were not evidenced in the input; optional fields may be absent.
- Do not create one `Needle` per turn for a conversation; reuse the instance so context carries. New tools = new instance.
- `import needle` does not import JAX; only `needle finetune`/`build` do.
-- `weights=` expects a `.cact` (from `needle build`), not a `.safetensors` or `.pkl` checkpoint.
+- `weights=` expects a `.cact` (from `needle build`), not a `.safetensors` or `.pkl` checkpoint. `Needle(tools=..., generation=3)` runs the base Needle 3 archive (fetched once, cached next to the engine); the default without arguments stays the embedded Needle 2.
- Checkpoints and adapters are `.safetensors`; pickle checkpoints still load. The base is `checkpoints/needle3.safetensors` (16 layers); `needle3_enterprise.safetensors` is the 20-layer parent.
- The engine cannot unload weights: once a tuned `.cact` is bound, constructing or calling a base-model agent raises instead of silently answering with those weights. Construct agents that want the base model before any tuned one, or run them in separate processes.
diff --git a/needle/__init__.py b/needle/__init__.py
index c98e035..ac16e03 100644
--- a/needle/__init__.py
+++ b/needle/__init__.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import ctypes
import decimal
+import datetime
import json
import os
import re
@@ -73,6 +74,15 @@ def _library_path(generation=2):
return fetch.fetch_library(version, cache, generation=generation)
+def _base_weights_path(generation):
+ from .agent import fetch
+
+ local = os.path.join(fetch.cache_dir(generation), fetch.base_weights(generation))
+ if os.path.exists(local):
+ return local
+ return fetch.fetch_weights(generation)
+
+
_lib_handles = {}
_active = {}
@@ -147,25 +157,29 @@ def _lib(generation=2):
lib.needle_reset.restype = None
lib.needle_load.argtypes = [ctypes.c_char_p, ctypes.c_uint64]
lib.needle_load.restype = ctypes.c_int
- if hasattr(lib, "needle_set_max_calls"):
- lib.needle_set_max_calls.argtypes = [ctypes.c_int]
- lib.needle_set_max_calls.restype = None
_lib_handles[generation] = lib
return _lib_handles[generation]
class Needle:
- def __init__(self, tools=None, system=None, weights=None, tool_index_path=None, buffer_size=65536):
+ def __init__(self, tools=None, system=None, weights=None, tool_index_path=None, buffer_size=65536,
+ auto_date=True, generation=None):
self._functions = {}
self._weights = os.fspath(weights) if weights is not None else None
- self._generation = _weight_generation(self._weights) if self._weights else 2
+ self._tuned = self._weights is not None
+ if self._tuned:
+ self._generation = _weight_generation(self._weights)
+ else:
+ self._generation = int(generation or 2)
+ if self._generation >= 3:
+ self._weights = _base_weights_path(self._generation)
self._worker = None
self._closed = False
- if weights:
+ if self._tuned:
warnings.warn("finetuning does not update the confidence head, so scores are "
"uncalibrated for tuned weights; this agent reports confidence as None",
stacklevel=2)
- self._system_text = system or ""
+ self._system_text = _with_date_fact(system or "") if auto_date else (system or "")
self._system = self._system_text.encode("utf-8")
tools_json = tools if isinstance(tools, str) else json.dumps(self._resolve(tools))
self._tools_json = tools_json.encode("utf-8")
@@ -219,24 +233,17 @@ class Needle:
return schemas
def _track_props(self):
- return {"n_tools": self._n_tools, "tuned": bool(self._weights),
+ return {"n_tools": self._n_tools, "tuned": self._tuned,
"generation": self._generation}
- def complete(self, text: str = "", max_new_tokens: int = 256,
+ def complete(self, text: str = "", max_new_tokens: int = 512,
audio=None, audio_format="wav", sample_rate=0,
channels=1) -> dict:
_track("complete", self._track_props())
payload = _prepare_audio(audio, audio_format, sample_rate, channels)
return self._complete(text, max_new_tokens, payload)
- def _set_max_calls(self, max_calls: int) -> None:
- if self._worker is not None:
- return
- lib = _lib(self._generation)
- if hasattr(lib, "needle_set_max_calls"):
- lib.needle_set_max_calls(int(max_calls))
-
- def _complete(self, text: str, max_new_tokens: int = 256,
+ def _complete(self, text: str, max_new_tokens: int = 512,
audio=None, ground: bool = True) -> dict:
if audio is not None and self._generation < 3:
raise ValueError("audio requires a Needle 3 model")
@@ -265,11 +272,11 @@ class Needle:
raise RuntimeError(
f"engine returned an unparseable envelope ({err}); this is an "
f"engine bug - please report it with the prompt and schema") from err
- if self._weights:
+ if self._tuned:
response["confidence"] = None
if ground:
_annotate_ungrounded(response, self._tool_schemas, self._seen_years,
- self._system_text)
+ self._system_text, text)
return response
def embed(self, text: str = "", audio=None, audio_format="wav",
@@ -292,7 +299,7 @@ class Needle:
return list(output)
def run(self, query: str = "", max_steps: int = 8,
- max_new_tokens: int = 256, audio=None, audio_format="wav",
+ max_new_tokens: int = 512, audio=None, audio_format="wav",
sample_rate=0, channels=1, strict: bool = True) -> dict:
_track("run", self._track_props())
payload = _prepare_audio(audio, audio_format, sample_rate, channels)
@@ -329,7 +336,7 @@ class Needle:
response["results"] = executed
return response
- def extract(self, text: str, schema: type | dict, max_new_tokens: int = 256,
+ def extract(self, text: str, schema: type | dict, max_new_tokens: int = 512,
strict: bool = True) -> object:
return extract(text, schema, max_new_tokens=max_new_tokens,
weights=self._weights, strict=strict)
@@ -407,9 +414,36 @@ def _source_years(text):
for match in re.finditer(pattern, lowered)}
-def _licensed_years(seen_years, system=None):
+_ISO_STAMP = re.compile(r"\d{4}-\d{2}-\d{2}")
+
+
+def _with_date_fact(system: str) -> str:
+ """Prefix the local date fact unless the caller already supplied one."""
+ if "date:" in system or _ISO_STAMP.search(system):
+ return system
+ now = datetime.datetime.now()
+ fact = now.strftime("date: %Y-%m-%d %a %H:%M")
+ if not system.strip():
+ return fact
+ if system.lstrip().startswith("{"):
+ return system
+ return fact + "; " + system
+
+
+_RELATIVE_CUE = re.compile(
+ r"\b(today|tonight|tomorrow|yesterday|next|this|coming|now|in \d+ (?:days?|weeks?|months?|years?)|"
+ r"monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b", re.IGNORECASE)
+
+
+def _relative_cue(text) -> bool:
+ return bool(text) and _RELATIVE_CUE.search(text) is not None
+
+
+def _licensed_years(seen_years, system=None, relative=True):
+ """Years a date argument may carry: the ones written in the input, plus the
+ system date's year when the input reasons relatively (tomorrow, next week)."""
years = set(seen_years)
- if years and system:
+ if years and system and relative:
years |= _source_years(system)
return years
@@ -446,7 +480,7 @@ def _walk_grounding(schema, arguments, years):
def _temporal_grounding(text, schema, arguments, system=None):
- years = _licensed_years(_source_years(text), system)
+ years = _licensed_years(_source_years(text), system, _relative_cue(text))
return _walk_grounding(schema, arguments, years)
@@ -472,7 +506,15 @@ def _numeric_paths(arguments, path=""):
yield from _numeric_paths(item, f"{path}[{index}]")
+_DATE_FACT = re.compile(r"date:\s*\d{4}-\d{2}-\d{2}(?:\s+[A-Za-z]{3})?(?:\s+\d{2}:\d{2})?|\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?")
+
+
+def _without_date_facts(text):
+ return _DATE_FACT.sub(" ", text or "")
+
+
def _source_numbers(*sources):
+ sources = tuple(_without_date_facts(source) for source in sources)
"""Numeric values written in the source texts, separators normalized."""
text = "\n".join(source for source in sources if source)
return {decimal.Decimal(match.group(0).replace(",", ""))
@@ -502,9 +544,9 @@ def _ungrounded_paths(response):
return grouped
-def _annotate_ungrounded(response, tool_schemas, seen_years, system=None):
+def _annotate_ungrounded(response, tool_schemas, seen_years, system=None, text=None):
calls = response.get("function_calls") or []
- years = _licensed_years(seen_years, system)
+ years = _licensed_years(seen_years, system, _relative_cue(text) if text is not None else True)
if not calls or not years:
return
schemas = {entry.get("name"): entry for entry in tool_schemas}
@@ -544,8 +586,8 @@ def _validate_extraction(text, schema, arguments, response, system=None):
def extract(text: str, schema: type | dict, system: str | None = None,
- max_new_tokens: int = 256, weights: str | None = None,
- strict: bool = True) -> object:
+ max_new_tokens: int = 512, weights: str | None = None,
+ strict: bool = True, generation: int | None = None) -> object:
"""One-shot structured extraction using the matching native engine.
With ``strict=True`` (the default), temporal values that contradict a literal
@@ -553,16 +595,12 @@ def extract(text: str, schema: type | dict, system: str | None = None,
:class:`ExtractionValidationError` instead of being returned silently.
"""
selected = weights
- generation = _weight_generation(selected) if selected else 2
+ generation = _weight_generation(selected) if selected else int(generation or 2)
_track("extract", {"n_tools": 1, "tuned": bool(selected),
"generation": generation})
- agent = Needle(tools=[schema], system=system, weights=selected)
+ agent = Needle(tools=[schema], system=system, weights=selected, generation=generation)
try:
- agent._set_max_calls(1)
- try:
- response = agent._complete(text, max_new_tokens)
- finally:
- agent._set_max_calls(0)
+ response = agent._complete(text, max_new_tokens)
finally:
agent.close()
calls = response.get("function_calls") or []
diff --git a/needle/agent/fetch.py b/needle/agent/fetch.py
index c1736a4..0733b08 100644
--- a/needle/agent/fetch.py
+++ b/needle/agent/fetch.py
@@ -12,6 +12,12 @@ ENGINE_VERSIONS = {
3: "3.0.0",
}
+BASE_WEIGHTS = {
+ 2: "needle2.cact",
+ 3: "needle3.cact",
+}
+CHECKPOINT_PREFIX = "checkpoints"
+
# Backwards-compatible aliases for callers that explicitly fetch Needle 2.
HF_REPO = ENGINE_REPOS[2]
ENGINE_VERSION = ENGINE_VERSIONS[2]
@@ -110,6 +116,59 @@ def download_platform(name, out_dir, generation=2):
return out
+def base_weights(generation=2):
+ try:
+ return BASE_WEIGHTS[int(generation)]
+ except (KeyError, TypeError, ValueError) as exc:
+ raise ValueError(f"unsupported Needle generation: {generation}") from exc
+
+
+def cache_dir(generation=2):
+ return os.path.join(os.path.expanduser("~"), ".cache", "cactus-needle",
+ f"v{int(generation)}", engine_version(generation))
+
+
+def fetch_weights(generation=2, dest_dir=None):
+ """Download the base .cact archive of a generation (cached next to its engine)."""
+ import shutil
+ from huggingface_hub import hf_hub_download
+
+ name = base_weights(generation)
+ dest_dir = dest_dir or cache_dir(generation)
+ out = os.path.join(dest_dir, name)
+ if os.path.exists(out):
+ return out
+ _register_download(generation)
+ cached = hf_hub_download(repo_id=engine_repo(generation), filename=name, repo_type="model")
+ os.makedirs(dest_dir, exist_ok=True)
+ shutil.copyfile(cached, out)
+ return out
+
+
+def fetch_checkpoint(name, dest_dir, generation=3):
+ """Download a training checkpoint (needle3.safetensors, ...) for finetune/build."""
+ import shutil
+ from huggingface_hub import hf_hub_download
+ from huggingface_hub.errors import EntryNotFoundError
+
+ repo = engine_repo(generation)
+ _register_download(generation)
+ base = os.path.basename(name)
+ cached = None
+ for candidate in (f"{CHECKPOINT_PREFIX}/{base}", base):
+ try:
+ cached = hf_hub_download(repo_id=repo, filename=candidate, repo_type="model")
+ break
+ except EntryNotFoundError:
+ continue
+ if cached is None:
+ raise FileNotFoundError(f"{base} is not published in {repo}")
+ os.makedirs(dest_dir, exist_ok=True)
+ out = os.path.join(dest_dir, base)
+ shutil.copyfile(cached, out)
+ return out
+
+
def fetch_library(version=None, dest_dir=None, tag=None, generation=2):
from huggingface_hub import hf_hub_download
diff --git a/needle/cli.py b/needle/cli.py
index dc3a9d7..5279596 100644
--- a/needle/cli.py
+++ b/needle/cli.py
@@ -6,12 +6,12 @@ import threading
HELP = """usage: needle <command> [options]
- run run a checkpoint on a query
- finetune train a LoRA adapter on JSONL data
+ run run a checkpoint on a query (JAX, Needle 3)
+ finetune train a LoRA adapter on JSONL data (--layers N for a rung)
generate-data synthesise training data via OpenRouter
- build export a checkpoint to a .cact archive
- download download weights or an engine build
- fetch fetch the engine for this platform
+ build export a checkpoint (+ adapter) to a .cact archive
+ download needle3 | needle3.safetensors | <platform> | <org>/<repo>[/<file>.cact]
+ fetch fetch the engine library for this platform
playground serve the browser playground
needle <command> --help for the options of one command.
@@ -25,6 +25,25 @@ def _weights_spec(spec):
return "/".join(parts[:2]), "/".join(parts[2:]) or None
+def _download_target(spec):
+ """Classify a `needle download` spec: engine build, base weights, checkpoint or hub archive."""
+ from .agent import fetch
+
+ if "/" in spec:
+ return "hub", spec
+ if spec in fetch.PLATFORMS:
+ return "platform", spec
+ name = spec[:-5] if spec.endswith(".cact") else spec
+ if name in ("needle2", "needle3"):
+ return "base", int(name[-1])
+ if spec.endswith((".safetensors", ".pkl")):
+ return "checkpoint", spec
+ raise SystemExit(
+ f"unknown download {spec!r}: pass needle3 (base weights), needle3.safetensors or "
+ f"needle3_enterprise.safetensors (a checkpoint to fine-tune), a platform ("
+ + ", ".join(fetch.PLATFORMS) + "), or <org>/<repo>[/<file>.cact]")
+
+
_ABSL_LOG_START = re.compile(rb"^[EIWF]\d{4} \d\d:\d\d:\d\d")
_NOISY_LOG_HEADER = re.compile(
rb"\] (?:Fusion: .*gemm_fusion|Computation: .*_computation|Delay kernel timed out)"
@@ -170,8 +189,9 @@ def main():
p.add_argument("--output", type=str, default=None)
p = sub.add_parser("build")
- p.add_argument("checkpoint", type=str,
- help="Base checkpoint (.safetensors or .pkl) to export")
+ p.add_argument("checkpoint", type=str, nargs="?", default=None,
+ help="Base checkpoint (.safetensors or .pkl); defaults to the adapter's "
+ "base, else the Needle 3 base (auto-downloads)")
p.add_argument("--lora", type=str, default=None, help="LoRA adapter to merge before export")
p.add_argument("--out", type=str, default=None, help="Output .cact path")
p.add_argument("--upload", action="store_true", help="Push the .cact to $NEEDLE_HF_REPO")
@@ -182,7 +202,9 @@ def main():
p = sub.add_parser("download")
p.add_argument("spec", type=str,
- help="Platform folder (e.g. macos-arm64), or Hugging Face spec: "
+ help="needle3 (base weights), needle3.safetensors or "
+ "needle3_enterprise.safetensors (checkpoints to fine-tune), a platform "
+ "folder (e.g. macos-arm64), or a Hugging Face spec: "
"<org>/<repo>/<file>.cact, or <org>/<repo> if it holds one archive")
p.add_argument("--out", type=str, default=".", help="Directory to place the files")
p.add_argument("--generation", type=int, choices=[2, 3], default=2,
@@ -228,11 +250,9 @@ def main():
import shutil
from huggingface_hub import hf_hub_download, list_repo_files
from .agent import fetch
- if "/" not in args.spec:
- if args.spec not in fetch.PLATFORMS:
- raise SystemExit("unknown platform, pick one of: "
- + ", ".join(fetch.PLATFORMS))
- paths = fetch.download_platform(args.spec, args.out,
+ kind, target = _download_target(args.spec)
+ if kind == "platform":
+ paths = fetch.download_platform(target, args.out,
generation=args.generation)
for path in paths:
print(f" {'file':<9} {path} {os.path.getsize(path) / 1e6:.2f} MB")
@@ -240,6 +260,17 @@ def main():
if os.path.basename(p) in ("needle", "needle.exe")), None)
if runner:
print(f" {'next':<9} {runner} --tools tools.json --serve")
+ elif kind == "base":
+ os.makedirs(args.out, exist_ok=True)
+ path = fetch.fetch_weights(target, args.out)
+ print(f" {'weights':<9} {path} {os.path.getsize(path) / 1e6:.2f} MB")
+ print(f" {'next':<9} needle.Needle(weights={path!r}, tools=[...])")
+ elif kind == "checkpoint":
+ generation = 2 if target.startswith("needle2") else 3
+ path = fetch.fetch_checkpoint(target, os.path.join(args.out, fetch.CHECKPOINT_PREFIX),
+ generation=generation)
+ print(f" {'file':<9} {path} {os.path.getsize(path) / 1e6:.2f} MB")
+ print(f" {'next':<9} needle finetune data.jsonl --checkpoint {path} [--layers N]")
else:
fetch._register_download(args.generation)
repo, filename = _weights_spec(args.spec)
diff --git a/needle/model/finetune.py b/needle/model/finetune.py
index b2cfaad..2b8769f 100644
--- a/needle/model/finetune.py
+++ b/needle/model/finetune.py
@@ -466,13 +466,17 @@ def build_main(args):
from .architecture import effective_kv_window
from .export import vocab_rows_for, write_export
- params, config, _ = load_checkpoint(args.checkpoint, return_run=True)
+ adapter = read_adapter(args.lora) if args.lora else None
+ checkpoint = args.checkpoint
+ if not checkpoint and adapter and adapter.get("base") and os.path.exists(adapter["base"]):
+ checkpoint = adapter["base"]
+ checkpoint = checkpoint or DEFAULT_BASE
+ params, config, _ = load_checkpoint(checkpoint, return_run=True)
layers = getattr(args, "layers", None)
adapter_qat_bits = None
adapter_qat_bits_map = None
if args.lora:
- adapter = read_adapter(args.lora)
adapter_layers = adapter.get("layers")
if adapter_layers and layers and int(layers) != int(adapter_layers):
raise ValueError(
@@ -509,7 +513,7 @@ def build_main(args):
if not bits and not bits_map:
bits = "4"
- out = args.out or (os.path.splitext(os.path.basename(args.checkpoint))[0] + ".cact")
+ out = args.out or (os.path.splitext(os.path.basename(checkpoint))[0] + ".cact")
info = write_export(params, config, out,
bits=int(bits) if bits else 4,
bits_map=bits_map,
diff --git a/needle/model/run.py b/needle/model/run.py
index 2784fb4..9fd447c 100644
--- a/needle/model/run.py
+++ b/needle/model/run.py
@@ -90,7 +90,12 @@ def load_checkpoint(path, return_run=False):
f"(got format_version={version!r}). Old encoder-decoder/tool-calling "
f"checkpoints are incompatible with this branch."
)
- config = TransformerConfig.from_saved(ckpt["config"])
+ saved = ckpt["config"] if isinstance(ckpt["config"], dict) else dict(vars(ckpt["config"]))
+ if "attn_dim" in saved and "qk_head_dim" not in saved:
+ raise ValueError(
+ f"{path} is a Needle 2 checkpoint; this package fine-tunes and builds Needle 3. "
+ "Use cactus-needle 2.x for it: pip install 'cactus-needle<3'")
+ config = TransformerConfig.from_saved(saved)
params = {k: v for k, v in ckpt["params"].items() if not k.startswith("mtp_")}
if return_run:
return params, config, ckpt.get("run") or {}
diff --git a/tests/test_fetch.py b/tests/test_fetch.py
index 520e071..d1f9041 100644
--- a/tests/test_fetch.py
+++ b/tests/test_fetch.py
@@ -25,6 +25,58 @@ def test_legacy_lib_override_cannot_capture_v3(tmp_path, monkeypatch):
assert needle._library_path(3) == str(v3)
+def test_download_target_kinds():
+ import pytest
+ from needle.cli import _download_target
+
+ assert _download_target("macos-arm64") == ("platform", "macos-arm64")
+ assert _download_target("needle3") == ("base", 3)
+ assert _download_target("needle2.cact") == ("base", 2)
+ assert _download_target("needle3.safetensors") == ("checkpoint", "needle3.safetensors")
+ assert _download_target("needle3_enterprise.safetensors") == ("checkpoint", "needle3_enterprise.safetensors")
+ assert _download_target("acme/tuned/model.cact") == ("hub", "acme/tuned/model.cact")
+ with pytest.raises(SystemExit, match="unknown download"):
+ _download_target("needle4")
+
+
+def test_fetch_weights_copies_the_base_archive_and_reuses_it(tmp_path, monkeypatch):
+ from needle.agent import fetch
+
+ archive = tmp_path / "needle3.cact"
+ archive.write_bytes(b"weights")
+ calls = []
+
+ def fake_download(**kwargs):
+ calls.append(kwargs["filename"])
+ return str(archive)
+
+ monkeypatch.setattr(fetch, "_register_download", lambda generation: None)
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", fake_download)
+ dest = tmp_path / "cache"
+ out = fetch.fetch_weights(3, str(dest))
+ assert out == str(dest / "needle3.cact") and open(out, "rb").read() == b"weights"
+ assert calls == ["needle3.cact"]
+ assert fetch.fetch_weights(3, str(dest)) == out and calls == ["needle3.cact"]
+
+
+def test_fetch_checkpoint_prefers_the_checkpoints_folder(tmp_path, monkeypatch):
+ from huggingface_hub.errors import EntryNotFoundError
+ from needle.agent import fetch
+
+ source = tmp_path / "needle3.safetensors"
+ source.write_bytes(b"ckpt")
+
+ def fake_download(**kwargs):
+ if kwargs["filename"] != "checkpoints/needle3.safetensors":
+ raise EntryNotFoundError("missing")
+ return str(source)
+
+ monkeypatch.setattr(fetch, "_register_download", lambda generation: None)
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", fake_download)
+ out = fetch.fetch_checkpoint("needle3.safetensors", str(tmp_path / "dl" / "checkpoints"))
+ assert out.endswith("checkpoints/needle3.safetensors") and open(out, "rb").read() == b"ckpt"
+
+
def test_weights_spec_parsing():
from needle.cli import _weights_spec
diff --git a/tests/test_finetune.py b/tests/test_finetune.py
index 6c67a53..4bf0c91 100644
--- a/tests/test_finetune.py
+++ b/tests/test_finetune.py
@@ -145,6 +145,21 @@ def test_finetune_on_a_rung_builds_that_depth(tiny_checkpoint, tmp_path):
bits="4", layers=3))
+def test_build_without_a_checkpoint_uses_the_adapter_base(tiny_checkpoint, tmp_path):
+ from needle.model.finetune import finetune_local, build_main
+ from needle.model.export import read_export
+
+ data = tmp_path / "data.jsonl"
+ _write_data(data)
+ adapter = tmp_path / "adapter.safetensors"
+ finetune_local(_finetune_args(data, tiny_checkpoint, adapter, tmp_path / "ck"))
+ out = str(tmp_path / "from_adapter.cact")
+ build_main(types.SimpleNamespace(checkpoint=None, lora=str(adapter), out=out,
+ upload=False, bits="4"))
+ header, _ = read_export(out)
+ assert header["num_layers"] == 4
+
+
def test_finetune_rng_is_controlled_by_seed():
from needle.model.finetune import _training_rng
diff --git a/tests/test_run.py b/tests/test_run.py
index 75e4c3f..1f1911d 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -26,6 +26,19 @@ def test_build_prompt_matches_training_template():
assert "do the thing" in out
+def test_needle2_checkpoint_is_rejected_with_a_version_hint(tmp_path):
+ import pickle
+ import pytest
+ from needle.model.run import load_checkpoint
+
+ path = tmp_path / "needle2.pkl"
+ with open(path, "wb") as handle:
+ pickle.dump({"format_version": 2, "params": {}, "config": {
+ "d_model": 512, "attn_dim": 512, "num_heads": 8, "num_layers": 27}}, handle)
+ with pytest.raises(ValueError, match="Needle 2 checkpoint.*cactus-needle<3"):
+ load_checkpoint(str(path))
+
+
def test_main_loads_tools_file_and_runs(tiny_checkpoint, tmp_path, capsys):
from needle.model.run import main
diff --git a/tests/test_weights.py b/tests/test_weights.py
index b9b90d0..f6f25fe 100644
--- a/tests/test_weights.py
+++ b/tests/test_weights.py
@@ -101,6 +101,30 @@ def _tuned_agent(path):
return needle.Needle(tools="[]", weights=path)
+def test_generation_3_without_weights_runs_the_base_archive(engine, tuned_v3, monkeypatch):
+ import needle
+
+ monkeypatch.setattr(needle, "_base_weights_path", lambda generation: tuned_v3)
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ agent = needle.Needle(tools="[]", generation=3)
+ assert agent._generation == 3 and agent._tuned is False
+ response = agent.complete("hello")
+ assert response.get("confidence", "kept") is not None
+ assert any(call[0] == "worker_start" and call[3] == tuned_v3
+ for call in engine if isinstance(call, tuple))
+ assert agent._track_props()["tuned"] is False
+
+
+def test_default_agent_is_still_the_embedded_needle_2(engine):
+ import needle
+
+ agent = needle.Needle(tools="[]")
+ assert agent._generation == 2 and agent._weights is None
+ agent.complete("hello")
+ assert "complete" in engine
+
+
def test_base_agent_and_tuned_worker_coexist(engine, tuned):
import needle