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.
Feat/telemetry (#96)
rshemetb1554b49178b
diff --git a/README.md b/README.mdindex f10209b..c3c7f45 100644--- a/README.md+++ b/README.md@@ -144,6 +144,10 @@ agent = needle.Needle(weights="my_needle.cact", tools=[...])agent.run("...")```+## Telemetry++Cactus Compute collects strictly anonymous usage telemetry (function name, package version, OS — never your prompts, outputs, or data); opt out with `NEEDLE_TELEMETRY=0` or `DO_NOT_TRACK=1`.+## CitationNeedle 2 is built by the Cactus Compute team. If you use it in your work, please cite:diff --git a/needle/__init__.py b/needle/__init__.pyindex a6f5399..07cb146 100644--- a/needle/__init__.py+++ b/needle/__init__.py@@ -7,6 +7,7 @@ import sysimport warningsfrom .agent.tools import Field, build_schema, pydantic_schema, tool, _is_pydantic_model+from ._telemetry import track as _track__version__ = "2.0.8"__all__ = ["Needle", "tool", "Field", "extract", "__version__"]@@ -63,6 +64,10 @@ class Needle:self._system = (system or "").encode("utf-8")tools_json = tools if isinstance(tools, str) else json.dumps(self._resolve(tools))self._tools_json = tools_json.encode("utf-8")+ try:+ self._n_tools = len(json.loads(tools_json))+ except (json.JSONDecodeError, TypeError):+ self._n_tools = Noneself._tool_index_path = tool_index_path.encode("utf-8") if tool_index_path else Noneself._buffer = ctypes.create_string_buffer(buffer_size)self._bind()@@ -108,7 +113,14 @@ class Needle:schemas.append(entry)return schemas+ def _track_props(self):+ return {"n_tools": self._n_tools, "tuned": bool(self._weights)}+def complete(self, text: str, max_new_tokens: int = 256) -> dict:+ _track("complete", self._track_props())+ return self._complete(text, max_new_tokens)++ def _complete(self, text: str, max_new_tokens: int = 256) -> dict:self._bind()rc = _lib().needle_complete(text.encode("utf-8"), int(max_new_tokens),self._buffer, len(self._buffer))@@ -125,7 +137,8 @@ class Needle:return responsedef run(self, query: str, max_steps: int = 8, max_new_tokens: int = 256) -> dict:- response = self.complete(query, max_new_tokens)+ _track("run", self._track_props())+ response = self._complete(query, max_new_tokens)executed = []for _ in range(max_steps):calls = response.get("function_calls") or []@@ -142,7 +155,7 @@ class Needle:except Exception as exc:results.append({"error": str(exc)})executed.extend(results)- response = self.complete(json.dumps(results, default=_jsonable), max_new_tokens)+ response = self._complete(json.dumps(results, default=_jsonable), max_new_tokens)response["results"] = executedreturn response@@ -169,8 +182,9 @@ def extract(text: str, schema: type | dict, system: str | None = None,the parsed object (a Pydantic instance if `schema` is a model, else a dict).Re-initializes the shared engine with this single schema. Defaults to whateverweights are already loaded, since the engine cannot unload them."""+ _track("extract", {"n_tools": 1, "tuned": bool(weights or _active_weights)})agent = Needle(tools=[schema], system=system, weights=weights or _active_weights)- response = agent.complete(text, max_new_tokens)+ response = agent._complete(text, max_new_tokens)calls = response.get("function_calls") or []if not calls:return Nonediff --git a/needle/_telemetry.py b/needle/_telemetry.pynew file mode 100644index 0000000..449e0fe--- /dev/null+++ b/needle/_telemetry.py@@ -0,0 +1,84 @@+from __future__ import annotations++import json+import os+import platform+import sys+import threading+import urllib.request+import uuid+from pathlib import Path++# Anonymous usage counts only (event name, versions, OS/arch, random install+# id) - never prompts, outputs, or paths; disclosed in the README and by the+# first-run notice. Sends run fire-and-forget on a daemon thread and must+# never raise into caller code.++ENDPOINT = os.environ.get(+ "NEEDLE_TELEMETRY_URL",+ "https://vlqqczxwyaodtcdmdmlw.supabase.co/functions/v1/telemetry",+)++_NOTICE = ("cactus-needle collects anonymous usage counts (function name, "+ "version, OS) to guide development; no prompts or outputs. "+ "Disable with NEEDLE_TELEMETRY=0.")++_lock = threading.Lock()+_anon_id: str | None = None+++def _enabled() -> bool:+ if os.environ.get("NEEDLE_TELEMETRY", "1") == "0":+ return False+ if os.environ.get("DO_NOT_TRACK"):+ return False+ if os.environ.get("CI"):+ return False+ return True+++def _get_anon_id() -> str:+ global _anon_id+ with _lock:+ if _anon_id:+ return _anon_id+ path = Path.home() / ".cactus_needle" / "telemetry_id"+ try:+ if path.exists():+ _anon_id = path.read_text().strip() or "ephemeral"+ else:+ path.parent.mkdir(parents=True, exist_ok=True)+ _anon_id = uuid.uuid4().hex+ path.write_text(_anon_id)+ print(_NOTICE, file=sys.stderr)+ except OSError:+ _anon_id = "ephemeral"+ return _anon_id+++def _send(event: str, props: dict | None) -> None:+ try:+ from . import __version__+ from .agent.fetch import ENGINE_VERSION+ payload = json.dumps({+ "event": event,+ "anon_id": _get_anon_id(),+ "version": __version__,+ "engine": ENGINE_VERSION,+ "os": platform.system(),+ "arch": platform.machine(),+ "python": platform.python_version(),+ "props": props or {},+ }).encode("utf-8")+ req = urllib.request.Request(+ ENDPOINT, data=payload,+ headers={"Content-Type": "application/json"})+ urllib.request.urlopen(req, timeout=3)+ except Exception:+ pass+++def track(event: str, props: dict | None = None) -> None:+ if not _enabled():+ return+ threading.Thread(target=_send, args=(event, props), daemon=True).start()diff --git a/needle/cli.py b/needle/cli.pyindex c733b29..a606c19 100644--- a/needle/cli.py+++ b/needle/cli.py@@ -190,6 +190,9 @@ def main():print(HELP)sys.exit(0)+ from ._telemetry import track+ track("cli:" + args.command)+if args.command == "run":from .model.run import main as run_mainrun_main(args)