cactus-needle 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,289 @@
1
+ Metadata-Version: 2.4
2
+ Name: cactus-needle
3
+ Version: 2.0.0
4
+ Summary: A 14MB foundation tool-calling model for tiny devices: inference, LoRA finetuning, and build.
5
+ License: Apache-2.0
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: huggingface_hub
10
+ Requires-Dist: numpy
11
+ Requires-Dist: jax
12
+ Requires-Dist: jaxlib
13
+ Requires-Dist: flax>=0.12.8
14
+ Requires-Dist: optax
15
+ Requires-Dist: sentencepiece
16
+ Provides-Extra: gpu
17
+ Requires-Dist: jax[cuda12]; extra == "gpu"
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest; extra == "test"
20
+ Requires-Dist: pydantic; extra == "test"
21
+ Dynamic: license-file
22
+
23
+ ![Needle](assets/banner.png)
24
+
25
+ # Needle 2
26
+
27
+ Needle 2 is an open 45M-parameter model for tool calling, device use and structured extraction. The whole model is a single 14MB binary that runs a full session in about 28MB of RAM. It is built on our Simple Attention Network findings, compressed to CQ2-bit with Cactus Quants, and baked into its own engine. On the benchmarks below, Needle 2 trades wins with other small models like FunctionGemma 270M, LFM2.5 230M and Apple FM, at 5x to 70x smaller, and 2 bits against their f16.
28
+
29
+ This repository is the Python package: inference, LoRA fine-tuning, and export. `pip install cactus-needle`, describe your tools, and call them from Python. The inference engine is fetched once from Hugging Face and cached; there is nothing else to build.
30
+
31
+ - **Self-contained**: weights baked into a single 14MB engine; no separate model files to manage, and inference does no network.
32
+ - **Simple contract**: tool calls come back as structured data, text in, JSON out; a byte-level grammar compiled from your schemas constrains every token.
33
+ - **Confidence-gated**: every response carries a calibrated confidence score from a learned head; set a threshold, act above it, escalate below it.
34
+ - **Tool retrieval**: declare a large catalogue and a built-in retrieval head renders only the top five tools per turn, with the grammar constrained to that subset.
35
+ - **Bounded memory**: a 256-token sliding window with the tools pinned as KV sinks, so total memory stays near 28MB no matter how long the conversation runs.
36
+
37
+ Weights: [huggingface.co/Cactus-Compute/needle2](https://huggingface.co/Cactus-Compute/needle2) · source: [github.com/cactus-compute/needle](https://github.com/cactus-compute/needle).
38
+
39
+ ![Size-quality frontier: mobile-class and below](assets/frontier.png)
40
+
41
+ ## Simple Attention Network
42
+
43
+ Needle 2 is a Simple Attention Network, our dense small-model recipe: a Hadamard MLP in place of the FFN, GQA attention, engram key-value memory, and multi-lane hyper-connections. See the paper for the design and ablations: [arXiv:2607.18363](https://arxiv.org/abs/2607.18363).
44
+
45
+ ![Simple Attention Network architecture](assets/architecture.png)
46
+
47
+ Each block carries its update rule. Here x̂ is the RMS-normalised flattening of the four residual streams, H the orthonormal Walsh-Hadamard transform (a fixed matrix, applied in n log n time with no weights to read), (kₜ, vₜ) rows gathered from hashed n-gram tables, and P the doubly-stochastic normalisation of the routing logits A, computed by Sinkhorn iteration; a, b, g and all σ-gates are learned and input-dependent. Both attention and MLP residuals are sandwich-normed and gated, the engram sites fire at two layers, and decoding is constrained by a byte-level grammar compiled from the declared schemas.
48
+
49
+ ## Quickstart
50
+
51
+ ```sh
52
+ pip install cactus-needle
53
+ ```
54
+
55
+ Needle reads your tool descriptions to decide what to call and how to fill arguments, so describing them well is the whole game. You can do it three ways, from least to most control.
56
+
57
+ **Simple**: decorate a function. The signature gives the argument types, the docstring is the tool description, and `run()` completes the loop: model picks the call, Needle executes your function, feeds the result back, and returns the model's final answer.
58
+
59
+ ```python
60
+ import needle
61
+
62
+ @needle.tool
63
+ def get_weather(city: str):
64
+ "Get the current weather for a city."
65
+ return {"city": city, "temp_c": 27, "sky": "clear"}
66
+
67
+ agent = needle.Needle(tools=[get_weather])
68
+ print(agent.run("what's it like in Lagos right now?")["reasoning"])
69
+ ```
70
+
71
+ **Medium**: describe each argument and offer choices. Needle reads a Google-style `Args:` block for per-parameter descriptions; a default makes an argument optional; a `Literal` becomes a fixed set the model must choose from (it cannot emit anything else).
72
+
73
+ ```python
74
+ from typing import Literal
75
+
76
+ @needle.tool
77
+ def set_thermostat(temperature: int, mode: Literal["heat", "cool", "auto"] = "auto"):
78
+ """Set the thermostat.
79
+
80
+ Args:
81
+ temperature: target temperature in Celsius
82
+ mode: heating strategy to use
83
+ """
84
+ return {"temperature": temperature, "mode": mode}
85
+
86
+ agent = needle.Needle(tools=[set_thermostat])
87
+ agent.run("make it 21 and cool the room")
88
+ ```
89
+
90
+ **Advanced**: constrain the values with `needle.Field`, attached inline via `Annotated`. Ranges, patterns, lengths, and item counts are compiled into the decode grammar, so the model can only ever emit values that satisfy them.
91
+
92
+ ```python
93
+ from typing import Annotated
94
+
95
+ @needle.tool
96
+ def send_money(
97
+ amount: Annotated[float, needle.Field(gt=0, le=10000, description="USD, up to 10,000")],
98
+ to: Annotated[str, needle.Field(pattern=r"^@[a-z0-9_]+$", description="recipient handle")],
99
+ memo: Annotated[str, needle.Field(max_length=80)] = "",
100
+ ):
101
+ "Send money to a handle."
102
+ return {"sent": amount, "to": to}
103
+ ```
104
+
105
+ `Field` supports `description`, `enum`, `const`, `ge`/`le`/`gt`/`lt`, `multiple_of`, `min_length`/`max_length`, `pattern`, `format`, `min_items`/`max_items`, and `unique_items`.
106
+
107
+ **Extraction**: to pull structured data out of text, declare the shape and call `extract()`. Pass a Pydantic model and you get a typed object back.
108
+
109
+ ```python
110
+ from pydantic import BaseModel
111
+
112
+ class Invoice(BaseModel):
113
+ vendor: str
114
+ total: float
115
+ due_date: str
116
+
117
+ invoice = needle.extract("Invoice from Acme Corp, $1,200.00, due 2026-09-01", Invoice)
118
+ print(invoice.vendor, invoice.total) # -> Acme Corp 1200.0
119
+ ```
120
+
121
+ **By hand** - the decorator just builds a JSON schema; you can pass that schema directly, which is exactly what Needle consumes. This is how you set descriptions and constraints without the decorator:
122
+
123
+ ```python
124
+ tools = [{
125
+ "name": "set_lights",
126
+ "description": "Turn a room's lights on or off and set brightness",
127
+ "parameters": {
128
+ "type": "object",
129
+ "properties": {
130
+ "room": {"type": "string", "description": "which room to control"},
131
+ "on": {"type": "boolean"},
132
+ "brightness": {"type": "integer", "minimum": 0, "maximum": 100},
133
+ },
134
+ "required": ["room", "on"],
135
+ },
136
+ }]
137
+ agent = needle.Needle(tools=tools)
138
+ ```
139
+
140
+ Prefer to drive the loop yourself instead of `run()`? `complete()` returns the raw call and you execute it:
141
+
142
+ ```python
143
+ import json
144
+ response = agent.complete("dim the living room to 30")
145
+ if response["type"] == "call":
146
+ result = set_lights(**response["function_calls"][0]["arguments"])
147
+ response = agent.complete(json.dumps(result)) # feed the result back
148
+ ```
149
+
150
+ With a large catalogue, persist tool embeddings across runs with `needle.Needle(tools=..., tool_index_path="tools.idx")`. Every turn returns one JSON object:
151
+
152
+ ```json
153
+ {
154
+ "type": "call",
155
+ "success": true,
156
+ "error": null,
157
+ "error_code": null,
158
+ "function_calls": [ { "name": "set_lights", "arguments": { "room": "living room", "on": true, "brightness": 30 } } ],
159
+ "reasoning": "'living room' -> room; 'dim' -> on true, brightness 30",
160
+ "confidence": 0.94,
161
+ "prefill_tps": 4300.0,
162
+ "decode_tps": 850.0
163
+ }
164
+ ```
165
+
166
+ ## Playground
167
+
168
+ Try any model in the browser: pick a preset, edit the tools or prompt, and Run. Follow-up queries continue the same conversation.
169
+
170
+ ```sh
171
+ needle playground # base model, http://127.0.0.1:7860
172
+ needle playground --weights my.cact # a tuned model
173
+ ```
174
+
175
+ The server downloads and initializes the model before serving, so the first query is instant. The **Finetune on these tools** button runs the fine-tuning pipeline below from the UI and hands back a downloadable `.cact`.
176
+
177
+ ## Behaviour
178
+
179
+ Needle solves every problem as a function call. The context declares what may be called; the model answers with calls. Performing an action and extracting structured data are the same operation, the only difference is what you declare.
180
+
181
+ - 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.
182
+ - Arguments contain only values evidenced by the input. An optional field with no evidence is omitted, not guessed; omission is the field-level `[]`.
183
+ - `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.
184
+ - 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 step may answer in plain text from the results: `"type": "respond"` with empty `function_calls`.
185
+ - A session shares one toolset. Later turns are bare queries against the same tools; `reset()` rewinds the conversation and keeps the tools loaded.
186
+
187
+ ## Extraction
188
+
189
+ Extraction is not a separate mode - it is tool calling with one tool. Declare the record as the only schema and pass the content where the query goes; the returned call's `arguments` are the extracted fields. With one declared tool the grammar admits exactly one call of that name, so schema conformance is guaranteed rather than requested. Use the `extract()` helper for a typed result (shown in Quickstart), or pass a plain schema and read the call:
190
+
191
+ ```python
192
+ receipt = [{
193
+ "name": "receipt",
194
+ "description": "A purchase receipt shared as text",
195
+ "parameters": {
196
+ "type": "object",
197
+ "properties": {
198
+ "merchant": {"type": "string"},
199
+ "total": {"type": "number"},
200
+ "currency": {"type": "string"},
201
+ "line_items": {"type": "array", "items": {"type": "object"}},
202
+ },
203
+ "required": ["merchant", "total"],
204
+ },
205
+ }]
206
+ agent = needle.Needle(tools=receipt)
207
+ print(agent.complete("GreenMart receipt: oat milk 3.50, total 7.75 paid by visa")["function_calls"])
208
+ # -> [{"name": "receipt", "arguments": {"merchant": "GreenMart", "total": 7.75}}]
209
+ ```
210
+
211
+ Because it is the same operation, everything else applies unchanged: `confidence` gates the extraction, unsupported input returns the empty call `[]`, and fine-tuning uses the same data format (the record as the tool, the passage as the query).
212
+
213
+ ## System facts
214
+
215
+ An optional system turn carries environment state as facts, never instructions:
216
+
217
+ ```python
218
+ agent = needle.Needle(tools=tools, system="date: 2026-07-21 Tue 14:30; locale: en-US; device: phone; battery: 62%")
219
+ ```
220
+
221
+ Recognized keys are `date`, `locale`, `device`, `battery`, `network`, `location`, `user`, and `assistant`. The model resolves relative language against them: "tomorrow at 7" becomes an absolute time only when a `date:` fact licenses it, otherwise the human phrase passes through verbatim. `assistant:` declares the identity the model binds to. Needle trains with and without the turn, so omitting it is safe; instructions placed there do not steer the model.
222
+
223
+ ## Tool retrieval
224
+
225
+ Five or fewer declared tools render directly. Above that, retrieval engages: at init every tool schema is embedded once by a built-in contrastive head, each turn embeds the query, and only the five highest-scoring tools enter the context, with the grammar rebuilt over just that subset. An unselected tool is unreachable, not merely unlikely. `tool_index_path` persists the embeddings on disk, keyed by a fingerprint over the schemas and the model; a matching fingerprint loads instantly, a changed schema re-embeds only what changed.
226
+
227
+ ## Confidence
228
+
229
+ The `confidence` field is the minimum of two signals: a calibrated post-hoc head that scores the full prompt plus the call the model just produced, and the decoding probability of the call tokens. A call is accepted only when both agree, so the failure mode is escalation, not wrong execution. The contract: pick a threshold for your product, act at or above it, re-ask or route to a bigger model below it. Off-topic requests return the empty call `[]`.
230
+
231
+ ## Fine-tuning
232
+
233
+ Needle fine-tunes with LoRA on the frozen base and merges the adapter at export, so a run is cheap and the tuned model is still a single `.cact` that runs on the same engine. The workflow is: (optionally) synthesize data, LoRA fine-tune, then build a tuned `.cact`.
234
+
235
+ **Data format.** A JSONL file, one example per line. `reasoning` is optional; an off-topic example has `answers: []`.
236
+
237
+ ```json
238
+ {"query": "dim the kitchen to 10", "tools": [{"name": "set_lights", "parameters": {"type": "object", "properties": {"room": {"type": "string"}, "brightness": {"type": "integer"}}, "required": ["room"]}}], "answers": [{"name": "set_lights", "arguments": {"room": "kitchen", "brightness": 10}}], "reasoning": "'kitchen' -> room; 'dim to 10' -> brightness 10"}
239
+ ```
240
+
241
+ **1. Synthesize data (optional).** Needs `OPENROUTER_API_KEY`. Seed from a tool schema file, or expand an existing set:
242
+
243
+ ```sh
244
+ export OPENROUTER_API_KEY=sk-or-...
245
+ needle generate-data --tools my_tools.json --num-samples 500 --output data.jsonl
246
+ needle generate-data --augment data.jsonl --num-samples 500 # expand an existing JSONL
247
+ ```
248
+
249
+ **2. LoRA fine-tune.** The base checkpoint auto-downloads from Hugging Face if you do not pass `--checkpoint`. `--generate N` first synthesizes N more examples from the tools in your data (also needs `OPENROUTER_API_KEY`).
250
+
251
+ ```sh
252
+ needle finetune data.jsonl --epochs 3
253
+ needle finetune data.jsonl --epochs 3 --generate 300 --lora-rank 16 --lora-alpha 32
254
+ ```
255
+
256
+ Key options: `--lora-rank` (default 16), `--lora-alpha` (32), `--lr` (1e-4), `--batch-size` (16), `--max-len` (1024), `--checkpoint <base.pkl>`, `--out <adapter.pkl>`. The adapter is written to `checkpoints/needle_lora.pkl`.
257
+
258
+ **3. Build a tuned `.cact`.** Merge the adapter into the base and quantize. The base auto-downloads if absent.
259
+
260
+ ```sh
261
+ needle build checkpoints/needle2.pkl --lora checkpoints/needle_lora.pkl --out my_needle.cact
262
+ ```
263
+
264
+ Add `--bits 2` (default 4) for a smaller model, or set `NEEDLE_HF_REPO=<you>/<model>` and pass `--upload` to publish the `.cact`.
265
+
266
+ **4. Run it.** The engine is weights-agnostic, so a tuned `.cact` runs on it directly - no recompilation:
267
+
268
+ ```python
269
+ import needle
270
+ agent = needle.Needle(weights="my_needle.cact", tools=[...])
271
+ agent.run("...")
272
+ ```
273
+
274
+ ## Citation
275
+
276
+ Needle 2 is built by the Cactus Compute team. If you use it in your work, please cite:
277
+
278
+ ```bibtex
279
+ @misc{needle2_2026,
280
+ title = {Needle 2: A 45M-Parameter Foundation Tool-Calling Model for Tiny Devices},
281
+ author = {Ndubuaku, Henry and Mosoyan, Karen and Mroz, Jakub and Cylich, Noah and
282
+ Kumar, Satyajit and Sandhu, Parkirat and Shemet, Roman and Lee, Justin H.},
283
+ year = {2026},
284
+ organization = {Cactus Compute, Inc.},
285
+ howpublished = {\url{https://github.com/cactus-compute/needle}}
286
+ }
287
+ ```
288
+
289
+ Reach out on founders@cactuscompute.com for partnerships, collaborations, synergies and deploying Needle2 in your product.
@@ -0,0 +1,26 @@
1
+ cactus_needle-2.0.0.dist-info/licenses/LICENSE,sha256=QBUOMBab7rhxMMn2atVjAkMniNkx7sHkzoCHXYON-FU,1071
2
+ needle/__init__.py,sha256=BLacnlhy153547QeD_mAxiuFtO3zRw_KZqKYCgfrTzI,4864
3
+ needle/cli.py,sha256=tgSfeFDwd6vyfl221nu63gbPprFePy_HkNe7Y6tAV0I,7263
4
+ needle/agent/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ needle/agent/fetch.py,sha256=_pP1IlIz3FMkyDHkHgfX-7DAQ-CQfzpgzXsyXf2HYDg,1522
6
+ needle/agent/tools.py,sha256=5_o4xZi734FlGglQlUcKqx7nrHh-athDbMPyQqdps80,6070
7
+ needle/model/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ needle/model/architecture.py,sha256=E3Op1v2lapJBRRbALpEMH_8t9CQtoIAm_75Q6rnjUzM,23848
9
+ needle/model/decode.py,sha256=dC_kBb75-ozKL9w0dfK-i8ubC_H-c4_xGB4eGezmq3k,16660
10
+ needle/model/export.py,sha256=NvrOsZC5sjVN15RbS24LD0O5HUUlJ2OP7OP40CKaMMY,21404
11
+ needle/model/finetune.py,sha256=ojL8YFA-VCqv889ThD75zmFyGieploo12_H6eLH0Coc,15375
12
+ needle/model/quantize.py,sha256=YG7VqcMHPwyqs9YcWyhvLy3S-A9J3GhmGtMfQFTS9Uc,11676
13
+ needle/model/run.py,sha256=pHQFVpYXZz_Ncwyb7Js6nMYB_kZTMbWnNXr-4iyhFDA,7898
14
+ needle/model/tokenizer.model,sha256=CHG449944N18zCNuGH_AVfdc1X6-O-x2yoEDAwuP5lk,132396
15
+ needle/model/tokenizer.py,sha256=vgzq4O5YDNVZel8P9wy4hsZU6KEs0XASgGNatq5Iv5o,3620
16
+ needle/model/tokenizer.vocab,sha256=7YNa_1sqPKZ7WJaQbdRxqwzhJibWmdkOc248fkupseM,113001
17
+ needle/playground/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ needle/playground/app.js,sha256=hqIPCRswooU6vyCJ4O7OeF_sJju_FKJx6CPlrBb5xwE,20802
19
+ needle/playground/index.html,sha256=-CdPtXgfP3QH37rBWIrnMkI7GZxHyaWn_hqbfeAu7C8,5857
20
+ needle/playground/server.py,sha256=3K8ylLe2lwioy5OI0UVi4MAGOjO8N8OVondyAElzGvI,7291
21
+ needle/playground/style.css,sha256=aVkkigyzqP0IYBF9r1ClrfoKzRCBpoRqGX-FTpvX_Nc,13162
22
+ cactus_needle-2.0.0.dist-info/METADATA,sha256=4WzvGE7buJOj2qqDebzkscwGAqtU0JyJNAhNMwhoW4E,15515
23
+ cactus_needle-2.0.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
24
+ cactus_needle-2.0.0.dist-info/entry_points.txt,sha256=U0xf5BvvRpPBG9x0er3fL182mqMcDboUKT5S4s7x0zk,43
25
+ cactus_needle-2.0.0.dist-info/top_level.txt,sha256=0pIQd3d32sCz0S9qZWoHPJunF89pMtvAGwzG3B53ebg,7
26
+ cactus_needle-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ needle = needle.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cactus Compute
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ needle
needle/__init__.py ADDED
@@ -0,0 +1,124 @@
1
+ import ctypes
2
+ import json
3
+ import os
4
+ import sys
5
+
6
+ from .agent.tools import Field, build_schema, pydantic_schema, tool, _is_pydantic_model
7
+
8
+ __version__ = "2.0.0"
9
+ __all__ = ["Needle", "tool", "Field", "extract", "__version__"]
10
+
11
+
12
+ def _library_path():
13
+ from .agent import fetch
14
+
15
+ here = os.path.dirname(os.path.abspath(__file__))
16
+ local = os.path.join(here, fetch._lib_name())
17
+ if os.path.exists(local):
18
+ return local
19
+ cache = os.path.join(os.path.expanduser("~"), ".cache", "cactus-needle", __version__)
20
+ cached = os.path.join(cache, fetch._lib_name())
21
+ if os.path.exists(cached):
22
+ return cached
23
+ os.makedirs(cache, exist_ok=True)
24
+ return fetch.fetch_library(__version__, cache)
25
+
26
+
27
+ _lib_handle = None
28
+
29
+
30
+ def _lib():
31
+ global _lib_handle
32
+ if _lib_handle is None:
33
+ lib = ctypes.CDLL(_library_path())
34
+ lib.needle_init.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]
35
+ lib.needle_init.restype = ctypes.c_int
36
+ lib.needle_complete.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int]
37
+ lib.needle_complete.restype = ctypes.c_int
38
+ lib.needle_reset.argtypes = []
39
+ lib.needle_reset.restype = None
40
+ lib.needle_load.argtypes = [ctypes.c_char_p, ctypes.c_uint64]
41
+ lib.needle_load.restype = ctypes.c_int
42
+ _lib_handle = lib
43
+ return _lib_handle
44
+
45
+
46
+ class Needle:
47
+ def __init__(self, tools=None, system=None, weights=None, tool_index_path=None, buffer_size=65536):
48
+ self._functions = {}
49
+ if weights:
50
+ with open(weights, "rb") as handle:
51
+ blob = handle.read()
52
+ if _lib().needle_load(blob, len(blob)) != 0:
53
+ raise RuntimeError(f"failed to load weights from {weights}")
54
+ tools_json = tools if isinstance(tools, str) else json.dumps(self._resolve(tools))
55
+ if _lib().needle_init((system or "").encode("utf-8"), tools_json.encode("utf-8"),
56
+ tool_index_path.encode("utf-8") if tool_index_path else None) < 0:
57
+ raise RuntimeError("needle_init failed")
58
+ self._buffer = ctypes.create_string_buffer(buffer_size)
59
+
60
+ def _resolve(self, tools):
61
+ schemas = []
62
+ for entry in tools or []:
63
+ if _is_pydantic_model(entry):
64
+ schema = pydantic_schema(entry)
65
+ self._functions[schema["name"]] = entry
66
+ schemas.append(schema)
67
+ elif callable(entry):
68
+ schema = getattr(entry, "_needle_tool", None) or build_schema(entry)
69
+ self._functions[schema["name"]] = entry
70
+ schemas.append(schema)
71
+ elif isinstance(entry, dict):
72
+ schemas.append(entry)
73
+ return schemas
74
+
75
+ def complete(self, text, max_new_tokens=256):
76
+ _lib().needle_complete(text.encode("utf-8"), int(max_new_tokens),
77
+ self._buffer, len(self._buffer))
78
+ return json.loads(self._buffer.value.decode("utf-8"))
79
+
80
+ def run(self, query, max_steps=8, max_new_tokens=256):
81
+ response = self.complete(query, max_new_tokens)
82
+ for _ in range(max_steps):
83
+ calls = response.get("function_calls") or []
84
+ if response.get("type") != "call" or not calls:
85
+ return response
86
+ results = []
87
+ for call in calls:
88
+ fn = self._functions.get(call.get("name"))
89
+ if fn is None:
90
+ results.append({"error": "unknown tool: " + str(call.get("name"))})
91
+ continue
92
+ try:
93
+ results.append(fn(**(call.get("arguments") or {})))
94
+ except Exception as exc:
95
+ results.append({"error": str(exc)})
96
+ response = self.complete(json.dumps(results, default=_jsonable), max_new_tokens)
97
+ return response
98
+
99
+ def extract(self, text, schema, max_new_tokens=256):
100
+ return extract(text, schema, max_new_tokens=max_new_tokens)
101
+
102
+ def reset(self):
103
+ _lib().needle_reset()
104
+
105
+
106
+ def _jsonable(value):
107
+ if hasattr(value, "model_dump"):
108
+ return value.model_dump()
109
+ if hasattr(value, "dict") and _is_pydantic_model(type(value)):
110
+ return value.dict()
111
+ return str(value)
112
+
113
+
114
+ def extract(text, schema, system=None, max_new_tokens=256):
115
+ """One-shot structured extraction: declare `schema` as the only tool and return
116
+ the parsed object (a Pydantic instance if `schema` is a model, else a dict).
117
+ Re-initializes the shared engine with this single schema."""
118
+ agent = Needle(tools=[schema], system=system)
119
+ response = agent.complete(text, max_new_tokens)
120
+ calls = response.get("function_calls") or []
121
+ if not calls:
122
+ return None
123
+ arguments = calls[0].get("arguments") or {}
124
+ return schema(**arguments) if _is_pydantic_model(schema) else arguments
File without changes
needle/agent/fetch.py ADDED
@@ -0,0 +1,54 @@
1
+ import os
2
+ import platform
3
+ import sys
4
+ import zipfile
5
+
6
+ HF_REPO = "Cactus-Compute/needle2"
7
+
8
+
9
+ def _lib_name():
10
+ if sys.platform == "darwin":
11
+ return "libneedle.dylib"
12
+ if sys.platform == "win32":
13
+ return "libneedle.dll"
14
+ return "libneedle.so"
15
+
16
+
17
+ def _is_musl():
18
+ if sys.platform != "linux":
19
+ return False
20
+ libc, _ = platform.libc_ver()
21
+ if libc:
22
+ return False
23
+ try:
24
+ with open("/proc/self/maps", "rb") as maps:
25
+ return b"musl" in maps.read()
26
+ except OSError:
27
+ return True
28
+
29
+
30
+ def _platform_tag():
31
+ machine = platform.machine().lower()
32
+ if sys.platform == "darwin":
33
+ arch = "arm64" if machine in ("arm64", "aarch64") else "x86_64"
34
+ return "macosx_11_0_" + arch
35
+ if sys.platform == "win32":
36
+ return "win_arm64" if machine in ("arm64", "aarch64") else "win_amd64"
37
+ arch = "aarch64" if machine in ("aarch64", "arm64") else "x86_64"
38
+ family = "musllinux_1_2_" if _is_musl() else "manylinux2014_"
39
+ return family + arch
40
+
41
+
42
+ def fetch_library(version, dest_dir):
43
+ from huggingface_hub import hf_hub_download
44
+
45
+ tag = _platform_tag()
46
+ wheel = "cactus_needle-{}-py3-none-{}.whl".format(version, tag)
47
+ path = hf_hub_download(repo_id=HF_REPO, filename="python/" + wheel, repo_type="model")
48
+ lib = _lib_name()
49
+ with zipfile.ZipFile(path) as archive:
50
+ data = archive.read("needle/" + lib)
51
+ out = os.path.join(dest_dir, lib)
52
+ with open(out, "wb") as handle:
53
+ handle.write(data)
54
+ return out