alexein-cli 0.3.0__py3-none-any.whl

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.
Files changed (40) hide show
  1. alexein_cli/__init__.py +127 -0
  2. alexein_cli/_version.py +1 -0
  3. alexein_cli/create.py +178 -0
  4. alexein_cli/create_crewai.py +138 -0
  5. alexein_cli/crews.py +120 -0
  6. alexein_cli/doctor.py +182 -0
  7. alexein_cli/env.py +125 -0
  8. alexein_cli/project.py +312 -0
  9. alexein_cli/render.py +40 -0
  10. alexein_cli/scaffold.py +369 -0
  11. alexein_cli/stop.py +12 -0
  12. alexein_cli/templates/crewai/memory.py.tmpl +55 -0
  13. alexein_cli/templates/crewai/project/README.md.tmpl +29 -0
  14. alexein_cli/templates/crewai/project/agents.yaml.tmpl +8 -0
  15. alexein_cli/templates/crewai/project/crew.py.tmpl +43 -0
  16. alexein_cli/templates/crewai/project/env.example.tmpl +8 -0
  17. alexein_cli/templates/crewai/project/gitignore.tmpl +3 -0
  18. alexein_cli/templates/crewai/project/main.py.tmpl +36 -0
  19. alexein_cli/templates/crewai/project/pyproject.toml.tmpl +20 -0
  20. alexein_cli/templates/crewai/project/tasks.yaml.tmpl +6 -0
  21. alexein_cli/templates/langgraph/memory.py.tmpl +45 -0
  22. alexein_cli/templates/langgraph/project/README.md.tmpl +31 -0
  23. alexein_cli/templates/langgraph/project/chat.py.tmpl +46 -0
  24. alexein_cli/templates/langgraph/project/env.example.tmpl +8 -0
  25. alexein_cli/templates/langgraph/project/graph.py.tmpl +61 -0
  26. alexein_cli/templates/langgraph/project/langgraph.json.tmpl +7 -0
  27. alexein_cli/templates/openai_agents/memory.py.tmpl +47 -0
  28. alexein_cli/templates/openai_agents/project/README.md.tmpl +25 -0
  29. alexein_cli/templates/openai_agents/project/agent.py.tmpl +43 -0
  30. alexein_cli/templates/openai_agents/project/chat.py.tmpl +38 -0
  31. alexein_cli/templates/openai_agents/project/env.example.tmpl +6 -0
  32. alexein_cli/templates/project/gitignore.tmpl +6 -0
  33. alexein_cli/templates/project/pyproject.toml.tmpl +14 -0
  34. alexein_cli/ui.py +75 -0
  35. alexein_cli/wiring.py +61 -0
  36. alexein_cli-0.3.0.dist-info/METADATA +208 -0
  37. alexein_cli-0.3.0.dist-info/RECORD +40 -0
  38. alexein_cli-0.3.0.dist-info/WHEEL +4 -0
  39. alexein_cli-0.3.0.dist-info/entry_points.txt +2 -0
  40. alexein_cli-0.3.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,369 @@
