crewai-hydradb 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,6 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ .pytest_cache/
4
+ build/
5
+ dist/
6
+ .venv/
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2025 HydraDB Contributors
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.5
2
+ Name: crewai-hydradb
3
+ Version: 0.1.0
4
+ Summary: HydraDB external-memory storage for CrewAI agents.
5
+ Project-URL: Homepage, https://hydradb.com
6
+ Project-URL: Documentation, https://docs.hydradb.com/
7
+ Project-URL: Repository, https://github.com/hydra-db/hydradb-crewai
8
+ Author-email: HydraDB <support@hydradb.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: agents,crewai,hydradb,memory
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: requests>=2.28
19
+ Provides-Extra: crewai
20
+ Requires-Dist: crewai<1.11,>=1.0; extra == 'crewai'
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest>=7; extra == 'test'
23
+ Requires-Dist: responses>=0.24; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # crewai-hydradb
27
+
28
+ HydraDB as external memory for [CrewAI](https://crewai.com) agents. Your crews
29
+ recall relevant history on each task and persist their outputs into
30
+ [HydraDB](https://hydradb.com), so memory survives across runs.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ pip install crewai-hydradb # once published; for local dev: pip install -e .
36
+ ```
37
+
38
+ ## Prerequisites
39
+
40
+ - Python >= 3.10
41
+ - A HydraDB account: API key + tenant ID ([hydradb.com](https://hydradb.com))
42
+ - `crewai >= 1.0, < 1.11`
43
+
44
+ ## CrewAI version compatibility
45
+
46
+ This integration implements CrewAI's `Storage` interface
47
+ (`crewai.memory.storage.interface.Storage`) wired via `ExternalMemory`, which
48
+ exists in CrewAI **1.0-1.10** (verified present in 1.5, removed in 1.11).
49
+ CrewAI **1.11+** restructured memory around a new embedding-based
50
+ `StorageBackend` protocol that expects the backend to store and search raw
51
+ embedding vectors - a poor fit for HydraDB's text-query recall. On 1.11+, use
52
+ HydraDB over MCP instead (`hydra-db/hydradb-mcp`), which exposes HydraDB's own
53
+ retrieval without a vector-store contract.
54
+
55
+ ## Quick start
56
+
57
+ ```python
58
+ from crewai import Crew
59
+ from crewai.memory.external.external_memory import ExternalMemory
60
+ from hydradb_crewai import HydraDBClient, HydraDBStorage
61
+
62
+ client = HydraDBClient(api_key="sk_live_...", tenant_id="your-tenant")
63
+
64
+ crew = Crew(
65
+ agents=[...],
66
+ tasks=[...],
67
+ external_memory=ExternalMemory(storage=HydraDBStorage(client)),
68
+ )
69
+ crew.kickoff()
70
+ ```
71
+
72
+ ## Notes
73
+
74
+ - **Public API only.** `save` writes via the public knowledge path
75
+ (`app_knowledge` → `/context/ingest`); `search` uses `POST /query`. The
76
+ memory-family write route is not publicly exposed, so outputs are stored as
77
+ knowledge (default `kind="knowledge"`).
78
+
79
+ ## How it works
80
+
81
+ CrewAI's `ExternalMemory` delegates to a `Storage` implementation:
82
+
83
+ | CrewAI call | HydraDB |
84
+ |---|---|
85
+ | `save(value, metadata)` - after a task completes | ingest as HydraDB knowledge (`app_knowledge`) |
86
+ | `search(query, limit, score_threshold)` - before a task | hybrid recall from HydraDB |
87
+
88
+ This mirrors the pattern used by Mem0, Honcho, and Hindsight.
89
+
90
+ ## Test
91
+
92
+ ```bash
93
+ pip install -e ".[test]"
94
+ pytest
95
+ ```
96
+
97
+ ## License
98
+
99
+ Apache-2.0 - Copyright (c) 2026 HydraDB
@@ -0,0 +1,74 @@
1
+ # crewai-hydradb
2
+
3
+ HydraDB as external memory for [CrewAI](https://crewai.com) agents. Your crews
4
+ recall relevant history on each task and persist their outputs into
5
+ [HydraDB](https://hydradb.com), so memory survives across runs.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install crewai-hydradb # once published; for local dev: pip install -e .
11
+ ```
12
+
13
+ ## Prerequisites
14
+
15
+ - Python >= 3.10
16
+ - A HydraDB account: API key + tenant ID ([hydradb.com](https://hydradb.com))
17
+ - `crewai >= 1.0, < 1.11`
18
+
19
+ ## CrewAI version compatibility
20
+
21
+ This integration implements CrewAI's `Storage` interface
22
+ (`crewai.memory.storage.interface.Storage`) wired via `ExternalMemory`, which
23
+ exists in CrewAI **1.0-1.10** (verified present in 1.5, removed in 1.11).
24
+ CrewAI **1.11+** restructured memory around a new embedding-based
25
+ `StorageBackend` protocol that expects the backend to store and search raw
26
+ embedding vectors - a poor fit for HydraDB's text-query recall. On 1.11+, use
27
+ HydraDB over MCP instead (`hydra-db/hydradb-mcp`), which exposes HydraDB's own
28
+ retrieval without a vector-store contract.
29
+
30
+ ## Quick start
31
+
32
+ ```python
33
+ from crewai import Crew
34
+ from crewai.memory.external.external_memory import ExternalMemory
35
+ from hydradb_crewai import HydraDBClient, HydraDBStorage
36
+
37
+ client = HydraDBClient(api_key="sk_live_...", tenant_id="your-tenant")
38
+
39
+ crew = Crew(
40
+ agents=[...],
41
+ tasks=[...],
42
+ external_memory=ExternalMemory(storage=HydraDBStorage(client)),
43
+ )
44
+ crew.kickoff()
45
+ ```
46
+
47
+ ## Notes
48
+
49
+ - **Public API only.** `save` writes via the public knowledge path
50
+ (`app_knowledge` → `/context/ingest`); `search` uses `POST /query`. The
51
+ memory-family write route is not publicly exposed, so outputs are stored as
52
+ knowledge (default `kind="knowledge"`).
53
+
54
+ ## How it works
55
+
56
+ CrewAI's `ExternalMemory` delegates to a `Storage` implementation:
57
+
58
+ | CrewAI call | HydraDB |
59
+ |---|---|
60
+ | `save(value, metadata)` - after a task completes | ingest as HydraDB knowledge (`app_knowledge`) |
61
+ | `search(query, limit, score_threshold)` - before a task | hybrid recall from HydraDB |
62
+
63
+ This mirrors the pattern used by Mem0, Honcho, and Hindsight.
64
+
65
+ ## Test
66
+
67
+ ```bash
68
+ pip install -e ".[test]"
69
+ pytest
70
+ ```
71
+
72
+ ## License
73
+
74
+ Apache-2.0 - Copyright (c) 2026 HydraDB
@@ -0,0 +1,37 @@
1
+ """Wire HydraDB as a CrewAI crew's external memory.
2
+
3
+ Run: set HYDRADB_API_KEY and HYDRADB_DATABASE, then `python examples/basic.py`.
4
+ """
5
+
6
+ import os
7
+
8
+ from crewai import Agent, Crew, Task
9
+ from crewai.memory.external.external_memory import ExternalMemory
10
+
11
+ from hydradb_crewai import HydraDBClient, HydraDBStorage
12
+
13
+ client = HydraDBClient(
14
+ api_key=os.environ["HYDRADB_API_KEY"],
15
+ tenant_id=os.environ["HYDRADB_DATABASE"],
16
+ )
17
+
18
+ researcher = Agent(
19
+ role="Researcher",
20
+ goal="Answer using durable project memory",
21
+ backstory="Remembers decisions across runs via HydraDB.",
22
+ )
23
+
24
+ task = Task(
25
+ description="Summarise our deployment policy.",
26
+ expected_output="A one-line policy summary.",
27
+ agent=researcher,
28
+ )
29
+
30
+ crew = Crew(
31
+ agents=[researcher],
32
+ tasks=[task],
33
+ external_memory=ExternalMemory(storage=HydraDBStorage(client)),
34
+ )
35
+
36
+ if __name__ == "__main__":
37
+ print(crew.kickoff())
@@ -0,0 +1,8 @@
1
+ """CrewAI integration for HydraDB - external memory storage."""
2
+
3
+ from .client import HydraChunk, HydraDBClient, HydraDBError
4
+ from .storage import HydraDBStorage
5
+
6
+ __all__ = ["HydraDBClient", "HydraChunk", "HydraDBError", "HydraDBStorage"]
7
+
8
+ __version__ = "0.1.0"
@@ -0,0 +1,231 @@
1
+ """Minimal HydraDB HTTP client - public API only.
2
+
3
+ Wraps the three public endpoints these integrations need:
4
+
5
+ * ``POST /query`` - hybrid recall over memory or knowledge (JSON body)
6
+ * ``POST /context/ingest`` - write knowledge (multipart ``app_knowledge``)
7
+ * ``DELETE /context`` - remove context by id (JSON body)
8
+
9
+ Ingestion uses the public knowledge path (``app_knowledge``); the memory-family
10
+ write route is not exposed on the public API, so text/conversations are stored
11
+ as knowledge. Auth is ``Authorization: Bearer <api_key>``. Responses are the
12
+ standard ``{"success", "data", "error", "meta"}`` envelope; recall results live
13
+ in ``data.chunks``. Chunks are normalised so callers do not depend on the wire
14
+ shape.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import uuid
21
+ from dataclasses import dataclass, field
22
+ from typing import Any, Iterable
23
+
24
+ import requests
25
+
26
+ DEFAULT_BASE_URL = "https://api.hydradb.com"
27
+
28
+
29
+ class HydraDBError(RuntimeError):
30
+ """Raised when the HydraDB API returns an error envelope or bad status."""
31
+
32
+
33
+ @dataclass
34
+ class HydraChunk:
35
+ """A single recalled chunk, normalised across memory/knowledge results."""
36
+
37
+ text: str
38
+ score: float | None = None
39
+ source_title: str = ""
40
+ id: str = ""
41
+ metadata: dict[str, Any] = field(default_factory=dict)
42
+
43
+
44
+ class HydraDBClient:
45
+ """Thin, dependency-light client for HydraDB recall and ingestion."""
46
+
47
+ def __init__(
48
+ self,
49
+ api_key: str,
50
+ tenant_id: str,
51
+ sub_tenant_id: str = "",
52
+ base_url: str = DEFAULT_BASE_URL,
53
+ timeout: float = 15.0,
54
+ session: requests.Session | None = None,
55
+ ) -> None:
56
+ if not api_key:
57
+ raise ValueError("api_key is required")
58
+ if not tenant_id:
59
+ raise ValueError("tenant_id is required")
60
+ self.api_key = api_key
61
+ self.tenant_id = tenant_id
62
+ self.sub_tenant_id = sub_tenant_id
63
+ self.base_url = base_url.rstrip("/")
64
+ self.timeout = timeout
65
+ self._session = session or requests.Session()
66
+
67
+ @property
68
+ def _auth_headers(self) -> dict[str, str]:
69
+ return {"Authorization": f"Bearer {self.api_key}"}
70
+
71
+ def _unwrap(self, resp: requests.Response) -> dict[str, Any]:
72
+ try:
73
+ body = resp.json()
74
+ except ValueError:
75
+ raise HydraDBError(f"HTTP {resp.status_code}: {resp.text[:200]}")
76
+ if not body.get("success", False):
77
+ err = body.get("error") or {}
78
+ raise HydraDBError(
79
+ f"{err.get('code', 'ERROR')}: {err.get('message', resp.text[:200])}"
80
+ )
81
+ return body.get("data") or {}
82
+
83
+ def query(
84
+ self,
85
+ query: str,
86
+ kind: str = "memory",
87
+ mode: str = "fast",
88
+ max_results: int = 6,
89
+ alpha: float = 0.8,
90
+ recency_bias: float = 0.0,
91
+ graph_context: bool = True,
92
+ ) -> list[HydraChunk]:
93
+ """Hybrid recall. ``kind`` is ``"memory"`` or ``"knowledge"``."""
94
+ payload = {
95
+ "tenant_id": self.tenant_id,
96
+ "sub_tenant_id": self.sub_tenant_id,
97
+ "query": query,
98
+ "kind": kind,
99
+ "mode": mode,
100
+ "max_results": max_results,
101
+ "alpha": alpha,
102
+ "recency_bias": recency_bias,
103
+ "graph_context": graph_context,
104
+ }
105
+ resp = self._session.post(
106
+ f"{self.base_url}/query",
107
+ headers={**self._auth_headers, "Content-Type": "application/json"},
108
+ json=payload,
109
+ timeout=self.timeout,
110
+ )
111
+ data = self._unwrap(resp)
112
+ return [_to_chunk(c) for c in (data.get("chunks") or [])]
113
+
114
+ def add_knowledge(self, items: Iterable[dict[str, Any]]) -> dict[str, Any]:
115
+ """Ingest ``app_knowledge`` items via the public ``/context/ingest``.
116
+
117
+ Each item is ``{"id", "title", "content": {"text": ...}, "metadata",
118
+ "infer"}``. Ingestion is asynchronous: a success here means the sources
119
+ were accepted/queued, not yet indexed.
120
+ """
121
+ fields = {
122
+ "tenant_id": (None, self.tenant_id),
123
+ "sub_tenant_id": (None, self.sub_tenant_id),
124
+ "kind": (None, "knowledge"),
125
+ "app_knowledge": (None, json.dumps(list(items))),
126
+ }
127
+ resp = self._session.post(
128
+ f"{self.base_url}/context/ingest",
129
+ headers=self._auth_headers,
130
+ files=fields,
131
+ timeout=self.timeout,
132
+ )
133
+ return self._unwrap(resp)
134
+
135
+ def add_text(
136
+ self,
137
+ text: str,
138
+ infer: bool = True,
139
+ title: str | None = None,
140
+ metadata: dict[str, Any] | None = None,
141
+ source_id: str | None = None,
142
+ ) -> dict[str, Any]:
143
+ """Store a single note as knowledge. Returns the ingest ack."""
144
+ item = {
145
+ "id": source_id or f"note-{uuid.uuid4().hex}",
146
+ "title": title or "note",
147
+ "content": {"text": text},
148
+ "metadata": metadata or {},
149
+ "infer": infer,
150
+ }
151
+ return self.add_knowledge([item])
152
+
153
+ def add_conversation(
154
+ self, user: str, assistant: str, infer: bool = True
155
+ ) -> dict[str, Any]:
156
+ """Store a user/assistant turn as knowledge."""
157
+ return self.add_text(
158
+ f"User: {user}\nAssistant: {assistant}", infer=infer, title="conversation"
159
+ )
160
+
161
+ def delete(self, ids: list[str], kind: str = "knowledge") -> dict[str, Any]:
162
+ ids = [i for i in (ids or []) if i]
163
+ if not ids:
164
+ return {"deleted_count": 0, "results": []}
165
+ resp = self._session.delete(
166
+ f"{self.base_url}/context",
167
+ headers={**self._auth_headers, "Content-Type": "application/json"},
168
+ json={
169
+ "tenant_id": self.tenant_id,
170
+ "sub_tenant_id": self.sub_tenant_id,
171
+ "ids": ids,
172
+ "kind": kind,
173
+ },
174
+ timeout=self.timeout,
175
+ )
176
+ return self._unwrap(resp)
177
+
178
+
179
+ def _to_chunk(raw: dict[str, Any]) -> HydraChunk:
180
+ """Normalise a wire chunk into :class:`HydraChunk`.
181
+
182
+ ``chunk_content`` is often a stored envelope whose prose lives at
183
+ ``content.text``; recall must yield the prose, not the JSON scaffolding
184
+ (mirrors the plugin's normalizeRetrievalResponse). Content that merely looks
185
+ JSON-ish but does not parse is passed through untouched.
186
+ """
187
+ raw_text = raw.get("chunk_content")
188
+ if raw_text is None:
189
+ raw_text = raw.get("text") or raw.get("content") or ""
190
+ return HydraChunk(
191
+ text=_extract_text(raw_text),
192
+ score=raw.get("relevancy_score") or raw.get("score") or raw.get("relevance_score"),
193
+ source_title=raw.get("source_title") or raw.get("title") or "",
194
+ id=raw.get("chunk_uuid") or raw.get("id") or "",
195
+ metadata=raw.get("metadata") or {},
196
+ )
197
+
198
+
199
+ def _extract_text(value: Any) -> str:
200
+ """Unwrap a HydraDB content envelope to its prose, else return as-is."""
201
+ if isinstance(value, dict):
202
+ return _prose_from_envelope(value) or json.dumps(value)
203
+ if not isinstance(value, str):
204
+ return str(value)
205
+ stripped = value.strip()
206
+ if stripped.startswith("{") and stripped.endswith("}"):
207
+ try:
208
+ obj = json.loads(stripped)
209
+ except ValueError:
210
+ return value
211
+ prose = _prose_from_envelope(obj)
212
+ if prose is not None:
213
+ return prose
214
+ return value
215
+
216
+
217
+ def _prose_from_envelope(obj: Any) -> str | None:
218
+ if not isinstance(obj, dict):
219
+ return None
220
+ content = obj.get("content")
221
+ if isinstance(content, dict):
222
+ for key in ("text", "markdown"):
223
+ val = content.get(key)
224
+ if isinstance(val, str) and val.strip():
225
+ return val
226
+ if isinstance(content, str) and content.strip():
227
+ return content
228
+ top = obj.get("text")
229
+ if isinstance(top, str) and top.strip():
230
+ return top
231
+ return None
@@ -0,0 +1,93 @@
1
+ """CrewAI external-memory storage backed by HydraDB.
2
+
3
+ CrewAI's ``ExternalMemory`` delegates to a ``Storage`` implementation with two
4
+ core operations: ``save`` (persist a task output) and ``search`` (recall
5
+ relevant history). This maps ``save`` → HydraDB ingest and ``search`` → HydraDB
6
+ recall, so a crew's memory lives in HydraDB and persists across runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ from .client import HydraDBClient
14
+
15
+ try:
16
+ from crewai.memory.storage.interface import Storage as _BaseStorage
17
+ except Exception: # pragma: no cover
18
+
19
+ class _BaseStorage:
20
+ def save(self, value: Any, metadata: dict[str, Any]) -> None: ...
21
+
22
+ def search(
23
+ self, query: str, limit: int = 3, score_threshold: float = 0.35
24
+ ) -> list[Any]: ...
25
+
26
+ def reset(self) -> None: ...
27
+
28
+
29
+ class HydraDBStorage(_BaseStorage):
30
+ """A CrewAI ``Storage`` that reads and writes HydraDB memory.
31
+
32
+ Example::
33
+
34
+ from crewai import Crew
35
+ from crewai.memory.external.external_memory import ExternalMemory
36
+ from hydradb_crewai import HydraDBStorage
37
+
38
+ crew = Crew(
39
+ agents=[...],
40
+ tasks=[...],
41
+ external_memory=ExternalMemory(
42
+ storage=HydraDBStorage(
43
+ HydraDBClient(api_key="sk_live_...", tenant_id="your-tenant")
44
+ )
45
+ ),
46
+ )
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ client: HydraDBClient,
52
+ kind: str = "knowledge",
53
+ infer: bool = True,
54
+ ) -> None:
55
+ self.client = client
56
+ self.kind = kind
57
+ self.infer = infer
58
+
59
+ def save(self, value: Any, metadata: dict[str, Any] | None = None) -> None:
60
+ """Persist a task output into HydraDB."""
61
+ text = value if isinstance(value, str) else str(value)
62
+ self.client.add_text(text, infer=self.infer, metadata=metadata or {})
63
+
64
+ def search(
65
+ self,
66
+ query: str,
67
+ limit: int = 3,
68
+ score_threshold: float = 0.35,
69
+ ) -> list[dict[str, Any]]:
70
+ """Recall relevant history for the current task."""
71
+ chunks = self.client.query(query, kind=self.kind, max_results=limit)
72
+ results: list[dict[str, Any]] = []
73
+ for chunk in chunks:
74
+ if chunk.score is not None and chunk.score < score_threshold:
75
+ continue
76
+ results.append(
77
+ {
78
+ "content": chunk.text,
79
+ "context": chunk.text,
80
+ "memory": chunk.text,
81
+ "score": chunk.score,
82
+ "metadata": {
83
+ "source_title": chunk.source_title,
84
+ "id": chunk.id,
85
+ **chunk.metadata,
86
+ },
87
+ }
88
+ )
89
+ return results
90
+
91
+ def reset(self) -> None:
92
+ """No bulk reset over the public API; delete by id via the client."""
93
+ return None
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "crewai-hydradb"
7
+ version = "0.1.0"
8
+ description = "HydraDB external-memory storage for CrewAI agents."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "HydraDB", email = "support@hydradb.com" }]
13
+ keywords = ["hydradb", "crewai", "memory", "agents"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ ]
21
+ dependencies = ["requests>=2.28"]
22
+
23
+ [project.optional-dependencies]
24
+ crewai = ["crewai>=1.0,<1.11"]
25
+ test = ["pytest>=7", "responses>=0.24"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://hydradb.com"
29
+ Documentation = "https://docs.hydradb.com/"
30
+ Repository = "https://github.com/hydra-db/hydradb-crewai"
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["hydradb_crewai"]
34
+
35
+ [tool.pytest.ini_options]
36
+ addopts = "--import-mode=importlib"
@@ -0,0 +1,51 @@
1
+ """Offline tests for the HydraDB CrewAI storage (no crewai/network needed)."""
2
+
3
+ import responses
4
+
5
+ from hydradb_crewai import HydraDBClient, HydraDBStorage
6
+
7
+ BASE = "https://api.hydradb.com"
8
+
9
+
10
+ def _storage():
11
+ client = HydraDBClient(api_key="k", tenant_id="test_beam", sub_tenant_id="")
12
+ return HydraDBStorage(client)
13
+
14
+
15
+ @responses.activate
16
+ def test_search_maps_chunks_and_filters_by_score():
17
+ responses.add(
18
+ responses.POST,
19
+ f"{BASE}/query",
20
+ json={
21
+ "success": True,
22
+ "data": {
23
+ "chunks": [
24
+ {"chunk_content": "keep me", "score": 0.9, "chunk_uuid": "a"},
25
+ {"chunk_content": "drop me", "score": 0.1, "chunk_uuid": "b"},
26
+ ]
27
+ },
28
+ "error": None,
29
+ },
30
+ status=200,
31
+ )
32
+ results = _storage().search("q", limit=5, score_threshold=0.35)
33
+ assert len(results) == 1
34
+ assert results[0]["content"] == "keep me"
35
+ assert results[0]["context"] == "keep me"
36
+ assert results[0]["metadata"]["id"] == "a"
37
+
38
+
39
+ @responses.activate
40
+ def test_save_ingests_as_knowledge():
41
+ responses.add(
42
+ responses.POST,
43
+ f"{BASE}/context/ingest",
44
+ json={"success": True, "data": {"success_count": 1}, "error": None},
45
+ status=200,
46
+ )
47
+ _storage().save("task output", metadata={"agent": "researcher"})
48
+ body = responses.calls[0].request.body
49
+ assert b"app_knowledge" in body
50
+ assert b"memories" not in body
51
+ assert b"test_beam" in body