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,127 @@
1
+ """`alexein-cli`, in the manner of shadcn: what it writes is the developer's own code from
2
+ then on - a short `memory.py` with their settings and one configured `AlexeinMemory`, wired
3
+ from the `alexein` client's integration modules - and nothing in this package reaches back
4
+ into it.
5
+
6
+ alexein-cli init langgraph memory for a LangGraph project you have
7
+ alexein-cli init openai-agents ... or an OpenAI Agents SDK one
8
+ alexein-cli init crewai ... or a CrewAI crew
9
+ alexein-cli create <framework> X a new project with memory wired in
10
+ alexein-cli doctor whether a project is set up for memory
11
+
12
+ The standard library and the `alexein` client only; it never imports a framework. Never an
13
+ installer of anything but the package the written files import, and never a writer of a key it
14
+ was not given.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import sys
21
+ from collections.abc import Sequence
22
+ from pathlib import Path
23
+
24
+ # The modules, not their functions: `create` and `doctor` are names of both, and binding the
25
+ # function here would hide the module of the same name from `alexein_cli.create`.
26
+ from alexein_cli import create as creating
27
+ from alexein_cli import create_crewai
28
+ from alexein_cli import doctor as checking
29
+ from alexein_cli._version import __version__
30
+ from alexein_cli.scaffold import MINIMUMS, Options, init
31
+ from alexein_cli.ui import Console
32
+
33
+
34
+ def _setup_flags(parser: argparse.ArgumentParser) -> None:
35
+ """What `init` and `create` share: the one preset, the key, and how far to go unasked."""
36
+ parser.add_argument(
37
+ "--fast",
38
+ action="store_true",
39
+ help="FAST = True: searches skip the relevance check, free and quicker",
40
+ )
41
+ key = parser.add_argument_group("the key (all of it can be skipped, and done later)")
42
+ key.add_argument("--key", help="your API key, written into .env and checked")
43
+ key.add_argument("--base-url", help="memory's address, written into .env")
44
+ key.add_argument("--skip-key", action="store_true", help="do not ask for a key")
45
+ parser.add_argument("--yes", "-y", action="store_true", help="answer yes; ask nothing")
46
+ parser.add_argument(
47
+ "--dry-run",
48
+ action="store_true",
49
+ help="check everything, say what would happen, change nothing",
50
+ )
51
+ parser.add_argument(
52
+ "--no-install", action="store_true", help="print install commands instead of running them"
53
+ )
54
+ # Installs the client from a checkout's path or a URL instead of PyPI.
55
+ parser.add_argument("--sdk", help=argparse.SUPPRESS)
56
+
57
+
58
+ def _parser() -> argparse.ArgumentParser:
59
+ parser = argparse.ArgumentParser(
60
+ prog="alexein-cli",
61
+ description="Memory from Alexein for LangGraph, CrewAI and the OpenAI Agents SDK, "
62
+ "as code you own.",
63
+ )
64
+ parser.add_argument("--version", action="version", version=f"alexein-cli {__version__}")
65
+ commands = parser.add_subparsers(dest="command", required=True)
66
+
67
+ start = commands.add_parser("init", help="write memory into this project, as code you own")
68
+ start.add_argument("framework", help="langgraph, openai-agents or crewai")
69
+ start.add_argument("--dir", type=Path, help="where to write the file (default: found)")
70
+ start.add_argument("--file", default="memory.py", help="the file's name (default: memory.py)")
71
+ start.add_argument("--graph", help="which graph in langgraph.json it is for (langgraph)")
72
+ start.add_argument("--force", action="store_true", help="replace a file already there")
73
+ _setup_flags(start)
74
+
75
+ new = commands.add_parser("create", help="a new project with memory wired in")
76
+ new.add_argument("framework", help="langgraph, openai-agents or crewai")
77
+ new.add_argument("name", help="the project's directory and name")
78
+ new.add_argument(
79
+ "--model",
80
+ help=(
81
+ f"the model, as the framework names it (LangGraph: {creating.DEFAULT_MODEL}; "
82
+ f"CrewAI: {create_crewai.DEFAULT_MODEL}; the OpenAI Agents SDK: its own default)"
83
+ ),
84
+ )
85
+ _setup_flags(new)
86
+
87
+ commands.add_parser("doctor", help="check that this project is set up for memory")
88
+ return parser
89
+
90
+
91
+ def _options(args: argparse.Namespace) -> Options:
92
+ return Options(
93
+ framework=args.framework,
94
+ directory=getattr(args, "dir", None),
95
+ filename=getattr(args, "file", "memory.py"),
96
+ graph=getattr(args, "graph", None),
97
+ force=getattr(args, "force", False),
98
+ install=not args.no_install,
99
+ fast=args.fast,
100
+ key=args.key,
101
+ base_url=args.base_url,
102
+ skip_key=args.skip_key or args.yes,
103
+ sdk=args.sdk,
104
+ dry_run=args.dry_run,
105
+ )
106
+
107
+
108
+ def main(argv: Sequence[str] | None = None, console: Console | None = None) -> int:
109
+ args = _parser().parse_args(argv)
110
+ cwd = Path.cwd()
111
+ if args.command == "doctor":
112
+ return checking.doctor(cwd, console or Console.for_terminal(yes=True))
113
+ console = console or Console.for_terminal(yes=args.yes)
114
+ if args.command == "create":
115
+ if args.framework not in MINIMUMS:
116
+ console.fail(f"no template for {args.framework!r}; there is: {', '.join(MINIMUMS)}")
117
+ return 2
118
+ if args.framework == "crewai":
119
+ model = args.model or create_crewai.DEFAULT_MODEL
120
+ return create_crewai.create(args.name, cwd, model, _options(args), console)
121
+ model = args.model or (creating.DEFAULT_MODEL if args.framework == "langgraph" else "")
122
+ return creating.create(args.name, cwd, model, _options(args), console)
123
+ return init(cwd, _options(args), console)
124
+
125
+
126
+ if __name__ == "__main__":
127
+ sys.exit(main())
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
alexein_cli/create.py ADDED
@@ -0,0 +1,178 @@
1
+ """`alexein-cli create <framework> <name>`: a new project with memory already wired in - for
2
+ LangGraph a graph, a terminal chat, `langgraph.json` for `langgraph dev`; for the OpenAI Agents
3
+ SDK an agent and a terminal chat; and `memory.py` as `init` writes it - so there is something to
4
+ run before there is anything to wire.
5
+
6
+ The project is a uv one: `uvx` is how this command is run, so uv is there to run it with.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ import shlex
13
+ import shutil
14
+ from pathlib import Path
15
+
16
+ from alexein_cli import env, scaffold
17
+ from alexein_cli.render import render
18
+ from alexein_cli.ui import Console
19
+
20
+ # LangGraph's, as `init_chat_model` names it. The OpenAI Agents SDK has a default of its own,
21
+ # which an agent gets when it names none.
22
+ DEFAULT_MODEL = "anthropic:claude-sonnet-5-5"
23
+
24
+ # The LangChain package each `init_chat_model` provider needs, and the key it reads. A provider
25
+ # not named here still works; its package and key are the developer's to add.
26
+ PROVIDERS = {
27
+ "anthropic": ("langchain-anthropic", "ANTHROPIC_API_KEY"),
28
+ "openai": ("langchain-openai", "OPENAI_API_KEY"),
29
+ "azure_openai": ("langchain-openai", "AZURE_OPENAI_API_KEY"),
30
+ "google_genai": ("langchain-google-genai", "GOOGLE_API_KEY"),
31
+ "mistralai": ("langchain-mistralai", "MISTRAL_API_KEY"),
32
+ "groq": ("langchain-groq", "GROQ_API_KEY"),
33
+ "ollama": ("langchain-ollama", ""),
34
+ "bedrock_converse": ("langchain-aws", ""),
35
+ }
36
+ _NAME = re.compile(r"[A-Za-z][A-Za-z0-9_-]{0,63}")
37
+
38
+
39
+ def create(name: str, cwd: Path, model: str, options: scaffold.Options, console: Console) -> int:
40
+ """Make the project; 0 when it is ready, 1 when something stopped it, 2 a bad command."""
41
+ if not _NAME.fullmatch(name):
42
+ console.fail(f"{name!r} is not a project name: letters, digits, '-' and '_'")
43
+ return 2
44
+ root = (cwd / name).resolve()
45
+ if root.exists() and any(root.iterdir()):
46
+ console.fail(f"{root} exists and is not empty. Nothing changed.")
47
+ return 1
48
+ if options.install and not shutil.which("uv"):
49
+ console.fail("this needs uv to set the project up: https://docs.astral.sh/uv/")
50
+ return 1
51
+ package = name.replace("-", "_").lower()
52
+ langgraph = options.framework == "langgraph"
53
+ if langgraph:
54
+ provider = model.split(":", 1)[0] if ":" in model else ""
55
+ library, provider_key = PROVIDERS.get(provider, ("", ""))
56
+ else:
57
+ library, provider_key = "", "OPENAI_API_KEY"
58
+ packages = [*scaffold.requirements(root, options), "python-dotenv"]
59
+ packages += [library] if library else []
60
+ commands = [["uv", "add", *packages]]
61
+ commands += [["uv", "add", "--dev", "langgraph-cli[inmem]"]] if langgraph else []
62
+ if options.dry_run:
63
+ _plan(root, package, commands, options, console)
64
+ return 0
65
+ _skeleton(root, name, package, model, provider_key, options.framework)
66
+ console.step("made", f"{root}")
67
+ scaffold.write(root / "src" / package, options)
68
+ console.step("wrote", f"src/{package}/memory.py, {_MAIN[options.framework]}, chat.py")
69
+ installed = _install(root, commands, options, console)
70
+ if langgraph and not library:
71
+ console.step("note", f"add the LangChain package for {model!r} yourself")
72
+ scaffold.setup_key(root, options, console)
73
+ console.line()
74
+ key, _ = env.resolve(root)
75
+ unset = [k for k in (provider_key,) if k] + ([] if key else [env.KEY])
76
+ console.line(_next(name, package, unset, langgraph=langgraph))
77
+ return 0 if installed else 1
78
+
79
+
80
+ # The file each framework's project is built around, beside `memory.py` and `chat.py`, and
81
+ # what the project is, for its pyproject.toml.
82
+ _MAIN = {"langgraph": "graph.py", "openai-agents": "agent.py"}
83
+ _DESCRIBED = {"langgraph": "A LangGraph agent", "openai-agents": "An OpenAI Agents SDK agent"}
84
+
85
+
86
+ def _plan(
87
+ root: Path, package: str, commands: list[list[str]], options: scaffold.Options, console: Console
88
+ ) -> None:
89
+ """What `create` would do, nothing made and nothing run."""
90
+ console.step("would", f"make {root}")
91
+ langgraph = ("langgraph.json",) if options.framework == "langgraph" else ()
92
+ for path in ("pyproject.toml", *langgraph, "README.md", ".gitignore", ".env"):
93
+ console.step("would", f"write {path}")
94
+ for path in (_MAIN[options.framework], "chat.py", "memory.py"):
95
+ console.step("would", f"write src/{package}/{path}")
96
+ verb = "run" if options.install else "print"
97
+ for command in commands:
98
+ console.step("would", f"{verb} {_shown(command)}")
99
+ console.line()
100
+ console.line("Dry run: nothing was made.")
101
+
102
+
103
+ def _skeleton(
104
+ root: Path, name: str, package: str, model: str, provider_key: str, framework: str
105
+ ) -> None:
106
+ langgraph = framework == "langgraph"
107
+ values = {
108
+ "name": name,
109
+ "package": package,
110
+ "model": model,
111
+ "provider_key": provider_key,
112
+ "description": f"{_DESCRIBED[framework]} that remembers the people it talks to, "
113
+ "with Alexein.",
114
+ }
115
+ own = f"{framework.replace('-', '_')}/project"
116
+ main = _MAIN[framework]
117
+ files: dict[str, tuple[str, tuple[str, ...]] | None] = {
118
+ "pyproject.toml": ("project/pyproject.toml.tmpl", ()),
119
+ ".gitignore": ("project/gitignore.tmpl", ("langgraph",) if langgraph else ()),
120
+ "README.md": (f"{own}/README.md.tmpl", ()),
121
+ ".env.example": (f"{own}/env.example.tmpl", ("provider_key",) if provider_key else ()),
122
+ f"src/{package}/{main}": (f"{own}/{main}.tmpl", ()),
123
+ f"src/{package}/chat.py": (f"{own}/chat.py.tmpl", ()),
124
+ f"src/{package}/__init__.py": None,
125
+ }
126
+ if langgraph:
127
+ files["langgraph.json"] = (f"{own}/langgraph.json.tmpl", ())
128
+ for path, source in files.items():
129
+ target = root / path
130
+ target.parent.mkdir(parents=True, exist_ok=True)
131
+ if source is None:
132
+ target.write_text("")
133
+ continue
134
+ template, parts = source
135
+ target.write_text(render(template, parts, values))
136
+ example = (root / ".env.example").read_text()
137
+ (root / ".env").write_text(
138
+ "\n".join(line for line in example.splitlines() if not line.startswith("#")) + "\n"
139
+ )
140
+
141
+
142
+ def _shown(command: list[str]) -> str:
143
+ """A command as it would be typed, quoted for the shell."""
144
+ return shlex.join(command)
145
+
146
+
147
+ def _install(
148
+ root: Path, commands: list[list[str]], options: scaffold.Options, console: Console
149
+ ) -> bool:
150
+ for command in commands:
151
+ shown = _shown(command)
152
+ if not options.install:
153
+ console.step("run", shown)
154
+ continue
155
+ console.step("running", shown)
156
+ if options.run(command, root) != 0:
157
+ console.fail(f"`{shown}` failed; run it in {root} yourself, then go on.")
158
+ return False
159
+ console.step("ran", shown)
160
+ return True
161
+
162
+
163
+ def _next(name: str, package: str, unset: list[str], *, langgraph: bool) -> str:
164
+ fill = [f" # fill in {' and '.join(unset)} in .env"] if unset else []
165
+ steps = [(f"uv run -m {package}.chat --user dana", "talk to it")]
166
+ steps += [("uv run langgraph dev", "or open it in LangGraph Studio")] if langgraph else []
167
+ steps += [("uvx alexein-cli doctor", "check the setup")]
168
+ # The comments line up however long the package's name makes the first command.
169
+ width = max(len(command) for command, _ in steps) + 3
170
+ return "\n".join(
171
+ [
172
+ " Next:",
173
+ "",
174
+ f" cd {name}",
175
+ *fill,
176
+ *(f" {command.ljust(width)}# {why}" for command, why in steps),
177
+ ]
178
+ )
@@ -0,0 +1,138 @@
1
+ """`alexein-cli create crewai <name>`: a new classic CrewAI crew with memory already wired in -
2
+ an assistant agent, its task, `run_crew`, and `memory.py` as `init crewai` writes it - so there is
3
+ something to run before there is anything to wire.
4
+
5
+ The project is a uv one, laid out as `crewai create crew --classic` lays one out, made here so the
6
+ `crewai` command need not be installed first.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ import shlex
13
+ import shutil
14
+ from pathlib import Path
15
+
16
+ from alexein_cli import crews, env, scaffold
17
+ from alexein_cli.render import render
18
+ from alexein_cli.ui import Console
19
+
20
+ DEFAULT_MODEL = "anthropic/claude-sonnet-5-5"
21
+
22
+ # What each CrewAI provider needs: the `crewai` extra that brings its SDK, and the key it reads.
23
+ # A provider not named here still works; its key is the developer's to add.
24
+ PROVIDERS = {
25
+ "anthropic": ("anthropic", "ANTHROPIC_API_KEY"),
26
+ "claude": ("anthropic", "ANTHROPIC_API_KEY"),
27
+ "openai": ("", "OPENAI_API_KEY"),
28
+ "openrouter": ("", "OPENROUTER_API_KEY"),
29
+ "deepseek": ("", "DEEPSEEK_API_KEY"),
30
+ "gemini": ("google-genai", "GEMINI_API_KEY"),
31
+ "google": ("google-genai", "GEMINI_API_KEY"),
32
+ "bedrock": ("bedrock", ""),
33
+ "ollama": ("", ""),
34
+ }
35
+ _NAME = re.compile(r"[a-z][a-z0-9-]{0,63}")
36
+ _PROJECT = "crewai/project/"
37
+
38
+
39
+ def create(name: str, cwd: Path, model: str, options: scaffold.Options, console: Console) -> int:
40
+ """Make the crew; 0 when it is ready, 1 when something stopped it, 2 a bad command."""
41
+ if not _NAME.fullmatch(name):
42
+ console.fail(f"{name!r} is not a project name: lowercase letters, digits and '-'")
43
+ return 2
44
+ root = (cwd / name).resolve()
45
+ if root.exists() and any(root.iterdir()):
46
+ console.fail(f"{root} exists and is not empty. Nothing changed.")
47
+ return 1
48
+ if options.install and not options.dry_run and not shutil.which("uv"):
49
+ console.fail("this needs uv to set the project up: https://docs.astral.sh/uv/")
50
+ return 1
51
+ options.framework = "crewai"
52
+ package = name.replace("-", "_")
53
+ extra, provider_key = PROVIDERS.get(model.split("/", 1)[0], ("", ""))
54
+ floor = crews.CREWAI_MINIMUM
55
+ crewai = f"crewai[{extra}]>={floor}" if extra else f"crewai>={floor}"
56
+ packages = [*scaffold.requirements(root, options), crewai, "python-dotenv"]
57
+ files = _files(package, provider_key)
58
+ if options.dry_run:
59
+ console.step("would", f"make {root}")
60
+ for path in [*files, f"src/{package}/memory.py"]:
61
+ console.step("would", f"write {path}")
62
+ verb = "run" if options.install else "print"
63
+ console.step("would", f"{verb} {shlex.join(['uv', 'add', *packages])}")
64
+ console.line()
65
+ console.line("Dry run: nothing was made.")
66
+ return 0
67
+ values = {
68
+ "name": name,
69
+ "package": package,
70
+ "model": model,
71
+ "provider_key": provider_key,
72
+ "crew_class": "".join(part.capitalize() for part in name.split("-")),
73
+ }
74
+ for path, (template, parts) in files.items():
75
+ target = root / path
76
+ target.parent.mkdir(parents=True, exist_ok=True)
77
+ target.write_text(render(_PROJECT + template, parts, values) if template else "")
78
+ example = (root / ".env.example").read_text().splitlines()
79
+ (root / ".env").write_text("\n".join(x for x in example if not x.startswith("#")) + "\n")
80
+ scaffold.write(root / "src" / package, options)
81
+ console.step("made", str(root))
82
+ installed = _install(root, packages, options, console)
83
+ if installed and options.install:
84
+ crews.require_version(root, console) # the newest CrewAI, maybe newer than tested
85
+ scaffold.setup_key(root, options, console)
86
+ key, _ = env.resolve(root)
87
+ unset = [k for k in (provider_key,) if k] + ([] if key else [env.KEY])
88
+ console.line()
89
+ console.line(_next(name, unset))
90
+ return 0 if installed else 1
91
+
92
+
93
+ def _files(package: str, provider_key: str) -> dict[str, tuple[str, tuple[str, ...]]]:
94
+ """Each file the project gets, from which template, with which of its parts."""
95
+ return {
96
+ f"src/{package}/crew.py": ("crew.py.tmpl", ()),
97
+ f"src/{package}/main.py": ("main.py.tmpl", ()),
98
+ "pyproject.toml": ("pyproject.toml.tmpl", ()),
99
+ "README.md": ("README.md.tmpl", ()),
100
+ ".gitignore": ("gitignore.tmpl", ()),
101
+ ".env.example": ("env.example.tmpl", ("provider_key",) if provider_key else ()),
102
+ f"src/{package}/__init__.py": ("", ()),
103
+ f"src/{package}/config/agents.yaml": ("agents.yaml.tmpl", ()),
104
+ f"src/{package}/config/tasks.yaml": ("tasks.yaml.tmpl", ()),
105
+ }
106
+
107
+
108
+ def _install(root: Path, packages: list[str], options: scaffold.Options, console: Console) -> bool:
109
+ command = ["uv", "add", *packages]
110
+ shown = shlex.join(command)
111
+ if not options.install:
112
+ console.step("run", shown)
113
+ return True
114
+ console.step("running", shown)
115
+ if options.run(command, root) != 0:
116
+ console.fail(f"`{shown}` failed; run it in {root} yourself, then go on.")
117
+ return False
118
+ console.step("ran", shown)
119
+ return True
120
+
121
+
122
+ def _next(name: str, unset: list[str]) -> str:
123
+ fill = [f" # fill in {' and '.join(unset)} in .env"] if unset else []
124
+ steps = [
125
+ ('uv run run_crew --user dana "I just moved to Lisbon."', "tell it something"),
126
+ ('uv run run_crew --user dana "Where do I live?"', "it remembers"),
127
+ ("uvx alexein-cli doctor", "check the setup"),
128
+ ]
129
+ width = max(len(command) for command, _ in steps) + 3
130
+ return "\n".join(
131
+ [
132
+ " Next:",
133
+ "",
134
+ f" cd {name}",
135
+ *fill,
136
+ *(f" {command.ljust(width)}# {why}" for command, why in steps),
137
+ ]
138
+ )
alexein_cli/crews.py ADDED
@@ -0,0 +1,120 @@
1
+ """What `init crewai` knows about CrewAI: which crews it can serve, the CrewAI it needs, and the
2
+ lines a developer adds to turn memory on.
3
+
4
+ Not the written file - that is `templates/crewai/memory.py.tmpl` - and not the steps every
5
+ framework shares, which are `scaffold.py`'s.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ from alexein_cli import env, project
13
+ from alexein_cli.stop import Stop
14
+ from alexein_cli.ui import Console
15
+
16
+ # `alexein.crewai` subclasses CrewAI's `Memory`, which CrewAI does not document as a place to
17
+ # extend: it was verified against 1.15, and a newer CrewAI is used with a warning, not refused.
18
+ CREWAI_MINIMUM = "1.15"
19
+ CREWAI_TESTED = "1.15"
20
+
21
+
22
+ def crew(root: Path) -> project.Crew:
23
+ """The crew to serve at `root`, or `Stop` with why there is none."""
24
+ found = project.crew(root)
25
+ if found is None:
26
+ raise Stop(
27
+ "not a CrewAI crew (no [tool.crewai] in pyproject.toml, and no @CrewBase crew). "
28
+ "Start one with `alexein-cli create crewai <name>`. Nothing changed."
29
+ )
30
+ if found.kind == "flow":
31
+ raise Stop("this is a CrewAI Flow; Flows are not supported yet. Nothing changed.")
32
+ return found
33
+
34
+
35
+ def require_version(root: Path, console: Console) -> None:
36
+ """Stop on a CrewAI older than the file needs; warn on one newer than it was tested with."""
37
+ site = project.environment(root)
38
+ version = project.installed(site, "crewai") if site else None
39
+ if version is None:
40
+ console.step(
41
+ "warning",
42
+ "crewai version not checked: no .venv found here; "
43
+ "run `alexein-cli doctor` once it is installed",
44
+ )
45
+ return
46
+ if project.older(version, CREWAI_MINIMUM):
47
+ tool = project.installer(root, []).name
48
+ raise Stop(
49
+ f"this project has crewai {version} (needs >={CREWAI_MINIMUM}) installed. Upgrade "
50
+ f"first - {tool} add 'crewai>={CREWAI_MINIMUM}' - then run init again. "
51
+ "Nothing changed."
52
+ )
53
+ if newer_than_tested(version):
54
+ console.step(
55
+ "warning",
56
+ f"crewai {version} is newer than this release was tested with ({CREWAI_TESTED}); "
57
+ "it should work - if tasks stop recalling or saving memory, "
58
+ "look for warnings on the `alexein` logger",
59
+ )
60
+
61
+
62
+ def newer_than_tested(version: str) -> bool:
63
+ """Whether `version` is a newer minor release of CrewAI than this one was tested with."""
64
+ return _minor(version) > _minor(CREWAI_TESTED)
65
+
66
+
67
+ def _minor(version: str) -> tuple[int, ...]:
68
+ return tuple(int(n) for n in version.split(".")[:2] if n.isdigit())
69
+
70
+
71
+ def next_steps(found: project.Crew, module: str) -> str:
72
+ """The lines that turn memory on, for this kind of crew."""
73
+ if found.kind == "json":
74
+ name = module.rsplit(".", 1)[-1]
75
+ wiring = [
76
+ " Wire it in, in crew.jsonc:",
77
+ "",
78
+ f' "memory": {{"python": "{name}.alexein_memory"}},',
79
+ f' "before_kickoff_callbacks": [{{"python": "{name}.whose"}}]',
80
+ ]
81
+ run = [
82
+ " from crewai.project.crew_loader import load_crew",
83
+ "",
84
+ ' crew, _ = load_crew("crew.jsonc")',
85
+ ' crew.kickoff(inputs={"user_id": "dana", ...})',
86
+ ]
87
+ else:
88
+ wiring = [
89
+ " Wire it in, in crew.py:",
90
+ "",
91
+ f" from {module} import alexein_memory, whose",
92
+ "",
93
+ " @CrewBase",
94
+ " class MyCrew:",
95
+ " memory = alexein_memory",
96
+ "",
97
+ " @before_kickoff",
98
+ " def whose_memory(self, inputs):",
99
+ " return whose(inputs)",
100
+ "",
101
+ " @crew",
102
+ " def crew(self) -> Crew:",
103
+ " return Crew(..., memory=self.memory)",
104
+ ]
105
+ run = [' MyCrew().crew().kickoff(inputs={"user_id": "dana", ...})']
106
+ return "\n".join(
107
+ [
108
+ *wiring,
109
+ "",
110
+ " Run with the app user's id; the model never chooses it:",
111
+ "",
112
+ *run,
113
+ "",
114
+ " Or, without CrewAI's memory: Agent(..., tools=alexein_memory.tools(user_id)),",
115
+ " and alexein_memory.save_result(user_id, output) after the run.",
116
+ "",
117
+ f" The key is {env.KEY} in .env; a plain script loads it itself.",
118
+ " `alexein-cli doctor` checks it all.",
119
+ ]
120
+ )