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.
fix needle instances clobbering each other (#54)
Avionic Harshit1b5a7c202ec3
diff --git a/needle/__init__.py b/needle/__init__.pyindex 48f55fe..950f1e5 100644--- a/needle/__init__.py+++ b/needle/__init__.py@@ -25,6 +25,8 @@ def _library_path():_lib_handle = None+_active = None+_active_weights = Nonedef _lib():@@ -46,16 +48,28 @@ def _lib():class Needle:def __init__(self, tools=None, system=None, weights=None, tool_index_path=None, buffer_size=65536):self._functions = {}- if weights:- with open(weights, "rb") as handle:+ self._weights = weights+ 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")+ self._tool_index_path = tool_index_path.encode("utf-8") if tool_index_path else None+ self._buffer = ctypes.create_string_buffer(buffer_size)+ self._bind()++ def _bind(self):+ global _active, _active_weights+ if _active is self:+ return+ if self._weights and _active_weights != self._weights:+ with open(self._weights, "rb") as handle:blob = handle.read()if _lib().needle_load(blob, len(blob)) != 0:- raise RuntimeError(f"failed to load weights from {weights}")- tools_json = tools if isinstance(tools, str) else json.dumps(self._resolve(tools))- if _lib().needle_init((system or "").encode("utf-8"), tools_json.encode("utf-8"),- tool_index_path.encode("utf-8") if tool_index_path else None) < 0:+ raise RuntimeError(f"failed to load weights from {self._weights}")+ _active_weights = self._weights+ if _lib().needle_init(self._system, self._tools_json, self._tool_index_path) < 0:+ _active = Noneraise RuntimeError("needle_init failed")- self._buffer = ctypes.create_string_buffer(buffer_size)+ _active = selfdef _resolve(self, tools):schemas = []@@ -73,6 +87,7 @@ class Needle:return schemasdef complete(self, text, max_new_tokens=256):+ self._bind()_lib().needle_complete(text.encode("utf-8"), int(max_new_tokens),self._buffer, len(self._buffer))return json.loads(self._buffer.value.decode("utf-8"))@@ -103,6 +118,7 @@ class Needle:return extract(text, schema, max_new_tokens=max_new_tokens)def reset(self):+ self._bind()_lib().needle_reset()diff --git a/tests/test_inference.py b/tests/test_inference.pyindex 6910e74..da4db93 100644--- a/tests/test_inference.py+++ b/tests/test_inference.py@@ -42,3 +42,49 @@ def test_run_agentic_loop():response = agent.run("what's the weather in Paris?")assert isinstance(response, dict)assert "type" in response+++def test_two_agents():+ from needle import Needle, tool++ @tool+ def set_thermostat(temperature: int):+ "Set the thermostat temperature."+ return {"temperature": temperature}++ @tool+ def get_weather(city: str):+ "Get the weather for a city."+ return {"temp_c": 20}++ thermostat = Needle(tools=[set_thermostat])+ weather = Needle(tools=[get_weather])++ response = thermostat.complete("set it to 21 degrees")+ assert response["type"] == "call"+ assert response["function_calls"][0]["name"] == "set_thermostat"++ response = weather.complete("what's the weather in Paris?")+ assert response["type"] == "call"+ assert response["function_calls"][0]["name"] == "get_weather"+++def test_extract_keeps_agent_tools():+ import pydantic+ from needle import Needle, extract, tool++ @tool+ def set_thermostat(temperature: int):+ "Set the thermostat temperature."+ return {"temperature": temperature}++ class Contact(pydantic.BaseModel):+ name: str+ email: str++ agent = Needle(tools=[set_thermostat])+ extract("John Doe can be reached at [email protected]", Contact)++ response = agent.complete("set it to 21 degrees")+ assert response["type"] == "call"+ assert response["function_calls"][0]["name"] == "set_thermostat"