1
+ """`alexein-cli init <framework>`: write memory into a project as a short file its developer
2
+ owns - the settings and one configured `AlexeinMemory`, everything else imported from the
3
+ client's integration module.
4
+
5
+ The steps, in order, each of which can stop the command before anything is written: find the
6
+ project, make sure it uses the framework (or that adding it is wanted), make sure what is
7
+ installed is new enough, and pick where the file goes: beside the graph, or the agent. Then:
8
+ write the file, add `alexein[<framework>]`, and set up the key - which can be skipped, and
9
+ added later.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import shlex
16
+ import subprocess
17
+ import sys
18
+ from collections.abc import Callable, Sequence
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+
22
+ from alexein_cli import crews, env, project
23
+ from alexein_cli._version import __version__
24
+ from alexein_cli.render import render
25
+ from alexein_cli.stop import Stop
26
+ from alexein_cli.ui import Console
27
+ from alexein_cli.wiring import next_steps
28
+
29
+ # The client the written file imports: `alexein.langgraph`, `.openai_agents` and `.crewai`
30
+ # are its 0.3.
31
+ CLIENT = "alexein"
32
+ CLIENT_MINIMUM = "0.3"
33
+ # What each framework's file needs installed, at least - the client, and the framework as the
34
+ # client's extra for it requires it. LangGraph's: 1.2, whose runtime carries the thread a node
35
+ # runs in (the session what is saved belongs to). The OpenAI Agents SDK's: 0.24. CrewAI's:
36
+ # nothing beyond CrewAI, which the crew has already and `crews.py` checks.
37
+ MINIMUMS = {
38
+ "langgraph": {CLIENT: CLIENT_MINIMUM, "langgraph": "1.2", "langchain": "1.0"},
39
+ "openai-agents": {CLIENT: CLIENT_MINIMUM, "openai-agents": "0.24"},
40
+ "crewai": {CLIENT: CLIENT_MINIMUM},
41
+ }
42
+ # The client's extra for each framework, and the module the written file imports from it.
43
+ EXTRAS = {"langgraph": "langgraph", "openai-agents": "openai-agents", "crewai": "crewai"}
44
+ MODULES = {
45
+ "langgraph": "alexein.langgraph",
46
+ "openai-agents": "alexein.openai_agents",
47
+ "crewai": "alexein.crewai",
48
+ }
49
+ # How each is named to the developer.
50
+ NAMES = {"langgraph": "LangGraph", "openai-agents": "the OpenAI Agents SDK", "crewai": "CrewAI"}
51
+
52
+ Runner = Callable[[Sequence[str], Path], int]
53
+
54
+
55
+ def run_command(command: Sequence[str], cwd: Path) -> int:
56
+ """Run an install in the project, never in this CLI's own environment: `uv run` and `uvx`
57
+ set VIRTUAL_ENV to it, which poetry and pdm would install into."""
58
+ own = os.environ.get("VIRTUAL_ENV")
59
+ environ = dict(os.environ)
60
+ if own and Path(own).resolve() == Path(sys.prefix).resolve():
61
+ del environ["VIRTUAL_ENV"]
62
+ return subprocess.run(list(command), cwd=cwd, env=environ, check=False).returncode
63
+
64
+
65
+ @dataclass
66
+ class Options:
67
+ """Everything `init` can be told. `sdk` installs the client from somewhere other than PyPI:
68
+ a checkout's path, or a URL."""
69
+
70
+ framework: str = "langgraph"
71
+ directory: Path | None = None
72
+ filename: str = "memory.py"
73
+ graph: str | None = None
74
+ force: bool = False
75
+ install: bool = True
76
+ fast: bool = False
77
+ key: str | None = None
78
+ base_url: str | None = None
79
+ skip_key: bool = False
80
+ sdk: str | None = None
81
+ dry_run: bool = False
82
+ run: Runner = field(default=run_command)
83
+
84
+
85
+ def init(cwd: Path, options: Options, console: Console) -> int:
86
+ """Run `init`; the exit code: 0 done, 1 stopped or the install failed, 2 a bad command."""
87
+ try:
88
+ root, target = _prepare(cwd, options, console)
89
+ except Stop as stop:
90
+ console.fail(str(stop))
91
+ return stop.code
92
+ if options.dry_run:
93
+ _plan(root, target / options.filename, options, console)
94
+ return 0
95
+ written = write(target, options)
96
+ console.step("wrote", _relative(written, root))
97
+ installed = install(root, options, console)
98
+ setup_key(root, options, console)
99
+ console.line()
100
+ module = _module(written, root)
101
+ if options.framework == "crewai":
102
+ console.line(crews.next_steps(crews.crew(root), module))
103
+ else:
104
+ console.line(next_steps(module, options.framework))
105
+ return 0 if installed else 1
106
+
107
+
108
+ def _prepare(cwd: Path, options: Options, console: Console) -> tuple[Path, Path]:
109
+ """The project's root and where the file goes, or `Stop` with why not."""
110
+ framework = options.framework
111
+ if framework not in MINIMUMS:
112
+ raise Stop(f"no template for {framework!r}; there is: {', '.join(MINIMUMS)}", code=2)
113
+ if framework != "langgraph" and options.graph is not None:
114
+ raise Stop(f"--graph is for langgraph, not {framework}", code=2)
115
+ if options.filename and not options.filename.endswith(".py"):
116
+ raise Stop(f"--file must name a Python file: {options.filename!r}", code=2)
117
+ root = project.find_root(cwd)
118
+ if root is None:
119
+ raise Stop(
120
+ "no Python project here (no pyproject.toml, requirements.txt or langgraph.json at "
121
+ "or above this directory). Run it from your project, or start one with "
122
+ f"`alexein-cli create {framework} <name>`."
123
+ )
124
+ console.step("found", f"{project.installer(root, [CLIENT]).name} project at {root}")
125
+ if framework == "crewai":
126
+ return root, _crew_dir(root, cwd, options, console)
127
+ _require_framework(root, framework, console)
128
+ _require_versions(root, framework)
129
+ if options.directory:
130
+ target = (cwd / options.directory).resolve()
131
+ elif framework == "langgraph":
132
+ target = _graph_dir(root, options, console)
133
+ else:
134
+ target = _agent_dir(root, console)
135
+ written = target / options.filename
136
+ if written.exists() and not options.force:
137
+ raise Stop(f"{_relative(written, root)} exists; --force replaces it. Nothing changed.")
138
+ return root, target
139
+
140
+
141
+ def _crew_dir(root: Path, cwd: Path, options: Options, console: Console) -> Path:
142
+ """Where a CrewAI crew's file goes - beside its crew - once `crews.py` has checked it."""
143
+ found = crews.crew(root)
144
+ crews.require_version(root, console)
145
+ target = (cwd / options.directory).resolve() if options.directory else found.home
146
+ written = target / options.filename
147
+ if written.exists() and not options.force:
148
+ raise Stop(f"{_relative(written, root)} exists; --force replaces it. Nothing changed.")
149
+ return target
150
+
151
+
152
+ def _require_framework(root: Path, framework: str, console: Console) -> None:
153
+ if framework == "openai-agents" and project.shadows_agents(root):
154
+ console.step(
155
+ "warning",
156
+ "this project has an `agents` package of its own; the OpenAI Agents SDK is "
157
+ "imported as `agents` too, and the two would clash",
158
+ )
159
+ if project.uses(root, framework):
160
+ return
161
+ name = NAMES[framework]
162
+ console.step("note", f"this project does not use {name} yet")
163
+ if not console.confirm(f"Add {name} to it and go on?"):
164
+ raise Stop(
165
+ f"this project does not use {name}; run again with --yes to add it, or start a "
166
+ f"new one with `alexein-cli create {framework} <name>`. Nothing changed."
167
+ )
168
+
169
+
170
+ def _require_versions(root: Path, framework: str) -> None:
171
+ site = project.environment(root)
172
+ if site is None:
173
+ return
174
+ stale = [
175
+ (package, version, minimum)
176
+ for package, minimum in MINIMUMS[framework].items()
177
+ if package != CLIENT
178
+ and (version := project.installed(site, package))
179
+ and project.older(version, minimum)
180
+ ]
181
+ if stale:
182
+ found = ", ".join(f"{p} {v} (needs >={m})" for p, v, m in stale)
183
+ upgrade = shlex.join(f"{p}>={m}" for p, _, m in stale)
184
+ raise Stop(
185
+ f"this project has {found} installed. Upgrade first - "
186
+ f"{project.installer(root, []).name} add {upgrade} - then run init again. "
187
+ "Nothing changed."
188
+ )
189
+
190
+
191
+ def _graph_dir(root: Path, options: Options, console: Console) -> Path:
192
+ found = project.graphs(root)
193
+ if options.graph is not None:
194
+ if options.graph not in found:
195
+ names = ", ".join(found) or "none"
196
+ raise Stop(f"no graph {options.graph!r} in langgraph.json (there is: {names})")
197
+ return found[options.graph]
198
+ if len(found) <= 1:
199
+ return project.target_dir(root, next(iter(found.values()), None))
200
+ chosen = console.choose("Which graph is memory for?", list(found))
201
+ if chosen is None:
202
+ raise Stop(
203
+ f"langgraph.json has {len(found)} graphs ({', '.join(found)}); "
204
+ "name one with --graph. Nothing changed."
205
+ )
206
+ return found[chosen]
207
+
208
+
209
+ def _agent_dir(root: Path, console: Console) -> Path:
210
+ """Beside the code that builds an `Agent`; with none found, the project's own package."""
211
+ found = project.agent_dirs(root)
212
+ if not found:
213
+ console.step("note", "found no file that builds an Agent; writing to the project's package")
214
+ return project.target_dir(root)
215
+ if len(found) == 1:
216
+ return found[0]
217
+ named = [_relative(d, root) for d in found]
218
+ chosen = console.choose("Which agent is memory for?", named)
219
+ if chosen is None:
220
+ raise Stop(
221
+ f"{len(found)} directories build an Agent ({', '.join(named)}); "
222
+ "name one with --dir. Nothing changed."
223
+ )
224
+ return found[named.index(chosen)]
225
+
226
+
227
+ def _plan(root: Path, written: Path, options: Options, console: Console) -> None:
228
+ """What `init` would do, every check made, nothing changed and nothing sent."""
229
+ console.step("would", f"write {_relative(written, root)}")
230
+ planned(root, requirements(root, options), options, console)
231
+ key, _ = env.resolve(root)
232
+ if options.base_url:
233
+ console.step("would", f"set {env.BASE_URL} in .env")
234
+ if options.key:
235
+ console.step("would", f"set {env.KEY} in .env, and check it")
236
+ elif not key:
237
+ console.step("would", f"ask for the key, or add an empty {env.KEY}= to .env")
238
+ else:
239
+ console.step("would", "check the key already in .env")
240
+ console.line()
241
+ console.line("Dry run: nothing was changed.")
242
+
243
+
244
+ def planned(root: Path, packages: list[str], options: Options, console: Console) -> None:
245
+ if not packages:
246
+ console.step("would", "install nothing: every package is a dependency already")
247
+ return
248
+ found = project.installer(root, packages)
249
+ if found.requirements is not None:
250
+ console.step("would", f"add {', '.join(packages)} to {found.requirements.name}")
251
+ verb = "run" if found.command and options.install else "print"
252
+ console.step("would", f"{verb} {found.hint}")
253
+
254
+
255
+ def write(target: Path, options: Options) -> Path:
256
+ """The memory file: the settings, one configured `AlexeinMemory`, and the names the
257
+ framework's code uses, everything else imported from the integration module."""
258
+ template = f"{options.framework.replace('-', '_')}/memory.py.tmpl"
259
+ values = {"version": __version__, "fast": str(options.fast)}
260
+ target.mkdir(parents=True, exist_ok=True)
261
+ written = target / options.filename
262
+ written.write_text(render(template, (), values))
263
+ return written
264
+
265
+
266
+ def requirement(framework: str, sdk: str | None = None) -> str:
267
+ """The client with the framework's extra: `alexein[langgraph]>=0.3`, or from `sdk` - a
268
+ checkout's path or a URL - while it is not on PyPI."""
269
+ named = f"{CLIENT}[{EXTRAS[framework]}]"
270
+ if not sdk:
271
+ return f"{named}>={CLIENT_MINIMUM}"
272
+ if "://" in sdk:
273
+ return f"{named} @ {sdk}"
274
+ return f"{named} @ {Path(sdk).expanduser().resolve().as_uri()}"
275
+
276
+
277
+ def requirements(root: Path, options: Options) -> list[str]:
278
+ """What still has to be added for the file to import: the client with the framework's
279
+ extra, which brings the framework, unless the project depends on it already."""
280
+ if options.sdk is None and project.declares(root, CLIENT, EXTRAS[options.framework]):
281
+ return []
282
+ return [requirement(options.framework, options.sdk)]
283
+
284
+
285
+ def install(root: Path, options: Options, console: Console) -> bool:
286
+ """Add what the project does not depend on yet, with its own tool; True unless that failed."""
287
+ packages = requirements(root, options)
288
+ if not packages:
289
+ console.step("kept", f"{requirement(options.framework)}: already a dependency")
290
+ return True
291
+ found = project.installer(root, packages)
292
+ if found.requirements is not None:
293
+ present = found.requirements.read_text()
294
+ separator = "" if not present or present.endswith("\n") else "\n"
295
+ found.requirements.write_text(present + separator + "\n".join(packages) + "\n")
296
+ console.step("added", f"{', '.join(packages)} to {found.requirements.name}")
297
+ if found.command is None or not options.install:
298
+ console.step("run", found.hint)
299
+ return True
300
+ shown = found.hint
301
+ console.step("running", shown)
302
+ if options.run(found.command, root) != 0:
303
+ console.fail(f"`{shown}` failed; run it yourself, then go on.")
304
+ return False
305
+ console.step("ran", shown)
306
+ return True
307
+
308
+
309
+ def setup_key(root: Path, options: Options, console: Console) -> None:
310
+ """Put the key (and address) in `.env` and check it. Skippable: without one, an empty
311
+ `ALEXEIN_API_KEY=` is left to fill in, and `alexein-cli doctor` checks it later."""
312
+ dotenv = root / ".env"
313
+ if options.base_url:
314
+ console.step(
315
+ env.put(dotenv, env.BASE_URL, options.base_url, replace=True), f"{env.BASE_URL} in .env"
316
+ )
317
+ key, _ = env.resolve(root)
318
+ given = options.key
319
+ if given is None and not key and not options.skip_key:
320
+ given = (
321
+ console.secret(
322
+ "Your Alexein API key (from the console, under API keys; Enter to skip):"
323
+ )
324
+ or None
325
+ )
326
+ if given:
327
+ console.step(env.put(dotenv, env.KEY, given, replace=True), f"{env.KEY} in .env")
328
+ elif not key:
329
+ env.put(dotenv, env.KEY, "", replace=False)
330
+ console.step("added", f"{env.KEY}= to .env: fill it in later (console, under API keys)")
331
+ if not env.ignored(root):
332
+ console.step("warning", ".env is not in .gitignore; add it before a key goes in it")
333
+ key, base_url = env.resolve(root)
334
+ if key:
335
+ _check_key(key, base_url, options, console)
336
+
337
+
338
+ def _check_key(key: str, base_url: str | None, options: Options, console: Console) -> None:
339
+ checked = env.check(key, base_url)
340
+ if not checked.ok:
341
+ console.step("warning", f"the key did not check out: {checked.detail}")
342
+ return
343
+ console.step("checked", f"key: {checked.detail}")
344
+ if checked.writes is False:
345
+ console.step("warning", f"this key only reads: {SAVING[options.framework]}")
346
+
347
+
348
+ # What needs a key that writes, in each framework's words.
349
+ SAVING = {
350
+ "langgraph": "memory.remember and the memory_add tool need one that writes",
351
+ "openai-agents": "memory.remember and the memory_add tool need one that writes",
352
+ "crewai": "saving what a task learned needs one that writes",
353
+ }
354
+
355
+
356
+ def _relative(path: Path, root: Path) -> str:
357
+ try:
358
+ return f"./{path.relative_to(root)}"
359
+ except ValueError:
360
+ return str(path)
361
+
362
+
363
+ def _module(written: Path, root: Path) -> str:
364
+ """How the developer's code imports the written file: `app.memory`, `memory`, ..."""
365
+ try:
366
+ parts = list(written.with_suffix("").relative_to(root).parts)
367
+ except ValueError:
368
+ return written.stem
369
+ return ".".join(parts[1:] if parts[:1] == ["src"] else parts)
alexein_cli/stop.py ADDED
@@ -0,0 +1,12 @@
1
+ """Why a command stopped before changing anything, with the exit code to stop with."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class Stop(Exception):
7
+ """Raised by a check that fails; the command prints it and exits with `code`, having
8
+ changed nothing: 1 when the project is not ready, 2 when the command itself is wrong."""
9
+
10
+ def __init__(self, why: str, code: int = 1) -> None:
11
+ super().__init__(why)
12
+ self.code = code
@@ -0,0 +1,55 @@
1
+ """Long-term memory for this crew, from Alexein.
2
+
3
+ Generated by `alexein-cli init crewai` (alexein-cli {version}); yours to edit. The
4
+ settings are here; the memory comes from `alexein.crewai`
5
+ (https://docs.alexein.ai/integrations/crewai).
6
+
7
+ `alexein_memory` is CrewAI's own memory, kept in Alexein: CrewAI recalls the user's
8
+ memory before every task, saves what each task learned, and gives agents memory tools.
9
+
10
+ Crew(..., memory=alexein_memory, before_kickoff_callbacks=[whose])
11
+
12
+ or, in a @CrewBase class, `memory = alexein_memory` and a @before_kickoff method that
13
+ returns `whose(inputs)`; or, in crew.jsonc:
14
+
15
+ "memory": {"python": "memory.alexein_memory"},
16
+ "before_kickoff_callbacks": [{"python": "memory.whose"}]
17
+
18
+ Whose memory is read is your code's choice, never the model's: every kickoff names the
19
+ app user, `crew.kickoff(inputs={"user_id": "dana", ...})`. The key is ALEXEIN_API_KEY
20
+ and the address ALEXEIN_API_URL, read on the first call: importing needs neither.
21
+ """
22
+
23
+ from typing import Any
24
+
25
+ from alexein.crewai import AlexeinMemory
26
+
27
+ # True skips search's relevance check: free and quicker, a little less precise.
28
+ FAST = {fast}
29
+
30
+ # False keeps your crew running while memory is down: a task goes on without its
31
+ # memory, a save is skipped, and a warning is logged on the `alexein` logger. True
32
+ # stops a run at kickoff instead (CrewAI itself carries on past what memory raises
33
+ # during a task). A wrong key stops the run at kickoff either way.
34
+ STRICT = False
35
+
36
+ # How much of what memory holds goes into a prompt, in characters.
37
+ MAX_CHARS = 4000
38
+
39
+ # Seconds each attempt at a call may take; a call is tried up to three times. A task
40
+ # waits for its recall and saves.
41
+ TIMEOUT = 10.0
42
+
43
+ alexein_memory = AlexeinMemory(
44
+ fast=FAST,
45
+ max_chars=MAX_CHARS,
46
+ strict=STRICT,
47
+ timeout=TIMEOUT,
48
+ )
49
+
50
+
51
+ def whose(inputs: dict[str, Any]) -> dict[str, Any]:
52
+ """Before each kickoff: the app user from `inputs["user_id"]`, and the key checked
53
+ once. A function rather than `alexein_memory.whose`, because CrewAI keeps only
54
+ module-level callbacks when it restores a checkpoint."""
55
+ return alexein_memory.whose(inputs)
@@ -0,0 +1,29 @@
1
+ # {name}
2
+
3
+ A CrewAI crew that remembers the people it works for, with [Alexein](https://alexein.ai).
4
+ Made by `alexein-cli create crewai`.
5
+
6
+ ## Run it
7
+
8
+ 1. Fill in `.env`: `ALEXEIN_API_KEY` (the console, under API keys), and the key for the model
9
+ `MODEL` names.
10
+ 2. Ask it something, as one of your users:
11
+
12
+ ```bash
13
+ uv run run_crew --user dana "I just moved to Lisbon for a job at Acme."
14
+ uv run run_crew --user dana "Where do I live these days?"
15
+ ```
16
+
17
+ The second run remembers the first.
18
+
19
+ 3. `uvx alexein-cli doctor` checks the setup.
20
+
21
+ ## What is where
22
+
23
+ - `src/{package}/crew.py` - the crew: memory is wired in here.
24
+ - `src/{package}/memory.py` - memory's settings and wiring, written by `alexein-cli init crewai`;
25
+ the memory itself comes from `alexein.crewai`. Yours to edit.
26
+ - `src/{package}/config/` - the agent and the task.
27
+ - `src/{package}/main.py` - `run_crew`.
28
+
29
+ Whose memory a run reads is the `user_id` in its inputs, set by your code and never by the model.
@@ -0,0 +1,8 @@
1
+ assistant:
2
+ role: >
3
+ Personal assistant
4
+ goal: >
5
+ Help the user with what they ask, using what you remember about them
6
+ backstory: >
7
+ You work for one person over many conversations. You remember what they have told you
8
+ before, and you use it where it helps; you never invent it.
@@ -0,0 +1,43 @@
1
+ """The crew: one assistant that remembers the person it works for.
2
+
3
+ Made by `alexein-cli create crewai`. Memory comes from `memory.py`, beside it.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from typing import Any
10
+
11
+ from crewai import Agent, Crew, Task
12
+ from crewai.project import CrewBase, agent, before_kickoff, crew, task
13
+
14
+ from {package}.memory import alexein_memory, whose
15
+
16
+ # The model, as CrewAI names it: MODEL in .env.
17
+ MODEL: Any = os.environ.get("MODEL", "{model}")
18
+
19
+
20
+ @CrewBase
21
+ class {crew_class}:
22
+ agents_config = "config/agents.yaml"
23
+ tasks_config = "config/tasks.yaml"
24
+
25
+ # CrewAI recalls the user's memory before the task and saves what it found after;
26
+ # whose() takes the user from the run's inputs.
27
+ memory = alexein_memory
28
+
29
+ @before_kickoff
30
+ def whose_memory(self, inputs: dict[str, Any]) -> dict[str, Any]:
31
+ return whose(inputs)
32
+
33
+ @agent
34
+ def assistant(self) -> Agent:
35
+ return Agent(config=self.agents_config["assistant"], llm=MODEL)
36
+
37
+ @task
38
+ def answer(self) -> Task:
39
+ return Task(config=self.tasks_config["answer"])
40
+
41
+ @crew
42
+ def crew(self) -> Crew:
43
+ return Crew(agents=self.agents, tasks=self.tasks, memory=self.memory)
@@ -0,0 +1,8 @@
1
+ # The model the crew's agent thinks with, as CrewAI names it: provider/model.
2
+ MODEL={model}
3
+ # >>> provider_key
4
+ {provider_key}=
5
+ # <<< provider_key
6
+ # Alexein: make a key in the console, under API keys.
7
+ ALEXEIN_API_KEY=
8
+ # ALEXEIN_API_URL=https://api.alexein.ai
@@ -0,0 +1,3 @@
1
+ .venv/
2
+ .env
3
+ __pycache__/
@@ -0,0 +1,36 @@
1
+ """Ask the crew something, as one of your users:
2
+
3
+ uv run run_crew --user dana "Where do I live these days?"
4
+
5
+ Each run is a new conversation; what the crew remembers from the last one is memory's.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+
12
+ from dotenv import load_dotenv
13
+
14
+ load_dotenv()
15
+
16
+ # After .env: the model and memory read their keys from it.
17
+ from {package}.crew import {crew_class} # noqa: E402
18
+
19
+
20
+ def ask(user_id: str, question: str) -> str:
21
+ """One run of the crew for `user_id`; its reply."""
22
+ crew = {crew_class}().crew()
23
+ out = crew.kickoff(inputs={"user_id": user_id, "question": question})
24
+ return str(getattr(out, "raw", out))
25
+
26
+
27
+ def run() -> None:
28
+ parser = argparse.ArgumentParser(description="Ask the crew something.")
29
+ parser.add_argument("--user", default="dana", help="whose memory the crew reads")
30
+ parser.add_argument("question", nargs="+", help="what to ask")
31
+ args = parser.parse_args()
32
+ print(ask(args.user, " ".join(args.question)))
33
+
34
+
35
+ if __name__ == "__main__":
36
+ run()
@@ -0,0 +1,20 @@
1
+ [project]
2
+ name = "{name}"
3
+ version = "0.1.0"
4
+ description = "A CrewAI crew that remembers the people it works for, with Alexein."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10,<3.14"
7
+ dependencies = []
8
+
9
+ [project.scripts]
10
+ run_crew = "{package}.main:run"
11
+
12
+ [build-system]
13
+ requires = ["hatchling"]
14
+ build-backend = "hatchling.build"
15
+
16
+ [tool.hatch.build.targets.wheel]
17
+ packages = ["src/{package}"]
18
+
19
+ [tool.crewai]
20
+ type = "crew"
@@ -0,0 +1,6 @@
1
+ answer:
2
+ description: >
3
+ The user says: {question}
4
+ expected_output: >
5
+ A short, helpful reply to the user, in plain sentences.
6
+ agent: assistant
@@ -0,0 +1,45 @@
1
+ """Long-term memory for this graph, from Alexein.
2
+
3
+ Generated by `alexein-cli init langgraph` (alexein-cli {version}); yours to edit. The
4
+ settings are here; the nodes and tools come from `alexein.langgraph`
5
+ (https://docs.alexein.ai/integrations/langgraph).
6
+
7
+ builder = StateGraph(MemoryState, context_schema=MemoryContext)
8
+ builder.add_node("recall", memory.recall) # before your model: what memory holds
9
+ builder.add_node("agent", agent) # yours: memory.prompt(state) in its prompt
10
+ builder.add_node("remember", memory.remember) # after it: save the turn
11
+
12
+ Or tools the model calls itself: `create_agent(model, tools=memory.tools(), ...)`, and
13
+ `memory.tools(write=True)` to let it save too.
14
+
15
+ Whose memory is read is your code's choice, never the model's: run with
16
+ `context={"user_id": "dana"}`; the thread id is the session. The key is ALEXEIN_API_KEY
17
+ and the address ALEXEIN_API_URL, read on the first call: importing needs neither.
18
+ """
19
+
20
+ from alexein.langgraph import AlexeinMemory, MemoryContext, MemoryState
21
+
22
+ __all__ = ["MemoryContext", "MemoryState", "memory"]
23
+
24
+ # True skips search's relevance check: free and quicker, a little less precise. Use it
25
+ # where a reply cannot wait, like a voice agent's turn.
26
+ FAST = {fast}
27
+
28
+ # False keeps the graph running while memory is down: a turn goes on without its
29
+ # memory, a save is skipped, and a warning is logged on the `alexein` logger. True
30
+ # raises instead. A wrong key raises either way: that is a mistake to fix.
31
+ STRICT = False
32
+
33
+ # How much of what memory holds goes into the prompt, in characters.
34
+ MAX_CHARS = 4000
35
+
36
+ # Seconds each attempt at a call may take; a call is tried up to three times.
37
+ TIMEOUT = 10.0
38
+
39
+ # Runs under invoke and ainvoke; memory.arecall and memory.aremember are async nodes.
40
+ memory = AlexeinMemory(
41
+ fast=FAST,
42
+ max_chars=MAX_CHARS,
43
+ strict=STRICT,
44
+ timeout=TIMEOUT,
45
+ )
@@ -0,0 +1,31 @@
1
+ # {name}
2
+
3
+ A LangGraph agent that remembers the people it talks to, with [Alexein](https://alexein.ai).
4
+ Made by `alexein-cli create langgraph`.
5
+
6
+ ## Run it
7
+
8
+ 1. Fill in `.env`: `ALEXEIN_API_KEY` (the console, under API keys), and the key for the model
9
+ `MODEL` names.
10
+ 2. Talk to it in a terminal, as one of your users:
11
+
12
+ ```bash
13
+ uv run -m {package}.chat --user dana
14
+ ```
15
+
16
+ Or open it in LangGraph Studio, passing `{"user_id": "dana"}` as the run's context:
17
+
18
+ ```bash
19
+ uv run langgraph dev
20
+ ```
21
+
22
+ 3. `uvx alexein-cli doctor` checks the setup.
23
+
24
+ ## What is where
25
+
26
+ - `src/{package}/graph.py` - the graph: memory is wired in here.
27
+ - `src/{package}/memory.py` - memory's settings and wiring, written by
28
+ `alexein-cli init langgraph`; the nodes and tools come from `alexein.langgraph`. Yours to edit.
29
+ - `src/{package}/chat.py` - the terminal chat.
30
+
31
+ Whose memory a run reads is the `user_id` in its context, set by your code and never by the model.