langchain-bilinc 0.1.0__tar.gz

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,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ReARC Labs Inc.
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,118 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-bilinc
3
+ Version: 0.1.0
4
+ Summary: LangChain memory tools and retriever for Bilinc agent memory.
5
+ Project-URL: Homepage, https://bilinc.space
6
+ Project-URL: Documentation, https://bilinc.space/docs
7
+ Project-URL: Repository, https://github.com/ReARCLabs/bilinc-langchain
8
+ Project-URL: Issues, https://github.com/ReARCLabs/bilinc-langchain/issues
9
+ Author: ReARC Labs Inc.
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,bilinc,langchain,memory,retriever
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Libraries
16
+ Requires-Python: <4.0,>=3.11
17
+ Requires-Dist: bilinc<3,>=2.7.3
18
+ Requires-Dist: langchain-core<2.0.0,>=1.4.7
19
+ Description-Content-Type: text/markdown
20
+
21
+ # langchain-bilinc
22
+
23
+ LangChain integration for [Bilinc](https://bilinc.space), shared and versioned memory for AI agents.
24
+
25
+ - `BilincRemember`: a tool that saves a fact, decision or preference to Bilinc (`commit`).
26
+ - `BilincRecall`: a tool that searches Bilinc memory in plain language (`recall`).
27
+ - `BilincRetriever`: a retriever that returns recalled memories as LangChain `Document`s.
28
+
29
+ All three wrap the official [`bilinc`](https://pypi.org/project/bilinc/) Python SDK.
30
+
31
+ Source: <https://github.com/ReARCLabs/bilinc-langchain>
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install -U langchain-bilinc
37
+ ```
38
+
39
+ ## Credentials
40
+
41
+ Set `BILINC_API_KEY`, or pass `api_key=`. If neither is set, the SDK uses the key saved by `bilinc login`. Get a key at [bilinc.space/signup](https://bilinc.space/signup).
42
+
43
+ ```bash
44
+ export BILINC_API_KEY="..."
45
+ ```
46
+
47
+ ## Tools
48
+
49
+ ```python
50
+ from langchain_bilinc import BilincRecall, BilincRemember
51
+
52
+ remember = BilincRemember(key_prefix="support-agent")
53
+ remember.invoke({"key": "user.timezone", "value": "Europe/Istanbul"})
54
+ # {"saved": True, "key": "support-agent.user.timezone", "entry_version": "..."}
55
+
56
+ recall = BilincRecall(limit=5)
57
+ recall.invoke({"query": "what timezone is the user in?"})
58
+ # [{"key": "support-agent.user.timezone", "value": "Europe/Istanbul", "score": ..., ...}]
59
+ ```
60
+
61
+ Give both to an agent so it can save and look up memory across sessions:
62
+
63
+ ```python
64
+ from langchain.agents import create_agent
65
+ from langchain_bilinc import BilincRecall, BilincRemember
66
+
67
+ agent = create_agent(
68
+ model="anthropic:claude-sonnet-5-5",
69
+ tools=[BilincRecall(), BilincRemember(key_prefix="my-agent")],
70
+ system_prompt="Recall memory before acting on earlier decisions. Save only durable facts.",
71
+ )
72
+ ```
73
+
74
+ `BilincRemember` details:
75
+
76
+ - Writing to an existing key replaces its value; Bilinc keeps the earlier value in that memory's history.
77
+ - Without a `key`, the tool derives a stable key from the value, so saving the same value twice writes the same key.
78
+ - Options: `key_prefix`, `default_memory_type` (`semantic`), `default_importance` (`1.0`), `source` (`"langchain"`), `session_id`, `metadata`.
79
+ - `session_id` is trimmed, and a blank one is not sent. One longer than 256 characters (Bilinc's limit) is sent as its hash.
80
+
81
+ `BilincRecall` options: `limit` (`5`), `profile` (`fast`, `balanced`, `verified`, `deep`; higher profiles depend on your plan), `memory_types`.
82
+
83
+ ## Retriever
84
+
85
+ ```python
86
+ from langchain_bilinc import BilincRetriever
87
+
88
+ retriever = BilincRetriever(k=5, profile="balanced")
89
+ docs = retriever.invoke("what did we decide about the release?")
90
+ for doc in docs:
91
+ print(doc.metadata["key"], doc.page_content)
92
+ ```
93
+
94
+ `page_content` is the stored value; JSON values are serialized. `metadata` holds `key`, `memory_type`, `importance`, `score`, `source`, `entry_version` and `updated_at` when the service returns them.
95
+
96
+ Bilinc's limits are applied before the call:
97
+ - `k` (on the retriever or per call) is capped at 100.
98
+ - The query is cut at 4,096 characters.
99
+ - A `k` of 0 or less, or a blank query, returns no documents without a call (so no credit is used).
100
+
101
+ A failed recall raises the SDK's own error (`bilinc.BilincRateLimitError`, `bilinc.BilincAuthError`, ...), so `except bilinc.BilincError` catches it.
102
+
103
+ ## Errors and costs
104
+
105
+ Tool errors are raised as `ToolException` (set `handle_tool_error=True` to return them to the model). A failed save means nothing was saved. Saves and recalls use Bilinc credits; see [pricing](https://bilinc.space/pricing).
106
+
107
+ ## Development
108
+
109
+ ```bash
110
+ pip install -e . pytest pytest-asyncio "langchain-tests>=1.1.9,<2"
111
+ pytest
112
+ ```
113
+
114
+ The unit tests replace the SDK transport with a fake and never reach the network.
115
+
116
+ ## License
117
+
118
+ MIT for this package. The `bilinc` SDK it depends on has its own license (BUSL-1.1).
@@ -0,0 +1,98 @@
1
+ # langchain-bilinc
2
+
3
+ LangChain integration for [Bilinc](https://bilinc.space), shared and versioned memory for AI agents.
4
+
5
+ - `BilincRemember`: a tool that saves a fact, decision or preference to Bilinc (`commit`).
6
+ - `BilincRecall`: a tool that searches Bilinc memory in plain language (`recall`).
7
+ - `BilincRetriever`: a retriever that returns recalled memories as LangChain `Document`s.
8
+
9
+ All three wrap the official [`bilinc`](https://pypi.org/project/bilinc/) Python SDK.
10
+
11
+ Source: <https://github.com/ReARCLabs/bilinc-langchain>
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pip install -U langchain-bilinc
17
+ ```
18
+
19
+ ## Credentials
20
+
21
+ Set `BILINC_API_KEY`, or pass `api_key=`. If neither is set, the SDK uses the key saved by `bilinc login`. Get a key at [bilinc.space/signup](https://bilinc.space/signup).
22
+
23
+ ```bash
24
+ export BILINC_API_KEY="..."
25
+ ```
26
+
27
+ ## Tools
28
+
29
+ ```python
30
+ from langchain_bilinc import BilincRecall, BilincRemember
31
+
32
+ remember = BilincRemember(key_prefix="support-agent")
33
+ remember.invoke({"key": "user.timezone", "value": "Europe/Istanbul"})
34
+ # {"saved": True, "key": "support-agent.user.timezone", "entry_version": "..."}
35
+
36
+ recall = BilincRecall(limit=5)
37
+ recall.invoke({"query": "what timezone is the user in?"})
38
+ # [{"key": "support-agent.user.timezone", "value": "Europe/Istanbul", "score": ..., ...}]
39
+ ```
40
+
41
+ Give both to an agent so it can save and look up memory across sessions:
42
+
43
+ ```python
44
+ from langchain.agents import create_agent
45
+ from langchain_bilinc import BilincRecall, BilincRemember
46
+
47
+ agent = create_agent(
48
+ model="anthropic:claude-sonnet-5-5",
49
+ tools=[BilincRecall(), BilincRemember(key_prefix="my-agent")],
50
+ system_prompt="Recall memory before acting on earlier decisions. Save only durable facts.",
51
+ )
52
+ ```
53
+
54
+ `BilincRemember` details:
55
+
56
+ - Writing to an existing key replaces its value; Bilinc keeps the earlier value in that memory's history.
57
+ - Without a `key`, the tool derives a stable key from the value, so saving the same value twice writes the same key.
58
+ - Options: `key_prefix`, `default_memory_type` (`semantic`), `default_importance` (`1.0`), `source` (`"langchain"`), `session_id`, `metadata`.
59
+ - `session_id` is trimmed, and a blank one is not sent. One longer than 256 characters (Bilinc's limit) is sent as its hash.
60
+
61
+ `BilincRecall` options: `limit` (`5`), `profile` (`fast`, `balanced`, `verified`, `deep`; higher profiles depend on your plan), `memory_types`.
62
+
63
+ ## Retriever
64
+
65
+ ```python
66
+ from langchain_bilinc import BilincRetriever
67
+
68
+ retriever = BilincRetriever(k=5, profile="balanced")
69
+ docs = retriever.invoke("what did we decide about the release?")
70
+ for doc in docs:
71
+ print(doc.metadata["key"], doc.page_content)
72
+ ```
73
+
74
+ `page_content` is the stored value; JSON values are serialized. `metadata` holds `key`, `memory_type`, `importance`, `score`, `source`, `entry_version` and `updated_at` when the service returns them.
75
+
76
+ Bilinc's limits are applied before the call:
77
+ - `k` (on the retriever or per call) is capped at 100.
78
+ - The query is cut at 4,096 characters.
79
+ - A `k` of 0 or less, or a blank query, returns no documents without a call (so no credit is used).
80
+
81
+ A failed recall raises the SDK's own error (`bilinc.BilincRateLimitError`, `bilinc.BilincAuthError`, ...), so `except bilinc.BilincError` catches it.
82
+
83
+ ## Errors and costs
84
+
85
+ Tool errors are raised as `ToolException` (set `handle_tool_error=True` to return them to the model). A failed save means nothing was saved. Saves and recalls use Bilinc credits; see [pricing](https://bilinc.space/pricing).
86
+
87
+ ## Development
88
+
89
+ ```bash
90
+ pip install -e . pytest pytest-asyncio "langchain-tests>=1.1.9,<2"
91
+ pytest
92
+ ```
93
+
94
+ The unit tests replace the SDK transport with a fake and never reach the network.
95
+
96
+ ## License
97
+
98
+ MIT for this package. The `bilinc` SDK it depends on has its own license (BUSL-1.1).
@@ -0,0 +1,25 @@
1
+ """LangChain integration for Bilinc: shared, versioned memory for AI agents."""
2
+
3
+ from importlib import metadata
4
+
5
+ from langchain_bilinc.retrievers import BilincRetriever
6
+ from langchain_bilinc.tools import (
7
+ BilincRecall,
8
+ BilincRecallInput,
9
+ BilincRemember,
10
+ BilincRememberInput,
11
+ )
12
+
13
+ try:
14
+ __version__ = metadata.version(__package__)
15
+ except metadata.PackageNotFoundError: # pragma: no cover
16
+ __version__ = ""
17
+
18
+ __all__ = [
19
+ "BilincRecall",
20
+ "BilincRecallInput",
21
+ "BilincRemember",
22
+ "BilincRememberInput",
23
+ "BilincRetriever",
24
+ "__version__",
25
+ ]
@@ -0,0 +1,104 @@
1
+ """Client construction and result shaping shared by the Bilinc tools and retriever."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from typing import Any
8
+
9
+ from bilinc import CloudClient
10
+ from langchain_core.utils import secret_from_env
11
+ from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, SecretStr
12
+
13
+ # The Bilinc server rejects a longer sessionId: it validates session_id with
14
+ # max_length=256 (Bilinc Cloud, cloud/service.py:63). The SDK does not check it.
15
+ # Same constant and helpers as in llama-index-memory-bilinc.
16
+ MAX_SESSION_ID_LENGTH = 256
17
+
18
+
19
+ def _session_hash(session_id: str) -> str:
20
+ return "h" + hashlib.sha256(session_id.encode("utf-8")).hexdigest()[:24]
21
+
22
+
23
+ def _session_field(session_id: str | None) -> str | None:
24
+ """The session as sent to Bilinc: trimmed, None if blank, hashed if too long."""
25
+ if session_id is None:
26
+ return None
27
+ session_id = session_id.strip()
28
+ if not session_id:
29
+ return None
30
+ if len(session_id) <= MAX_SESSION_ID_LENGTH:
31
+ return session_id
32
+ return _session_hash(session_id)
33
+
34
+
35
+ class BilincClientMixin(BaseModel):
36
+ """Builds a :class:`bilinc.CloudClient` lazily.
37
+
38
+ The key comes from ``api_key``, else ``BILINC_API_KEY``, else the key saved by
39
+ ``bilinc login`` (the SDK's own lookup). Nothing is sent until the first call.
40
+ """
41
+
42
+ model_config = ConfigDict(arbitrary_types_allowed=True, populate_by_name=True)
43
+
44
+ bilinc_api_key: SecretStr | None = Field(
45
+ default_factory=secret_from_env("BILINC_API_KEY", default=None),
46
+ alias="api_key",
47
+ )
48
+ """Bilinc Cloud API key."""
49
+
50
+ base_url: str | None = None
51
+ """Override the Bilinc Cloud URL. Defaults to the SDK's own choice."""
52
+
53
+ client: CloudClient | None = Field(default=None, exclude=True)
54
+ """Optional pre-built client; when set, ``api_key`` and ``base_url`` are ignored."""
55
+
56
+ _client: CloudClient | None = PrivateAttr(default=None)
57
+
58
+ def _get_client(self) -> CloudClient:
59
+ if self.client is not None:
60
+ return self.client
61
+ if self._client is None:
62
+ key = self.bilinc_api_key.get_secret_value() if self.bilinc_api_key else None
63
+ self._client = CloudClient(api_key=key, base_url=self.base_url)
64
+ return self._client
65
+
66
+
67
+ def _pick(item: dict[str, Any], *names: str) -> Any:
68
+ for name in names:
69
+ if item.get(name) is not None:
70
+ return item[name]
71
+ return None
72
+
73
+
74
+ def recall_results(response: dict[str, Any]) -> list[dict[str, Any]]:
75
+ """Normalize a recall response into a list of plain result dicts."""
76
+
77
+ items = response.get("results")
78
+ if items is None:
79
+ items = response.get("memories") or []
80
+ out: list[dict[str, Any]] = []
81
+ for item in items:
82
+ if not isinstance(item, dict):
83
+ continue
84
+ out.append(
85
+ {
86
+ "key": item.get("key"),
87
+ "value": item.get("value"),
88
+ "memory_type": _pick(item, "memory_type", "memoryType"),
89
+ "importance": item.get("importance"),
90
+ "score": item.get("score"),
91
+ "source": item.get("source"),
92
+ "entry_version": _pick(item, "entry_version", "entryVersion"),
93
+ "updated_at": _pick(item, "updated_at", "updatedAt"),
94
+ }
95
+ )
96
+ return out
97
+
98
+
99
+ def value_to_text(value: Any) -> str:
100
+ """Render a stored memory value as text for an LLM or a Document."""
101
+
102
+ if isinstance(value, str):
103
+ return value
104
+ return json.dumps(value, ensure_ascii=False, sort_keys=True)
File without changes
@@ -0,0 +1,55 @@
1
+ """A LangChain retriever over Bilinc agent memory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from bilinc.client import MAX_QUERY_LENGTH, MAX_RECALL_LIMIT
8
+ from langchain_core.callbacks import CallbackManagerForRetrieverRun
9
+ from langchain_core.documents import Document
10
+ from langchain_core.retrievers import BaseRetriever
11
+
12
+ from langchain_bilinc._client import BilincClientMixin, recall_results, value_to_text
13
+
14
+
15
+ class BilincRetriever(BilincClientMixin, BaseRetriever):
16
+ """Retrieve Bilinc memories as LangChain ``Document`` objects.
17
+
18
+ Each memory becomes one document: ``page_content`` is the stored value (JSON
19
+ values are serialized), and ``metadata`` holds the key, memory type,
20
+ importance, score, source, entry version and update time.
21
+
22
+ Example:
23
+ .. code-block:: python
24
+
25
+ from langchain_bilinc import BilincRetriever
26
+
27
+ retriever = BilincRetriever(k=5)
28
+ docs = retriever.invoke("what did we decide about the release?")
29
+ """
30
+
31
+ k: int = 5
32
+ """Number of memories to return (at most 100; 0 or less returns nothing)."""
33
+
34
+ profile: Literal["fast", "balanced", "verified", "deep"] = "balanced"
35
+ memory_types: list[str] | None = None
36
+
37
+ def _get_relevant_documents(
38
+ self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: object
39
+ ) -> list[Document]:
40
+ k = int(kwargs.get("k", self.k)) # type: ignore[call-overload]
41
+ query = query.strip()[:MAX_QUERY_LENGTH]
42
+ if k <= 0 or not query:
43
+ return [] # nothing asked for: no call, no credit
44
+ # Bilinc errors (BilincRateLimitError, BilincAuthError, ...) propagate unchanged.
45
+ response = self._get_client().recall(
46
+ query,
47
+ profile=self.profile,
48
+ limit=min(k, MAX_RECALL_LIMIT),
49
+ memory_types=list(self.memory_types) if self.memory_types else None,
50
+ )
51
+ docs: list[Document] = []
52
+ for item in recall_results(response):
53
+ metadata = {name: v for name, v in item.items() if name != "value" and v is not None}
54
+ docs.append(Document(page_content=value_to_text(item["value"]), metadata=metadata))
55
+ return docs
@@ -0,0 +1,176 @@
1
+ """LangChain tools that write to and read from Bilinc agent memory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from typing import Any, Literal
7
+
8
+ from bilinc import BilincError
9
+ from langchain_core.callbacks import CallbackManagerForToolRun
10
+ from langchain_core.tools import BaseTool, ToolException
11
+ from pydantic import BaseModel, Field
12
+
13
+ from langchain_bilinc._client import (
14
+ BilincClientMixin,
15
+ _session_field,
16
+ recall_results,
17
+ value_to_text,
18
+ )
19
+
20
+ MemoryType = Literal["episodic", "procedural", "semantic", "working", "spatial"]
21
+ RecallProfile = Literal["fast", "balanced", "verified", "deep"]
22
+
23
+
24
+ class BilincRememberInput(BaseModel):
25
+ """Input for :class:`BilincRemember`."""
26
+
27
+ value: str | dict[str, Any] = Field(
28
+ description="What to remember: a short fact or decision, as text or a JSON object."
29
+ )
30
+ key: str | None = Field(
31
+ default=None,
32
+ description=(
33
+ "Optional stable, namespaced key such as 'user.preference.language'. "
34
+ "Writing to an existing key replaces its value; the old value stays in history."
35
+ ),
36
+ )
37
+ memory_type: MemoryType | None = Field(
38
+ default=None,
39
+ description="episodic (events), semantic (facts), procedural (how-to), working or spatial.",
40
+ )
41
+ importance: float | None = Field(
42
+ default=None, ge=0.0, le=1.0, description="How important this is, from 0.0 to 1.0."
43
+ )
44
+
45
+
46
+ class BilincRemember(BilincClientMixin, BaseTool):
47
+ """Commit a memory to Bilinc Cloud (``CloudClient.commit``).
48
+
49
+ Setup:
50
+ .. code-block:: bash
51
+
52
+ pip install -U langchain-bilinc
53
+ export BILINC_API_KEY="..."
54
+
55
+ Instantiate:
56
+ .. code-block:: python
57
+
58
+ from langchain_bilinc import BilincRemember
59
+
60
+ tool = BilincRemember(key_prefix="support-agent")
61
+
62
+ Invoke:
63
+ .. code-block:: python
64
+
65
+ tool.invoke({"key": "user.timezone", "value": "Europe/Istanbul"})
66
+ """
67
+
68
+ name: str = "bilinc_remember"
69
+ description: str = (
70
+ "Save a durable fact, decision or preference to long-term memory so it can be "
71
+ "recalled in later sessions. Only save what should still matter later."
72
+ )
73
+ args_schema: type[BaseModel] = BilincRememberInput
74
+
75
+ key_prefix: str | None = None
76
+ """Prefix added to every key, e.g. an agent or project name."""
77
+
78
+ default_memory_type: MemoryType = "semantic"
79
+ default_importance: float = 1.0
80
+ source: str | None = "langchain"
81
+ """The "saved by" label stored with each memory."""
82
+
83
+ session_id: str | None = None
84
+ """Session stored with each memory; over 256 characters (Bilinc's limit) it is hashed."""
85
+ metadata: dict[str, Any] | None = None
86
+ """Extra metadata stored with every memory this tool writes."""
87
+
88
+ def _full_key(self, key: str | None, value: Any) -> str:
89
+ if not key:
90
+ digest = hashlib.sha256(value_to_text(value).encode("utf-8")).hexdigest()[:16]
91
+ key = f"memory.{digest}"
92
+ return f"{self.key_prefix}.{key}" if self.key_prefix else key
93
+
94
+ def _run(
95
+ self,
96
+ value: str | dict[str, Any],
97
+ key: str | None = None,
98
+ memory_type: str | None = None,
99
+ importance: float | None = None,
100
+ run_manager: CallbackManagerForToolRun | None = None,
101
+ ) -> dict[str, Any]:
102
+ full_key = self._full_key(key, value)
103
+ try:
104
+ response = self._get_client().commit(
105
+ full_key,
106
+ value,
107
+ memory_type=memory_type or self.default_memory_type,
108
+ importance=self.default_importance if importance is None else importance,
109
+ metadata=dict(self.metadata or {}),
110
+ source=self.source,
111
+ session_id=_session_field(self.session_id),
112
+ )
113
+ except BilincError as exc:
114
+ raise ToolException(f"Memory was not saved: {exc}") from exc
115
+ return {
116
+ "saved": True,
117
+ "key": full_key,
118
+ "entry_version": response.get("entryVersion") or response.get("entry_version"),
119
+ }
120
+
121
+
122
+ class BilincRecallInput(BaseModel):
123
+ """Input for :class:`BilincRecall`."""
124
+
125
+ query: str = Field(description="What to look up in memory, in plain language.")
126
+ limit: int | None = Field(default=None, ge=1, le=100, description="How many memories.")
127
+
128
+
129
+ class BilincRecall(BilincClientMixin, BaseTool):
130
+ """Recall memories from Bilinc Cloud (``CloudClient.recall``).
131
+
132
+ Instantiate:
133
+ .. code-block:: python
134
+
135
+ from langchain_bilinc import BilincRecall
136
+
137
+ tool = BilincRecall(limit=5)
138
+
139
+ Invoke:
140
+ .. code-block:: python
141
+
142
+ tool.invoke({"query": "what timezone is the user in?"})
143
+ """
144
+
145
+ name: str = "bilinc_recall"
146
+ description: str = (
147
+ "Search long-term memory for earlier facts, decisions and preferences. "
148
+ "Call it before acting on something that may have been decided before."
149
+ )
150
+ args_schema: type[BaseModel] = BilincRecallInput
151
+
152
+ limit: int = 5
153
+ profile: RecallProfile = "balanced"
154
+ """Recall profile. Higher profiles depend on the Bilinc plan."""
155
+
156
+ memory_types: list[MemoryType] | None = None
157
+
158
+ def _run(
159
+ self,
160
+ query: str,
161
+ limit: int | None = None,
162
+ run_manager: CallbackManagerForToolRun | None = None,
163
+ ) -> list[dict[str, Any]]:
164
+ try:
165
+ response = self._get_client().recall(
166
+ query,
167
+ profile=self.profile,
168
+ limit=limit or self.limit,
169
+ memory_types=list(self.memory_types) if self.memory_types else None,
170
+ )
171
+ except BilincError as exc:
172
+ raise ToolException(f"Recall failed: {exc}") from exc
173
+ return [
174
+ {k: v for k, v in item.items() if v is not None and k != "entry_version"}
175
+ for item in recall_results(response)
176
+ ]
@@ -0,0 +1,54 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "langchain-bilinc"
7
+ version = "0.1.0"
8
+ description = "LangChain memory tools and retriever for Bilinc agent memory."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "ReARC Labs Inc." }]
13
+ requires-python = ">=3.11,<4.0"
14
+ dependencies = [
15
+ "langchain-core>=1.4.7,<2.0.0",
16
+ "bilinc>=2.7.3,<3",
17
+ ]
18
+ keywords = ["langchain", "bilinc", "memory", "agents", "retriever"]
19
+ classifiers = [
20
+ "Programming Language :: Python :: 3",
21
+ "Operating System :: OS Independent",
22
+ "Topic :: Software Development :: Libraries",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://bilinc.space"
27
+ Documentation = "https://bilinc.space/docs"
28
+ Repository = "https://github.com/ReARCLabs/bilinc-langchain"
29
+ Issues = "https://github.com/ReARCLabs/bilinc-langchain/issues"
30
+
31
+ [dependency-groups]
32
+ test = [
33
+ "pytest>=8.3",
34
+ "pytest-asyncio>=0.24",
35
+ "langchain-tests>=1.1.9,<2.0.0",
36
+ ]
37
+ lint = ["ruff>=0.13"]
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["langchain_bilinc"]
41
+
42
+ [tool.hatch.build.targets.sdist]
43
+ include = ["langchain_bilinc/", "tests/", "README.md", "LICENSE"]
44
+
45
+ [tool.ruff]
46
+ line-length = 100
47
+ target-version = "py311"
48
+
49
+ [tool.ruff.lint]
50
+ select = ["E", "F", "I", "UP", "B"]
51
+
52
+ [tool.pytest.ini_options]
53
+ asyncio_mode = "auto"
54
+ asyncio_default_fixture_loop_scope = "function"
File without changes
@@ -0,0 +1,21 @@
1
+ """Test setup: no network, no real key, and no saved Bilinc login is read."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import socket
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+
11
+ @pytest.fixture(autouse=True)
12
+ def _isolated(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
13
+ def guard(*args: object, **kwargs: object) -> None:
14
+ raise RuntimeError("network access is disabled in unit tests")
15
+
16
+ monkeypatch.setattr(socket.socket, "connect", guard)
17
+ monkeypatch.setattr(socket, "create_connection", guard)
18
+ for name in ("BILINC_API_KEY", "BILINC_BASE_URL", "XDG_CONFIG_HOME"):
19
+ monkeypatch.delenv(name, raising=False)
20
+ # Point the SDK at an empty config dir so a developer's `bilinc login` is never read.
21
+ monkeypatch.setenv("BILINC_CONFIG_DIR", str(tmp_path / "bilinc-config"))
@@ -0,0 +1,64 @@
1
+ """A recording fake for the Bilinc SDK transport (no network)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from bilinc import CloudClient
9
+ from bilinc.client import error_for_response
10
+
11
+
12
+ class FakeTransport:
13
+ def __init__(self, routes: dict[str, tuple[int, dict[str, Any]]]) -> None:
14
+ self.routes = routes
15
+ self.calls: list[dict[str, Any]] = []
16
+
17
+ def __call__(
18
+ self, method: str, url: str, *, headers: dict[str, str], body: bytes | None, timeout: float
19
+ ) -> dict[str, Any]:
20
+ path = url.split("://", 1)[1].split("/", 1)[1]
21
+ path = "/" + path.split("?", 1)[0]
22
+ self.calls.append(
23
+ {
24
+ "method": method,
25
+ "path": path,
26
+ "headers": headers,
27
+ "json": json.loads(body) if body else None,
28
+ }
29
+ )
30
+ status, payload = self.routes[path]
31
+ if status >= 400:
32
+ raise error_for_response(status, payload)
33
+ return payload
34
+
35
+
36
+ def make_client(transport: FakeTransport) -> CloudClient:
37
+ return CloudClient(api_key="test-key", transport=transport, read_retry_attempts=1)
38
+
39
+
40
+ RECALL_RESPONSE = {
41
+ "query": "release",
42
+ "results": [
43
+ {
44
+ "key": "project.release",
45
+ "value": {"decision": "ship 0.1.0 after review"},
46
+ "memory_type": "episodic",
47
+ "importance": 0.9,
48
+ "score": 0.42,
49
+ "entry_version": "v1_abc",
50
+ "source": "langchain",
51
+ "updated_at": 1794394635.8,
52
+ },
53
+ {
54
+ "key": "user.timezone",
55
+ "value": "Europe/Istanbul",
56
+ "memoryType": "semantic",
57
+ "importance": 1.0,
58
+ "score": 0.2,
59
+ "entryVersion": "v1_def",
60
+ },
61
+ ],
62
+ }
63
+
64
+ COMMIT_RESPONSE = {"key": "x", "entryVersion": "v1_new"}
File without changes
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ from langchain_bilinc import BilincRetriever
4
+ from tests.fakes import RECALL_RESPONSE, FakeTransport, make_client
5
+
6
+ RECALL = "/api/cloud/memory/recall"
7
+
8
+
9
+ def test_retriever_returns_documents() -> None:
10
+ fake = FakeTransport({RECALL: (200, RECALL_RESPONSE)})
11
+ retriever = BilincRetriever(client=make_client(fake), k=3, profile="fast")
12
+
13
+ docs = retriever.invoke("release")
14
+
15
+ assert fake.calls[0]["json"] == {"query": "release", "profile": "fast", "limit": 3}
16
+ assert docs[0].page_content == '{"decision": "ship 0.1.0 after review"}'
17
+ assert docs[0].metadata["key"] == "project.release"
18
+ assert docs[0].metadata["score"] == 0.42
19
+ assert docs[1].page_content == "Europe/Istanbul"
20
+ assert docs[1].metadata["entry_version"] == "v1_def"
21
+ assert "value" not in docs[1].metadata
22
+
23
+
24
+ def test_retriever_k_override_at_call_time() -> None:
25
+ fake = FakeTransport({RECALL: (200, {"results": []})})
26
+ retriever = BilincRetriever(client=make_client(fake))
27
+ assert retriever.invoke("x", k=9) == []
28
+ assert fake.calls[0]["json"]["limit"] == 9
29
+
30
+
31
+ async def test_retriever_async() -> None:
32
+ fake = FakeTransport({RECALL: (200, RECALL_RESPONSE)})
33
+ retriever = BilincRetriever(client=make_client(fake))
34
+ docs = await retriever.ainvoke("release")
35
+ assert len(docs) == 2
@@ -0,0 +1,65 @@
1
+ """Regression tests for the second code review round (2026-11-26, no network)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import logging
7
+
8
+ import bilinc.client
9
+ import pytest
10
+ from bilinc import BilincApiKeyRequired, BilincAuthError, BilincError, BilincRateLimitError
11
+
12
+ import langchain_bilinc.retrievers as retrievers_module
13
+ from langchain_bilinc import BilincRetriever
14
+ from tests.fakes import RECALL_RESPONSE, FakeTransport, make_client
15
+
16
+ RECALL = "/api/cloud/memory/recall"
17
+
18
+
19
+ # Finding 5: the SDK's own error types reach the caller -------------------------
20
+
21
+
22
+ @pytest.mark.parametrize(
23
+ "status, payload, error_type",
24
+ [
25
+ (429, {"error": "rate_limited", "message": "slow down"}, BilincRateLimitError),
26
+ (401, {"error": "invalid_api_key", "message": "bad key"}, BilincAuthError),
27
+ ],
28
+ )
29
+ def test_bilinc_errors_propagate_unchanged(status, payload, error_type, caplog) -> None:
30
+ fake = FakeTransport({RECALL: (status, payload)})
31
+ retriever = BilincRetriever(client=make_client(fake))
32
+ with caplog.at_level(logging.DEBUG):
33
+ with pytest.raises(error_type):
34
+ retriever.invoke("release")
35
+ # existing `except BilincError` code keeps working
36
+ with pytest.raises(BilincError):
37
+ retriever.invoke("release")
38
+ assert caplog.records == [] # raised, not also logged
39
+
40
+
41
+ def test_missing_key_raises_the_sdk_error() -> None:
42
+ with pytest.raises(BilincApiKeyRequired):
43
+ BilincRetriever().invoke("release")
44
+
45
+
46
+ # Finding 8: k <= 0 returns nothing and costs nothing ------------------------------
47
+
48
+
49
+ @pytest.mark.parametrize("k", [0, -1, -50])
50
+ def test_non_positive_k_makes_no_call(k: int) -> None:
51
+ fake = FakeTransport({RECALL: (200, RECALL_RESPONSE)})
52
+ assert BilincRetriever(client=make_client(fake), k=k).invoke("release") == []
53
+ assert BilincRetriever(client=make_client(fake)).invoke("release", k=k) == []
54
+ assert fake.calls == []
55
+
56
+
57
+ # Cleanup: the limits come from the SDK, not local copies --------------------------
58
+
59
+
60
+ def test_limits_are_the_sdk_constants() -> None:
61
+ assert retrievers_module.MAX_RECALL_LIMIT is bilinc.client.MAX_RECALL_LIMIT
62
+ assert retrievers_module.MAX_QUERY_LENGTH is bilinc.client.MAX_QUERY_LENGTH
63
+ source = inspect.getsource(retrievers_module)
64
+ assert "MAX_RECALL_LIMIT = " not in source and "MAX_QUERY_LENGTH = " not in source
65
+ assert "logger" not in source
@@ -0,0 +1,45 @@
1
+ """Regression tests for the fifth review round: long session IDs (no network)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import langchain_bilinc._client as client_module
6
+ from langchain_bilinc import BilincRemember
7
+ from tests.fakes import COMMIT_RESPONSE, FakeTransport, make_client
8
+
9
+ COMMIT = "/api/cloud/memory/commit"
10
+
11
+
12
+ def remember(session_id: str | None) -> dict:
13
+ fake = FakeTransport({COMMIT: (201, COMMIT_RESPONSE)})
14
+ BilincRemember(client=make_client(fake), session_id=session_id).invoke({"value": "x"})
15
+ return fake.calls[0]["json"]
16
+
17
+
18
+ def test_limit_matches_the_server() -> None:
19
+ assert client_module.MAX_SESSION_ID_LENGTH == 256
20
+
21
+
22
+ def test_long_session_id_is_hashed() -> None:
23
+ session = "s" * 300
24
+ body = remember(session)
25
+ assert body["sessionId"] == client_module._session_hash(session)
26
+ assert len(body["sessionId"]) <= 256
27
+
28
+
29
+ def test_session_id_at_the_limit_is_sent_as_is() -> None:
30
+ assert remember("t" * 256)["sessionId"] == "t" * 256
31
+
32
+
33
+ def test_short_and_blank_session_ids() -> None:
34
+ assert remember(" s1 ")["sessionId"] == "s1"
35
+ assert "sessionId" not in remember(" ")
36
+ assert "sessionId" not in remember(None)
37
+
38
+
39
+ def test_same_hash_as_the_llamaindex_package_would_use() -> None:
40
+ # Both packages use "h" + the first 24 hex characters of SHA-256.
41
+ import hashlib
42
+
43
+ session = "u" * 400
44
+ expected = "h" + hashlib.sha256(session.encode("utf-8")).hexdigest()[:24]
45
+ assert remember(session)["sessionId"] == expected
@@ -0,0 +1,27 @@
1
+ """Regression tests for the code review findings (no network)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from langchain_bilinc import BilincRetriever
6
+ from tests.fakes import RECALL_RESPONSE, FakeTransport, make_client
7
+
8
+ RECALL = "/api/cloud/memory/recall"
9
+
10
+
11
+ def test_k_is_capped_at_100() -> None:
12
+ fake = FakeTransport({RECALL: (200, RECALL_RESPONSE)})
13
+ BilincRetriever(client=make_client(fake), k=500).invoke("release")
14
+ BilincRetriever(client=make_client(fake)).invoke("release", k=1000)
15
+ assert [c["json"]["limit"] for c in fake.calls] == [100, 100]
16
+
17
+
18
+ def test_query_is_cut_at_4096_characters() -> None:
19
+ fake = FakeTransport({RECALL: (200, RECALL_RESPONSE)})
20
+ BilincRetriever(client=make_client(fake)).invoke("q" * 5000)
21
+ assert len(fake.calls[0]["json"]["query"]) == 4096
22
+
23
+
24
+ def test_blank_query_returns_nothing_without_a_call() -> None:
25
+ fake = FakeTransport({})
26
+ assert BilincRetriever(client=make_client(fake)).invoke(" ") == []
27
+ assert fake.calls == []
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ from langchain_tests.unit_tests import ToolsUnitTests
4
+
5
+ from langchain_bilinc import BilincRecall, BilincRemember
6
+
7
+ ENV = ({"BILINC_API_KEY": "env-key"}, {}, {"bilinc_api_key": "env-key"})
8
+
9
+
10
+ class TestBilincRememberStandard(ToolsUnitTests):
11
+ @property
12
+ def tool_constructor(self) -> type[BilincRemember]:
13
+ return BilincRemember
14
+
15
+ @property
16
+ def tool_invoke_params_example(self) -> dict:
17
+ return {"key": "user.timezone", "value": "Europe/Istanbul"}
18
+
19
+ @property
20
+ def init_from_env_params(self) -> tuple[dict, dict, dict]:
21
+ return ENV
22
+
23
+
24
+ class TestBilincRecallStandard(ToolsUnitTests):
25
+ @property
26
+ def tool_constructor(self) -> type[BilincRecall]:
27
+ return BilincRecall
28
+
29
+ @property
30
+ def tool_invoke_params_example(self) -> dict:
31
+ return {"query": "what timezone is the user in?"}
32
+
33
+ @property
34
+ def init_from_env_params(self) -> tuple[dict, dict, dict]:
35
+ return ENV
@@ -0,0 +1,98 @@
1
+ from __future__ import annotations
2
+
3
+ import pytest
4
+ from bilinc import BilincApiKeyRequired
5
+ from langchain_core.tools import ToolException
6
+
7
+ from langchain_bilinc import BilincRecall, BilincRemember
8
+ from tests.fakes import COMMIT_RESPONSE, RECALL_RESPONSE, FakeTransport, make_client
9
+
10
+ COMMIT = "/api/cloud/memory/commit"
11
+ RECALL = "/api/cloud/memory/recall"
12
+
13
+
14
+ def test_remember_commits_with_prefix_and_defaults() -> None:
15
+ fake = FakeTransport({COMMIT: (201, COMMIT_RESPONSE)})
16
+ tool = BilincRemember(client=make_client(fake), key_prefix="agent", session_id="s1")
17
+
18
+ out = tool.invoke({"key": "user.timezone", "value": "Europe/Istanbul"})
19
+
20
+ call = fake.calls[0]
21
+ assert call["method"] == "POST" and call["path"] == COMMIT
22
+ assert call["headers"]["Authorization"] == "Bearer test-key"
23
+ assert call["json"]["key"] == "agent.user.timezone"
24
+ assert call["json"]["value"] == "Europe/Istanbul"
25
+ assert call["json"]["memoryType"] == "semantic"
26
+ assert call["json"]["importance"] == 1.0
27
+ assert call["json"]["source"] == "langchain"
28
+ assert call["json"]["sessionId"] == "s1"
29
+ assert out == {"saved": True, "key": "agent.user.timezone", "entry_version": "v1_new"}
30
+
31
+
32
+ def test_remember_without_key_uses_stable_content_key() -> None:
33
+ fake = FakeTransport({COMMIT: (201, COMMIT_RESPONSE)})
34
+ tool = BilincRemember(client=make_client(fake))
35
+ first = tool.invoke({"value": {"fact": "a"}, "memory_type": "episodic", "importance": 0.5})
36
+ second = tool.invoke({"value": {"fact": "a"}})
37
+ assert first["key"] == second["key"]
38
+ assert first["key"].startswith("memory.")
39
+ assert fake.calls[0]["json"]["memoryType"] == "episodic"
40
+ assert fake.calls[0]["json"]["importance"] == 0.5
41
+
42
+
43
+ def test_remember_error_is_tool_exception() -> None:
44
+ error = {"error": "payment_required", "message": "Monthly credits used up"}
45
+ fake = FakeTransport({COMMIT: (402, error)})
46
+ tool = BilincRemember(client=make_client(fake))
47
+ with pytest.raises(ToolException, match="not saved.*Monthly credits used up"):
48
+ tool.invoke({"value": "x"})
49
+
50
+
51
+ def test_recall_returns_normalized_results() -> None:
52
+ fake = FakeTransport({RECALL: (200, RECALL_RESPONSE)})
53
+ tool = BilincRecall(client=make_client(fake), limit=7, memory_types=["semantic"])
54
+
55
+ out = tool.invoke({"query": "release"})
56
+
57
+ body = fake.calls[0]["json"]
58
+ assert body == {
59
+ "query": "release",
60
+ "profile": "balanced",
61
+ "limit": 7,
62
+ "memoryTypes": ["semantic"],
63
+ }
64
+ assert out[0]["key"] == "project.release"
65
+ assert out[0]["memory_type"] == "episodic"
66
+ assert out[1]["memory_type"] == "semantic"
67
+ assert "entry_version" not in out[0]
68
+
69
+
70
+ async def test_recall_async_uses_executor() -> None:
71
+ fake = FakeTransport({RECALL: (200, RECALL_RESPONSE)})
72
+ tool = BilincRecall(client=make_client(fake))
73
+ out = await tool.ainvoke({"query": "release", "limit": 2})
74
+ assert fake.calls[0]["json"]["limit"] == 2
75
+ assert len(out) == 2
76
+
77
+
78
+ def test_recall_error_is_tool_exception() -> None:
79
+ error = {"error": "capability_not_entitled", "message": "profile not in plan"}
80
+ fake = FakeTransport({RECALL: (403, error)})
81
+ tool = BilincRecall(client=make_client(fake), profile="deep")
82
+ with pytest.raises(ToolException, match="Recall failed"):
83
+ tool.invoke({"query": "x"})
84
+
85
+
86
+ def test_api_key_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
87
+ monkeypatch.setenv("BILINC_API_KEY", "env-key")
88
+ tool = BilincRecall()
89
+ assert tool.bilinc_api_key is not None
90
+ assert tool.bilinc_api_key.get_secret_value() == "env-key"
91
+ assert "env-key" not in repr(tool)
92
+ assert tool._get_client().api_key == "env-key"
93
+
94
+
95
+ def test_missing_key_fails_only_on_first_call() -> None:
96
+ tool = BilincRecall() # constructing without a key is fine
97
+ with pytest.raises(BilincApiKeyRequired):
98
+ tool._get_client()