crewai-recallic 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,76 @@
1
+ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2
+
3
+ # dependencies
4
+ /node_modules
5
+ /.pnp
6
+ .pnp.*
7
+ .yarn/*
8
+ !.yarn/patches
9
+ !.yarn/plugins
10
+ !.yarn/releases
11
+ !.yarn/versions
12
+
13
+ # testing
14
+ /coverage
15
+
16
+ # next.js
17
+ /.next/
18
+ /out/
19
+
20
+ # production
21
+ /build
22
+
23
+ # misc
24
+ .DS_Store
25
+ *.pem
26
+
27
+ # debug
28
+ npm-debug.log*
29
+ yarn-debug.log*
30
+ yarn-error.log*
31
+ .pnpm-debug.log*
32
+
33
+ # env files (can opt-in for committing if needed)
34
+ .env*
35
+
36
+ # vercel
37
+ .vercel
38
+
39
+ # typescript
40
+ *.tsbuildinfo
41
+ next-env.d.ts
42
+
43
+ # python
44
+ venv/
45
+ .venv/
46
+ __pycache__/
47
+ *.pyc
48
+ *.pyo
49
+ *.pyd
50
+ .Python
51
+ env/
52
+ pip-log.txt
53
+ pip-delete-this-directory.txt
54
+
55
+ # Databases and Local Models
56
+ *.db
57
+ *.sqlite
58
+ *.sqlite3
59
+ backend/models/
60
+ storage/
61
+
62
+ # Build and IDE
63
+ **/build/
64
+ .vscode/
65
+ .idea/
66
+ *.log
67
+
68
+ # Phase 6 training data (some sources are CC BY-SA; never committed)
69
+ .phase6_data/
70
+
71
+ # built Python packages (python -m build / pyproject-build)
72
+ integrations/*/dist/
73
+ legacy/*/dist/
74
+
75
+ # private submission drafts
76
+ submissions/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.5
2
+ Name: crewai-recallic
3
+ Version: 0.1.0
4
+ Summary: Recallic memory tools for CrewAI agents: self-hosted, no LLM calls for memory, says when it has no record.
5
+ Project-URL: Homepage, https://www.recallic.com
6
+ Project-URL: Source, https://github.com/Recallic/Recallic/tree/main/integrations/crewai
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Python: <3.14,>=3.10
10
+ Requires-Dist: crewai>=1.0
11
+ Requires-Dist: recallic>=0.3.0
12
+ Description-Content-Type: text/markdown
13
+
14
+ # crewai-recallic: Recallic memory tools for CrewAI
15
+
16
+ Website: [recallic.com](https://www.recallic.com)
17
+
18
+ Long-term memory for [CrewAI](https://www.crewai.com) agents, backed by a self-hosted
19
+ [Recallic](https://github.com/Recallic/Recallic) server. It gives an agent two tools: one to look up what a user told
20
+ it before, and one to save what the user tells it now.
21
+
22
+ * **No LLM calls for memory.** Storing and searching use Recallic's local models.
23
+ * **Across crews and runs.** A fact saved in one crew run can be recalled in any later run with the same user.
24
+ * **Honest.** When no stored memory answers the question, the tool tells the agent there is no record and not to
25
+ guess, instead of handing it near-misses.
26
+ * **Your data stays on your server**, separated per user and per agent.
27
+
28
+ This integration is Apache-2.0. The Recallic server is source-available.
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ pip install crewai-recallic
34
+ ```
35
+
36
+ Run Recallic ([quickstart](../../docs/quickstart.md)) and create a key with role `service`, which acts for each of
37
+ your users (or use a user's own key and leave `user_id` out):
38
+
39
+ ```bash
40
+ python -m backend.tools.keys create --user my-crewai-app --role service
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ ```python
46
+ import os
47
+
48
+ from crewai import Agent, Crew, Task
49
+ from crewai_recallic import recallic_tools
50
+
51
+ tools = recallic_tools(api_key=os.environ["RECALLIC_SERVICE_KEY"], user_id="alice",
52
+ base_url="http://localhost:8000") # recall_memory(query), save_memory(fact)
53
+
54
+ assistant = Agent(
55
+ role="Personal assistant",
56
+ goal="Help Alice, using what she told you before",
57
+ backstory="Before answering anything about Alice's life, look it up with recall_memory. "
58
+ "When she tells you something about herself, save it with save_memory.",
59
+ tools=tools,
60
+ llm="openai/gpt-5-mini",
61
+ )
62
+
63
+ task = Task(description="Alice says: {message}", expected_output="A short, friendly reply.", agent=assistant)
64
+ crew = Crew(agents=[assistant], tasks=[task])
65
+
66
+ crew.kickoff(inputs={"message": "I moved to Pune in March."})
67
+ crew.kickoff(inputs={"message": "Which city did I move to?"}) # "Pune."
68
+ crew.kickoff(inputs={"message": "What is my brother's name?"}) # says it has no record
69
+ ```
70
+
71
+ You can also make the tools one at a time:
72
+
73
+ ```python
74
+ from crewai_recallic import RecallicRecallTool, RecallicSaveTool
75
+
76
+ recall = RecallicRecallTool(api_key=key, user_id="alice", mode="cautious")
77
+ save = RecallicSaveTool(api_key=key, user_id="alice", memory_type="shared")
78
+ print(recall.run(query="Where do I work?"))
79
+ ```
80
+
81
+ | Parameter | Default | What it does |
82
+ |---|---|---|
83
+ | `api_key` | required | A Recallic key. Role `service` acts for the `user_id` you pass; a user key acts for itself. |
84
+ | `user_id` | `None` | Whose memory the tools read and write. Leave out with a user key. |
85
+ | `base_url` | `http://localhost:8000` | Your Recallic server. |
86
+ | `agent_id` | `crewai` | Recallic agent id; each agent reads back what it wrote (and what any agent shared). |
87
+ | `mode` | server's `recall.mode` | Recall only. `cautious` declines more (more "I don't know"); `helpful` answers more counting, ordering and "how long between" questions. |
88
+ | `limit` | 5 | Recall only. Memories given to the agent per lookup. |
89
+ | `memory_type` | `private` | Save only (`RecallicSaveTool`). `shared` makes the fact readable by all of the user's agents. |
90
+ | `timeout` | 30 | Seconds per request to Recallic. |
91
+
92
+ ## Notes
93
+
94
+ * **One user per tool instance.** CrewAI does not pass per-run context (such as the current user) to a tool, so the
95
+ user is fixed when the tool is made. In an app with many users, make the tools for each request:
96
+ `recallic_tools(api_key=key, user_id=request_user)`, and build the agent and crew with them.
97
+ * **Why tools and not CrewAI's memory setting.** CrewAI's built-in memory hands its storage records it has already
98
+ embedded and scoped with its own LLM. Recallic does the storing, matching and the "does anything answer this?"
99
+ check itself without an LLM, so it fits as tools the agent calls.
100
+ * What the agent gets back from `recall_memory` is the memories, newest facts first (with the date each was said),
101
+ or a note that there is no record. `format_memories(recall_result)` gives the same text for any Recallic recall
102
+ result.
103
+ * Tool results are not cached by CrewAI, because memory changes during a run. Pass `cache_function=` to change that.
104
+ * Needs Recallic server 0.2.5 or newer. Tested with crewai 1.15.
105
+
106
+ ## Tests
107
+
108
+ Against a running Recallic: `RECALLIC_URL=http://127.0.0.1:8000 RECALLIC_SERVICE_KEY=rx_... pytest tests`.
109
+ They include real CrewAI `Agent`/`Task`/`Crew` runs with a scripted LLM.
110
+
111
+ Licence: Apache-2.0.
@@ -0,0 +1,98 @@
1
+ # crewai-recallic: Recallic memory tools for CrewAI
2
+
3
+ Website: [recallic.com](https://www.recallic.com)
4
+
5
+ Long-term memory for [CrewAI](https://www.crewai.com) agents, backed by a self-hosted
6
+ [Recallic](https://github.com/Recallic/Recallic) server. It gives an agent two tools: one to look up what a user told
7
+ it before, and one to save what the user tells it now.
8
+
9
+ * **No LLM calls for memory.** Storing and searching use Recallic's local models.
10
+ * **Across crews and runs.** A fact saved in one crew run can be recalled in any later run with the same user.
11
+ * **Honest.** When no stored memory answers the question, the tool tells the agent there is no record and not to
12
+ guess, instead of handing it near-misses.
13
+ * **Your data stays on your server**, separated per user and per agent.
14
+
15
+ This integration is Apache-2.0. The Recallic server is source-available.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pip install crewai-recallic
21
+ ```
22
+
23
+ Run Recallic ([quickstart](../../docs/quickstart.md)) and create a key with role `service`, which acts for each of
24
+ your users (or use a user's own key and leave `user_id` out):
25
+
26
+ ```bash
27
+ python -m backend.tools.keys create --user my-crewai-app --role service
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ```python
33
+ import os
34
+
35
+ from crewai import Agent, Crew, Task
36
+ from crewai_recallic import recallic_tools
37
+
38
+ tools = recallic_tools(api_key=os.environ["RECALLIC_SERVICE_KEY"], user_id="alice",
39
+ base_url="http://localhost:8000") # recall_memory(query), save_memory(fact)
40
+
41
+ assistant = Agent(
42
+ role="Personal assistant",
43
+ goal="Help Alice, using what she told you before",
44
+ backstory="Before answering anything about Alice's life, look it up with recall_memory. "
45
+ "When she tells you something about herself, save it with save_memory.",
46
+ tools=tools,
47
+ llm="openai/gpt-5-mini",
48
+ )
49
+
50
+ task = Task(description="Alice says: {message}", expected_output="A short, friendly reply.", agent=assistant)
51
+ crew = Crew(agents=[assistant], tasks=[task])
52
+
53
+ crew.kickoff(inputs={"message": "I moved to Pune in March."})
54
+ crew.kickoff(inputs={"message": "Which city did I move to?"}) # "Pune."
55
+ crew.kickoff(inputs={"message": "What is my brother's name?"}) # says it has no record
56
+ ```
57
+
58
+ You can also make the tools one at a time:
59
+
60
+ ```python
61
+ from crewai_recallic import RecallicRecallTool, RecallicSaveTool
62
+
63
+ recall = RecallicRecallTool(api_key=key, user_id="alice", mode="cautious")
64
+ save = RecallicSaveTool(api_key=key, user_id="alice", memory_type="shared")
65
+ print(recall.run(query="Where do I work?"))
66
+ ```
67
+
68
+ | Parameter | Default | What it does |
69
+ |---|---|---|
70
+ | `api_key` | required | A Recallic key. Role `service` acts for the `user_id` you pass; a user key acts for itself. |
71
+ | `user_id` | `None` | Whose memory the tools read and write. Leave out with a user key. |
72
+ | `base_url` | `http://localhost:8000` | Your Recallic server. |
73
+ | `agent_id` | `crewai` | Recallic agent id; each agent reads back what it wrote (and what any agent shared). |
74
+ | `mode` | server's `recall.mode` | Recall only. `cautious` declines more (more "I don't know"); `helpful` answers more counting, ordering and "how long between" questions. |
75
+ | `limit` | 5 | Recall only. Memories given to the agent per lookup. |
76
+ | `memory_type` | `private` | Save only (`RecallicSaveTool`). `shared` makes the fact readable by all of the user's agents. |
77
+ | `timeout` | 30 | Seconds per request to Recallic. |
78
+
79
+ ## Notes
80
+
81
+ * **One user per tool instance.** CrewAI does not pass per-run context (such as the current user) to a tool, so the
82
+ user is fixed when the tool is made. In an app with many users, make the tools for each request:
83
+ `recallic_tools(api_key=key, user_id=request_user)`, and build the agent and crew with them.
84
+ * **Why tools and not CrewAI's memory setting.** CrewAI's built-in memory hands its storage records it has already
85
+ embedded and scoped with its own LLM. Recallic does the storing, matching and the "does anything answer this?"
86
+ check itself without an LLM, so it fits as tools the agent calls.
87
+ * What the agent gets back from `recall_memory` is the memories, newest facts first (with the date each was said),
88
+ or a note that there is no record. `format_memories(recall_result)` gives the same text for any Recallic recall
89
+ result.
90
+ * Tool results are not cached by CrewAI, because memory changes during a run. Pass `cache_function=` to change that.
91
+ * Needs Recallic server 0.2.5 or newer. Tested with crewai 1.15.
92
+
93
+ ## Tests
94
+
95
+ Against a running Recallic: `RECALLIC_URL=http://127.0.0.1:8000 RECALLIC_SERVICE_KEY=rx_... pytest tests`.
96
+ They include real CrewAI `Agent`/`Task`/`Crew` runs with a scripted LLM.
97
+
98
+ Licence: Apache-2.0.
@@ -0,0 +1,19 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "crewai-recallic"
7
+ version = "0.1.0"
8
+ description = "Recallic memory tools for CrewAI agents: self-hosted, no LLM calls for memory, says when it has no record."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10,<3.14"
12
+ dependencies = ["crewai>=1.0", "recallic>=0.3.0"]
13
+
14
+ [project.urls]
15
+ Homepage = "https://www.recallic.com"
16
+ Source = "https://github.com/Recallic/Recallic/tree/main/integrations/crewai"
17
+
18
+ [tool.hatch.build.targets.wheel]
19
+ packages = ["src/crewai_recallic"]
@@ -0,0 +1,4 @@
1
+ from crewai_recallic.tools import (DECLINE_NOTE, RecallicRecallTool, RecallicSaveTool, format_memories,
2
+ recallic_tools)
3
+
4
+ __all__ = ["RecallicRecallTool", "RecallicSaveTool", "recallic_tools", "format_memories", "DECLINE_NOTE"]
@@ -0,0 +1,151 @@
1
+ """
2
+ Recallic as long-term memory for CrewAI agents, as two tools.
3
+
4
+ from crewai import Agent
5
+ from crewai_recallic import recallic_tools
6
+
7
+ agent = Agent(role="Assistant", goal="...", backstory="...",
8
+ tools=recallic_tools(api_key="rx_...", user_id="alice"))
9
+
10
+ * RecallicRecallTool (`recall_memory`): what this user said before that answers the query, or a note that there is
11
+ no record (so the agent does not guess). It never hands back near-misses.
12
+ * RecallicSaveTool (`save_memory`): stores a fact the user told the agent.
13
+
14
+ Why tools and not a CrewAI memory backend: CrewAI's memory storage receives records the crew has already embedded
15
+ and scoped with its own LLM. Recallic embeds, scopes and decides what answers a question itself, without an LLM, so
16
+ it plugs in as tools the agent calls.
17
+
18
+ Whose memory: CrewAI passes no per-run context to a tool, so each tool instance is fixed to one `user_id`. Make the
19
+ tools per user (per request) in a multi-user app.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import asyncio
24
+ from datetime import datetime, timezone
25
+ from typing import Any, List, Optional, Type
26
+
27
+ from crewai.tools import BaseTool
28
+ from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
29
+ from recallic import Memory as RecallicClient
30
+
31
+ DECLINE_NOTE = ("No stored memory of this user answers this. If it depends on something they would have told you "
32
+ "before, say you don't have a record of it rather than guess about their past.")
33
+ HEADER = "Things this user told you before (newest facts win; use only what bears on the question):"
34
+
35
+
36
+ def _when(ts: Any) -> str:
37
+ try:
38
+ return datetime.fromtimestamp(float(ts), tz=timezone.utc).strftime("%d %b %Y")
39
+ except (TypeError, ValueError):
40
+ return ""
41
+
42
+
43
+ def _answered(out: dict) -> bool:
44
+ return out.get("status") == "CONSISTENT" and bool(out.get("memories"))
45
+
46
+
47
+ def format_memories(out: dict, limit: int = 5) -> str:
48
+ """A Recallic recall result as text for an agent: the memories, or the no-record note."""
49
+ if not _answered(out):
50
+ return DECLINE_NOTE
51
+ lines = [HEADER]
52
+ for m in out["memories"][:limit]:
53
+ when = _when(m.get("timestamp"))
54
+ lines.append(f"- {('[' + when + '] ') if when else ''}{m.get('content_resolved') or m.get('content', '')}")
55
+ computed = out.get("computed_answer")
56
+ if computed and computed.get("text"):
57
+ lines.append(f"Worked out from these memories: {computed['text']} "
58
+ f"({(out.get('receipt') or {}).get('computed', '')}).")
59
+ return "\n".join(lines)
60
+
61
+
62
+ def _no_cache(_args: Any = None, _result: Any = None) -> bool:
63
+ """Memory changes during a run (a save, then a recall), so tool results are never cached."""
64
+ return False
65
+
66
+
67
+ class RecallInput(BaseModel):
68
+ query: str = Field(..., description="What to look up about the user, e.g. 'Which city did I move to?'")
69
+
70
+
71
+ class SaveInput(BaseModel):
72
+ fact: str = Field(..., description="The fact the user told you, in their words, e.g. 'I moved to Pune in March.'")
73
+
74
+
75
+ class _RecallicTool(BaseTool):
76
+ """Connection and user settings shared by both tools."""
77
+
78
+ model_config = ConfigDict(arbitrary_types_allowed=True)
79
+
80
+ api_key: Optional[str] = Field(default=None, exclude=True, repr=False)
81
+ base_url: str = "http://localhost:8000"
82
+ user_id: Optional[str] = None
83
+ agent_id: str = "crewai"
84
+ timeout: float = 30.0
85
+ client: Optional[Any] = Field(default=None, exclude=True, repr=False)
86
+ _client: Any = PrivateAttr(default=None)
87
+
88
+ def model_post_init(self, __context: Any) -> None:
89
+ super().model_post_init(__context)
90
+ if "cache_function" not in self.model_fields_set:
91
+ self.cache_function = _no_cache
92
+ if self.client is None and not self.api_key:
93
+ raise ValueError("pass api_key (a Recallic key) or client")
94
+ self._client = self.client or RecallicClient(api_key=self.api_key, base_url=self.base_url,
95
+ timeout=self.timeout)
96
+
97
+
98
+ class RecallicRecallTool(_RecallicTool):
99
+ """
100
+ Looks up what this user told the agent before.
101
+
102
+ Returns the memories that answer the query, newest facts first, or, when Recallic finds none that does, a note
103
+ telling the agent there is no record and not to guess.
104
+ """
105
+
106
+ name: str = "recall_memory"
107
+ description: str = ("Look up what this user told you in earlier conversations. Use it for anything about the "
108
+ "user's own life, plans or preferences before answering.")
109
+ args_schema: Type[BaseModel] = RecallInput
110
+ mode: Optional[str] = None
111
+ limit: int = 5
112
+
113
+ def _run(self, query: str) -> str:
114
+ out = self._client.recall(query[:2000], limit=self.limit, agent_id=self.agent_id, user_id=self.user_id,
115
+ mode=self.mode)
116
+ return format_memories(out, self.limit)
117
+
118
+ async def _arun(self, query: str) -> str:
119
+ return await asyncio.to_thread(self._run, query)
120
+
121
+
122
+ class RecallicSaveTool(_RecallicTool):
123
+ """Stores a fact the user told the agent, so later runs (and other crews with the same agent_id) can recall it."""
124
+
125
+ name: str = "save_memory"
126
+ description: str = ("Remember a fact the user told you about themselves, in their words "
127
+ "(e.g. 'I moved to Pune in March').")
128
+ args_schema: Type[BaseModel] = SaveInput
129
+ memory_type: str = "private"
130
+
131
+ def _run(self, fact: str) -> str:
132
+ res = self._client.store(fact[:20000], agent_id=self.agent_id, memory_type=self.memory_type,
133
+ user_id=self.user_id, metadata={"speaker": "User", "source": "crewai-tool"})
134
+ status = res.get("status")
135
+ return {"stored": "Saved.", "skipped_duplicate": "Already remembered."}.get(status, f"Not stored ({status}).")
136
+
137
+ async def _arun(self, fact: str) -> str:
138
+ return await asyncio.to_thread(self._run, fact)
139
+
140
+
141
+ def recallic_tools(api_key: Optional[str] = None, *, user_id: Optional[str] = None,
142
+ base_url: str = "http://localhost:8000", agent_id: str = "crewai", mode: Optional[str] = None,
143
+ limit: int = 5, timeout: float = 30.0, client: Optional[RecallicClient] = None) -> List[BaseTool]:
144
+ """`recall_memory` and `save_memory` for one user, sharing one Recallic client."""
145
+ if client is None:
146
+ if not api_key:
147
+ raise ValueError("pass api_key (a Recallic key) or client")
148
+ client = RecallicClient(api_key=api_key, base_url=base_url, timeout=timeout)
149
+ common = dict(api_key=api_key, base_url=base_url, user_id=user_id, agent_id=agent_id, timeout=timeout,
150
+ client=client)
151
+ return [RecallicRecallTool(mode=mode, limit=limit, **common), RecallicSaveTool(**common)]
@@ -0,0 +1,103 @@
1
+ """
2
+ Live tests against a running Recallic:
3
+ RECALLIC_URL=http://127.0.0.1:8000 RECALLIC_SERVICE_KEY=rx_... pytest tests
4
+
5
+ The crew tests run a real CrewAI Agent, Task and Crew with a scripted LLM (no network model). The script decides
6
+ which tool to call; the test then checks what the tool sent back to the model.
7
+ """
8
+ import asyncio
9
+ import json
10
+ import os
11
+ import uuid
12
+ from typing import Any, List
13
+
14
+ os.environ.setdefault("CREWAI_DISABLE_TELEMETRY", "true")
15
+ os.environ.setdefault("OTEL_SDK_DISABLED", "true")
16
+
17
+ import pytest # noqa: E402
18
+ from crewai import Agent, Crew, Task # noqa: E402
19
+ from crewai.llms.base_llm import BaseLLM # noqa: E402
20
+ from crewai_recallic import (DECLINE_NOTE, RecallicRecallTool, RecallicSaveTool, # noqa: E402
21
+ recallic_tools)
22
+
23
+ URL, KEY = os.environ.get("RECALLIC_URL"), os.environ.get("RECALLIC_SERVICE_KEY")
24
+ pytestmark = pytest.mark.skipif(not (URL and KEY), reason="needs RECALLIC_URL and RECALLIC_SERVICE_KEY")
25
+
26
+
27
+ def _user():
28
+ return f"crew-{uuid.uuid4().hex[:8]}"
29
+
30
+
31
+ def _tools(user, **kw):
32
+ return recallic_tools(KEY, user_id=user, base_url=URL, agent_id="crewai-test", timeout=120, **kw)
33
+
34
+
35
+ class Scripted(BaseLLM):
36
+ """Calls one tool, then gives a final answer. Keeps every prompt it was sent."""
37
+ tool: str = ""
38
+ args: dict = {}
39
+ seen: List[str] = []
40
+
41
+ def call(self, messages: Any, tools: Any = None, callbacks: Any = None, available_functions: Any = None,
42
+ from_task: Any = None, from_agent: Any = None, response_model: Any = None) -> str:
43
+ text = messages if isinstance(messages, str) else "\n".join(str(m.get("content", "")) for m in messages)
44
+ self.seen.append(text)
45
+ if len(self.seen) == 1:
46
+ return f"Thought: I should use a tool.\nAction: {self.tool}\nAction Input: {json.dumps(self.args)}"
47
+ return "Thought: I now know the final answer\nFinal Answer: done"
48
+
49
+
50
+ def _crew_run(tools, tool, args):
51
+ llm = Scripted(model="scripted", tool=tool, args=args, seen=[])
52
+ agent = Agent(role="Assistant", goal="Help the user", backstory="You remember what users tell you.",
53
+ tools=tools, llm=llm, verbose=False, max_iter=3)
54
+ task = Task(description="Handle the user's message.", expected_output="A short reply.", agent=agent)
55
+ Crew(agents=[agent], tasks=[task], verbose=False).kickoff()
56
+ assert len(llm.seen) >= 2, "the tool result never went back to the model"
57
+ return llm.seen[1] # the prompt that carries the tool's observation
58
+
59
+
60
+ def test_tools_save_recall_and_decline():
61
+ recall, save = _tools(_user())
62
+ assert isinstance(recall, RecallicRecallTool) and isinstance(save, RecallicSaveTool)
63
+ assert save.run(fact="I moved to Pune in March, and my sister Mira is a pediatrician in Goa.") == "Saved."
64
+ assert save.run(fact="I moved to Pune in March, and my sister Mira is a pediatrician in Goa.") \
65
+ == "Already remembered."
66
+ assert "Pune" in recall.run(query="Which city did I move to?")
67
+ never = recall.run(query="What is my brother's name?")
68
+ assert never == DECLINE_NOTE and "don't have a record" in never
69
+
70
+
71
+ def test_users_are_kept_apart():
72
+ a, b = _user(), _user()
73
+ _tools(a)[1].run(fact="My dog is called Bruno.")
74
+ out = _tools(b)[0].run(query="What is my dog called?")
75
+ assert "Bruno" not in out and out == DECLINE_NOTE
76
+
77
+
78
+ def test_async_run():
79
+ recall, save = _tools(_user())
80
+
81
+ async def go():
82
+ await save.arun(fact="I work at a bakery in Lisbon.")
83
+ return await recall.arun(query="Where do I work?")
84
+
85
+ assert "Lisbon" in asyncio.run(go())
86
+
87
+
88
+ def test_secrets_stay_out_of_serialised_tools():
89
+ recall, _ = _tools(_user())
90
+ dumped = json.dumps(recall.model_dump(mode="json"), default=str)
91
+ assert KEY not in dumped and KEY not in repr(recall)
92
+
93
+
94
+ def test_crew_saves_then_recalls_in_a_later_crew():
95
+ user = _user()
96
+ _crew_run(_tools(user), "save_memory", {"fact": "I moved to Pune in March."})
97
+ seen = _crew_run(_tools(user), "recall_memory", {"query": "Which city did I move to?"}) # a new crew
98
+ assert "Pune" in seen
99
+
100
+
101
+ def test_crew_is_told_there_is_no_record():
102
+ seen = _crew_run(_tools(_user()), "recall_memory", {"query": "What is my brother's name?"})
103
+ assert "don't have a record" in seen