repocraft 0.4.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 (56) hide show
  1. repocraft/__init__.py +5 -0
  2. repocraft/__main__.py +5 -0
  3. repocraft/cli.py +284 -0
  4. repocraft/craft.py +178 -0
  5. repocraft/errors.py +27 -0
  6. repocraft/intent.py +167 -0
  7. repocraft/recipe.py +268 -0
  8. repocraft/recipes/factorial.py.j2 +22 -0
  9. repocraft/recipes/factorial.yaml +12 -0
  10. repocraft/recipes/fibonacci.py.j2 +22 -0
  11. repocraft/recipes/fibonacci.yaml +12 -0
  12. repocraft/recipes/fizzbuzz.py.j2 +29 -0
  13. repocraft/recipes/fizzbuzz.yaml +13 -0
  14. repocraft/recipes/pascal.py.j2 +25 -0
  15. repocraft/recipes/pascal.yaml +13 -0
  16. repocraft/recipes/password.py.j2 +24 -0
  17. repocraft/recipes/password.yaml +14 -0
  18. repocraft/recipes/prime_sieve.py.j2 +31 -0
  19. repocraft/recipes/prime_sieve.yaml +14 -0
  20. repocraft/recipes/test_factorial.py.j2 +23 -0
  21. repocraft/recipes/test_fibonacci.py.j2 +29 -0
  22. repocraft/recipes/test_fizzbuzz.py.j2 +46 -0
  23. repocraft/recipes/test_pascal.py.j2 +32 -0
  24. repocraft/recipes/test_password.py.j2 +29 -0
  25. repocraft/recipes/test_prime_sieve.py.j2 +30 -0
  26. repocraft/recipes/test_triangle.py.j2 +27 -0
  27. repocraft/recipes/triangle.py.j2 +21 -0
  28. repocraft/recipes/triangle.yaml +13 -0
  29. repocraft/render.py +126 -0
  30. repocraft/schema/recipe.schema.json +72 -0
  31. repocraft/schema/spec.schema.json +116 -0
  32. repocraft/spec.py +104 -0
  33. repocraft/templates/cli/cli.py.j2 +26 -0
  34. repocraft/templates/cli/main.py.j2 +5 -0
  35. repocraft/templates/cli/test_cli.py.j2 +36 -0
  36. repocraft/templates/common/CONTRIBUTING.md.j2 +28 -0
  37. repocraft/templates/common/README.md.j2 +53 -0
  38. repocraft/templates/common/SECURITY.md.j2 +22 -0
  39. repocraft/templates/common/check_junit.py +40 -0
  40. repocraft/templates/common/ci.yml.j2 +38 -0
  41. repocraft/templates/common/codeql.yml.j2 +26 -0
  42. repocraft/templates/common/dependabot.yml +12 -0
  43. repocraft/templates/common/gitignore.txt +12 -0
  44. repocraft/templates/common/init.py.j2 +8 -0
  45. repocraft/templates/common/py.typed +0 -0
  46. repocraft/templates/common/pyproject.toml.j2 +64 -0
  47. repocraft/templates/common/test_metadata.py.j2 +9 -0
  48. repocraft/templates/library/core.py.j2 +8 -0
  49. repocraft/templates/library/test_core.py.j2 +9 -0
  50. repocraft/templates/licenses/Apache-2.0.txt.j2 +202 -0
  51. repocraft/templates/licenses/MIT.txt.j2 +21 -0
  52. repocraft-0.4.0.dist-info/METADATA +311 -0
  53. repocraft-0.4.0.dist-info/RECORD +56 -0
  54. repocraft-0.4.0.dist-info/WHEEL +4 -0
  55. repocraft-0.4.0.dist-info/entry_points.txt +2 -0
  56. repocraft-0.4.0.dist-info/licenses/LICENSE +21 -0
repocraft/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Deterministic Python project scaffolding from a validated spec."""
2
+
3
+ __version__ = "0.4.0"
4
+
5
+ __all__ = ["__version__"]
repocraft/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Run repocraft with ``python -m repocraft``."""
2
+
3
+ from repocraft.cli import main
4
+
5
+ raise SystemExit(main())
repocraft/cli.py ADDED
@@ -0,0 +1,284 @@
1
+ """Command-line interface for repocraft."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from collections.abc import Mapping, Sequence
8
+ from pathlib import Path
9
+
10
+ from repocraft import __version__
11
+ from repocraft.craft import VerifiedCraft, request_craft, verify_craft
12
+ from repocraft.errors import CraftError, RecipeError, RepocraftError
13
+ from repocraft.intent import request_intent
14
+ from repocraft.recipe import (
15
+ GeneratedFile,
16
+ Recipe,
17
+ load_recipes,
18
+ render_recipe,
19
+ resolve_parameters,
20
+ select_recipe,
21
+ write_files,
22
+ )
23
+ from repocraft.render import render_project
24
+ from repocraft.spec import load_spec
25
+
26
+
27
+ def _build_parser() -> argparse.ArgumentParser:
28
+ parser = argparse.ArgumentParser(
29
+ prog="repocraft",
30
+ description="Render deterministic Python projects and snippets.",
31
+ )
32
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
33
+ commands = parser.add_subparsers(dest="command", required=True)
34
+
35
+ validate = commands.add_parser("validate", help="check a spec without writing files")
36
+ validate.add_argument("spec", type=Path, help="path to a YAML spec")
37
+
38
+ render = commands.add_parser("render", help="render a spec into a new directory")
39
+ render.add_argument("spec", type=Path, help="path to a YAML spec")
40
+ render.add_argument("output", type=Path, help="directory to create")
41
+ render.add_argument("--dry-run", action="store_true", help="list files without writing them")
42
+
43
+ make = commands.add_parser("make", help="generate a snippet from a short request")
44
+ make.add_argument("request", help='short request, for example "triangle"')
45
+ make.add_argument(
46
+ "-o",
47
+ "--output",
48
+ type=Path,
49
+ default=Path("."),
50
+ help="directory to write into (default: current directory)",
51
+ )
52
+ make.add_argument(
53
+ "--param",
54
+ action="append",
55
+ default=[],
56
+ metavar="NAME=VALUE",
57
+ help="override a recipe parameter; repeat for several parameters",
58
+ )
59
+ make.add_argument(
60
+ "-y", "--yes", action="store_true", help="write without asking for confirmation"
61
+ )
62
+ make.add_argument("--dry-run", action="store_true", help="list files without writing them")
63
+
64
+ commands.add_parser("recipes", help="list the built-in snippet recipes")
65
+
66
+ ask = commands.add_parser(
67
+ "ask", help="turn a free-form request into a snippet with AI"
68
+ )
69
+ ask.add_argument("request", help="free-form request, for example 'a tall triangle'")
70
+ ask.add_argument(
71
+ "-o",
72
+ "--output",
73
+ type=Path,
74
+ default=Path("."),
75
+ help="directory to write into (default: current directory)",
76
+ )
77
+ ask.add_argument(
78
+ "--param",
79
+ action="append",
80
+ default=[],
81
+ metavar="NAME=VALUE",
82
+ help="override an intent parameter; repeat for several parameters",
83
+ )
84
+ ask.add_argument(
85
+ "-y", "--yes", action="store_true", help="write without asking for confirmation"
86
+ )
87
+ ask.add_argument(
88
+ "--dry-run", action="store_true", help="list files without writing them"
89
+ )
90
+ ask.add_argument(
91
+ "--endpoint",
92
+ default=None,
93
+ help="OpenAI-compatible base URL (default: OPENAI_BASE_URL env or the public API)",
94
+ )
95
+ ask.add_argument(
96
+ "--model",
97
+ default=None,
98
+ help="model name (default: REPOCRAFT_MODEL env or gpt-4o-mini)",
99
+ )
100
+
101
+ craft = commands.add_parser(
102
+ "craft",
103
+ help="generate a free-form snippet with AI and verify it before writing",
104
+ )
105
+ craft.add_argument("request", help="what to generate, for example 'binary search'")
106
+ craft.add_argument(
107
+ "-o",
108
+ "--output",
109
+ type=Path,
110
+ default=Path("."),
111
+ help="directory to write into (default: current directory)",
112
+ )
113
+ craft.add_argument(
114
+ "-y", "--yes", action="store_true", help="write without asking for confirmation"
115
+ )
116
+ craft.add_argument(
117
+ "--dry-run", action="store_true", help="list files without writing them"
118
+ )
119
+ craft.add_argument(
120
+ "--endpoint",
121
+ default=None,
122
+ help="OpenAI-compatible base URL (default: OPENAI_BASE_URL env or the public API)",
123
+ )
124
+ craft.add_argument(
125
+ "--model",
126
+ default=None,
127
+ help="model name (default: REPOCRAFT_MODEL env or gpt-4o-mini)",
128
+ )
129
+ return parser
130
+
131
+
132
+ def main(argv: Sequence[str] | None = None) -> int:
133
+ """Run the CLI and return its exit status."""
134
+ args = _build_parser().parse_args(argv)
135
+ try:
136
+ if args.command == "validate":
137
+ return _validate(args)
138
+ if args.command == "render":
139
+ return _render(args)
140
+ if args.command == "recipes":
141
+ return _list_recipes()
142
+ if args.command == "ask":
143
+ return _ask(args)
144
+ if args.command == "craft":
145
+ return _craft(args)
146
+ return _make(args)
147
+ except RepocraftError as error:
148
+ print(f"error: {error}", file=sys.stderr)
149
+ return 1
150
+
151
+
152
+ def _validate(args: argparse.Namespace) -> int:
153
+ spec = load_spec(args.spec)
154
+ project = spec["project"]
155
+ print(f"valid spec: {project['name']} ({project['type']})")
156
+ return 0
157
+
158
+
159
+ def _render(args: argparse.Namespace) -> int:
160
+ spec = load_spec(args.spec)
161
+ written = render_project(spec, args.output, dry_run=args.dry_run)
162
+ if args.dry_run:
163
+ for path in written:
164
+ print(path)
165
+ else:
166
+ print(f"wrote {len(written)} files to {args.output}")
167
+ return 0
168
+
169
+
170
+ def _list_recipes() -> int:
171
+ for recipe in load_recipes():
172
+ print(f"{recipe.id} {recipe.version}: {recipe.description}")
173
+ return 0
174
+
175
+
176
+ def _make(args: argparse.Namespace) -> int:
177
+ recipe = select_recipe(args.request, load_recipes())
178
+ parameters = resolve_parameters(recipe, _parse_overrides(args.param))
179
+ return _write_snippet(recipe, parameters, args)
180
+
181
+
182
+ def _ask(args: argparse.Namespace) -> int:
183
+ intent = request_intent(
184
+ args.request, load_recipes(), base_url=args.endpoint, model=args.model
185
+ )
186
+ proposed = {name: str(value) for name, value in intent.parameters.items()}
187
+ parameters = resolve_parameters(
188
+ intent.recipe, proposed | _parse_overrides(args.param)
189
+ )
190
+ return _write_snippet(intent.recipe, parameters, args)
191
+
192
+
193
+ def _write_snippet(
194
+ recipe: Recipe, parameters: Mapping[str, int], args: argparse.Namespace
195
+ ) -> int:
196
+ files = render_recipe(recipe, parameters)
197
+ output = Path(args.output)
198
+ if not args.dry_run and not args.yes:
199
+ _confirm(recipe, parameters, files, output)
200
+ written = write_files(files, output, dry_run=args.dry_run)
201
+ if args.dry_run:
202
+ for path in written:
203
+ print(path)
204
+ else:
205
+ for path in written:
206
+ print(f"wrote {path}")
207
+ return 0
208
+
209
+
210
+ def _craft(args: argparse.Namespace) -> int:
211
+ verified = verify_craft(
212
+ request_craft(args.request, base_url=args.endpoint, model=args.model)
213
+ )
214
+ result = verified.result
215
+ files = (
216
+ GeneratedFile(name=f"{result.name}.py", content=result.code),
217
+ GeneratedFile(name=f"test_{result.name}.py", content=result.test),
218
+ )
219
+ output = Path(args.output)
220
+ if not args.dry_run and not args.yes:
221
+ _confirm_craft(verified, files, output)
222
+ written = write_files(files, output, dry_run=args.dry_run)
223
+ if args.dry_run:
224
+ for path in written:
225
+ print(path)
226
+ else:
227
+ for path in written:
228
+ print(f"wrote {path}")
229
+ return 0
230
+
231
+
232
+ def _confirm_craft(
233
+ verified: VerifiedCraft,
234
+ files: Sequence[GeneratedFile],
235
+ output: Path,
236
+ ) -> None:
237
+ print("checks passed: " + ", ".join(verified.checks))
238
+ for file in files:
239
+ print(f"file: {output / file.name}")
240
+ print(file.content.rstrip())
241
+ print("write these files? [y/N] ", end="", flush=True)
242
+ try:
243
+ answer = input()
244
+ except (EOFError, OSError) as error:
245
+ raise CraftError(
246
+ "confirmation required; rerun with --yes to write without prompting"
247
+ ) from error
248
+ if answer.strip().casefold() not in {"y", "yes"}:
249
+ raise CraftError("aborted; no files were written")
250
+
251
+
252
+ def _parse_overrides(pairs: Sequence[str]) -> dict[str, str]:
253
+ overrides: dict[str, str] = {}
254
+ for pair in pairs:
255
+ name, separator, value = pair.partition("=")
256
+ name = name.strip()
257
+ if not separator or not name:
258
+ raise RecipeError(f"invalid --param {pair!r}; expected NAME=VALUE")
259
+ if name in overrides:
260
+ raise RecipeError(f"--param {name!r} was given more than once")
261
+ overrides[name] = value.strip()
262
+ return overrides
263
+
264
+
265
+ def _confirm(
266
+ recipe: Recipe,
267
+ parameters: Mapping[str, int],
268
+ files: Sequence[GeneratedFile],
269
+ output: Path,
270
+ ) -> None:
271
+ print(f"recipe: {recipe.id} {recipe.version}")
272
+ print(f"description: {recipe.description}")
273
+ print("parameters: " + ", ".join(f"{name}={value}" for name, value in parameters.items()))
274
+ for file in files:
275
+ print(f"file: {output / file.name}")
276
+ print("write these files? [y/N] ", end="", flush=True)
277
+ try:
278
+ answer = input()
279
+ except (EOFError, OSError) as error:
280
+ raise RecipeError(
281
+ "confirmation required; rerun with --yes to write without prompting"
282
+ ) from error
283
+ if answer.strip().casefold() not in {"y", "yes"}:
284
+ raise RecipeError("aborted; no files were written")
repocraft/craft.py ADDED
@@ -0,0 +1,178 @@
1
+ """Free-form snippets where a model writes the code and repocraft verifies it.
2
+
3
+ The model proposes a module, its code, and a unittest file as JSON. repocraft
4
+ then runs deterministic gates on the proposal: python syntax, a check that the
5
+ tests import the module, ruff when it is installed, and the generated tests
6
+ themselves. Nothing is written until every gate passes and the user confirms.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import importlib.util
13
+ import keyword
14
+ import os
15
+ import re
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+
22
+ from repocraft.errors import CraftError, IntentError
23
+ from repocraft.intent import (
24
+ DEFAULT_BASE_URL,
25
+ DEFAULT_MODEL,
26
+ chat_content,
27
+ chat_url,
28
+ parse_intent,
29
+ post_chat,
30
+ )
31
+
32
+ _NAME = re.compile(r"^[a-z][a-z0-9_]{0,49}$")
33
+ _RAN_TESTS = re.compile(r"Ran (\d+) tests?")
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class CraftResult:
38
+ """The unverified model proposal: a module name, its code, and its test."""
39
+
40
+ name: str
41
+ code: str
42
+ test: str
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class VerifiedCraft:
47
+ """A proposal that passed every deterministic gate."""
48
+
49
+ result: CraftResult
50
+ checks: tuple[str, ...]
51
+
52
+
53
+ def craft_prompt() -> str:
54
+ """Describe the strict reply format for free-form snippet generation."""
55
+ return (
56
+ "You write single-file Python 3 snippets on request.\n"
57
+ 'Reply with JSON only: {"name": "<snake_case module name>",'
58
+ ' "code": "<module source>", "test": "<unittest source>"}.\n'
59
+ "The code must be self-contained, use only the standard library,"
60
+ " and carry type hints and docstrings.\n"
61
+ "The test must import the module by its name, use unittest, and"
62
+ " contain at least one meaningful test."
63
+ )
64
+
65
+
66
+ def parse_craft(content: str) -> CraftResult:
67
+ """Parse and shape-check the model reply; deeper checks happen in verify."""
68
+ try:
69
+ data = parse_intent(content)
70
+ except IntentError as error:
71
+ raise CraftError(str(error)) from error
72
+ name = data.get("name")
73
+ code = data.get("code")
74
+ test = data.get("test")
75
+ if (
76
+ not isinstance(name, str)
77
+ or not _NAME.fullmatch(name)
78
+ or keyword.iskeyword(name)
79
+ ):
80
+ raise CraftError("the craft name must be a lowercase snake_case identifier")
81
+ if (
82
+ not isinstance(code, str)
83
+ or not isinstance(test, str)
84
+ or not code.strip()
85
+ or not test.strip()
86
+ ):
87
+ raise CraftError("the craft reply must include non-empty code and test strings")
88
+ return CraftResult(name=name, code=code, test=test)
89
+
90
+
91
+ def request_craft(
92
+ request: str,
93
+ *,
94
+ api_key: str | None = None,
95
+ base_url: str | None = None,
96
+ model: str | None = None,
97
+ ) -> CraftResult:
98
+ """Ask the model for a snippet proposal."""
99
+ key = api_key or os.environ.get("OPENAI_API_KEY")
100
+ if not key:
101
+ raise CraftError("OPENAI_API_KEY is not set; the craft command needs it")
102
+ url = chat_url(base_url or os.environ.get("OPENAI_BASE_URL") or DEFAULT_BASE_URL)
103
+ chosen_model = model or os.environ.get("REPOCRAFT_MODEL") or DEFAULT_MODEL
104
+ messages = [
105
+ {"role": "system", "content": craft_prompt()},
106
+ {"role": "user", "content": request},
107
+ ]
108
+ try:
109
+ payload = post_chat(url=url, api_key=key, model=chosen_model, messages=messages)
110
+ content = chat_content(payload)
111
+ except IntentError as error:
112
+ raise CraftError(str(error)) from error
113
+ return parse_craft(content)
114
+
115
+
116
+ def verify_craft(
117
+ result: CraftResult, *, run_ruff: bool = True
118
+ ) -> VerifiedCraft:
119
+ """Run every deterministic gate on the proposal and report what passed."""
120
+ checks: list[str] = []
121
+ try:
122
+ ast.parse(result.code)
123
+ test_tree = ast.parse(result.test)
124
+ except SyntaxError as error:
125
+ raise CraftError(f"the generated code has a syntax error: {error}") from error
126
+ checks.append("python syntax")
127
+ imported = {
128
+ alias.name.split(".")[0]
129
+ for node in ast.walk(test_tree)
130
+ if isinstance(node, ast.Import)
131
+ for alias in node.names
132
+ }
133
+ imported |= {
134
+ (node.module or "").split(".")[0]
135
+ for node in ast.walk(test_tree)
136
+ if isinstance(node, ast.ImportFrom)
137
+ }
138
+ if result.name not in imported:
139
+ raise CraftError(f"the generated test must import the module {result.name!r}")
140
+ checks.append("test imports the module")
141
+ with tempfile.TemporaryDirectory() as temporary:
142
+ directory = Path(temporary)
143
+ (directory / f"{result.name}.py").write_text(
144
+ result.code, encoding="utf-8", newline="\n"
145
+ )
146
+ (directory / f"test_{result.name}.py").write_text(
147
+ result.test, encoding="utf-8", newline="\n"
148
+ )
149
+ if run_ruff and _ruff_available():
150
+ lint = subprocess.run(
151
+ [sys.executable, "-m", "ruff", "check", str(directory)],
152
+ capture_output=True,
153
+ text=True,
154
+ check=False,
155
+ )
156
+ if lint.returncode != 0:
157
+ detail = (lint.stdout + lint.stderr).strip()[:400]
158
+ raise CraftError(f"ruff rejected the generated code: {detail}")
159
+ checks.append("ruff")
160
+ completed = subprocess.run(
161
+ [sys.executable, f"test_{result.name}.py"],
162
+ cwd=directory,
163
+ capture_output=True,
164
+ text=True,
165
+ check=False,
166
+ )
167
+ summary = completed.stdout + completed.stderr
168
+ ran = _RAN_TESTS.search(summary)
169
+ if ran is None or int(ran.group(1)) < 1:
170
+ raise CraftError("the generated test file contains no tests")
171
+ if completed.returncode != 0:
172
+ raise CraftError(f"the generated tests failed:\n{summary.strip()[:400]}")
173
+ checks.append("unit tests pass")
174
+ return VerifiedCraft(result=result, checks=tuple(checks))
175
+
176
+
177
+ def _ruff_available() -> bool:
178
+ return importlib.util.find_spec("ruff") is not None
repocraft/errors.py ADDED
@@ -0,0 +1,27 @@
1
+ """Expected, user-facing failures."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class RepocraftError(Exception):
7
+ """A failure the CLI reports as an error instead of a traceback."""
8
+
9
+
10
+ class SpecError(RepocraftError):
11
+ """The spec is unreadable, invalid, or contradicts itself."""
12
+
13
+
14
+ class RenderError(RepocraftError):
15
+ """The output directory cannot be used, or rendering failed."""
16
+
17
+
18
+ class RecipeError(RepocraftError):
19
+ """A recipe is invalid, or a request cannot be matched unambiguously."""
20
+
21
+
22
+ class IntentError(RepocraftError):
23
+ """The AI intent layer is unusable, or returned an unusable intent."""
24
+
25
+
26
+ class CraftError(RepocraftError):
27
+ """The AI craft layer is unusable, or its output failed verification."""
repocraft/intent.py ADDED
@@ -0,0 +1,167 @@
1
+ """Turn a free-form request into a validated recipe intent with an AI helper.
2
+
3
+ The model only proposes a ``{recipe, parameters}`` intent as JSON; it never
4
+ writes code or files. The proposal is validated against the recipe catalog
5
+ with the same rules as ``repocraft make``, so the deterministic core and its
6
+ guarantees are unchanged.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import re
14
+ import urllib.error
15
+ import urllib.request
16
+ from collections.abc import Sequence
17
+ from dataclasses import dataclass
18
+ from typing import Any
19
+
20
+ from repocraft.errors import IntentError
21
+ from repocraft.recipe import Recipe, resolve_parameters
22
+
23
+ DEFAULT_BASE_URL = "https://api.openai.com/v1"
24
+ DEFAULT_MODEL = "gpt-4o-mini"
25
+ _TIMEOUT_SECONDS = 60
26
+
27
+ _JSON_OBJECT = re.compile(r"\{.*\}", re.DOTALL)
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Intent:
32
+ """A validated intent: one recipe and its resolved parameters."""
33
+
34
+ recipe: Recipe
35
+ parameters: dict[str, int]
36
+
37
+
38
+ def system_prompt(recipes: Sequence[Recipe]) -> str:
39
+ """Describe the catalog and the strict reply format; deterministic."""
40
+ lines = [
41
+ "You translate free-form snippet requests into a strict JSON intent.",
42
+ "Available recipes:",
43
+ ]
44
+ for recipe in recipes:
45
+ parameters = ", ".join(
46
+ f"{parameter.name} (integer, {parameter.minimum}..{parameter.maximum},"
47
+ f" default {parameter.default})"
48
+ for parameter in recipe.parameters
49
+ )
50
+ lines.append(
51
+ f"- id: {recipe.id} | description: {recipe.description}"
52
+ f" | parameters: {parameters}"
53
+ )
54
+ lines.append(
55
+ 'Reply with JSON only: {"recipe": "<id>", "parameters": {"<name>": <integer>}}.'
56
+ " Use the parameter defaults unless the request clearly states other values"
57
+ ' inside the allowed range. If no single recipe fits, reply'
58
+ ' {"recipe": null, "reason": "<short explanation>"}.'
59
+ )
60
+ return "\n".join(lines)
61
+
62
+
63
+ def chat_url(base_url: str) -> str:
64
+ """Return the chat completions URL for an OpenAI-compatible base URL."""
65
+ if base_url.endswith("/chat/completions"):
66
+ return base_url
67
+ return base_url.rstrip("/") + "/chat/completions"
68
+
69
+
70
+ def parse_intent(content: str) -> dict[str, Any]:
71
+ """Parse the model reply as a JSON object, tolerating markdown fences."""
72
+ try:
73
+ data = json.loads(content)
74
+ except json.JSONDecodeError:
75
+ match = _JSON_OBJECT.search(content)
76
+ if match is None:
77
+ raise IntentError("the model reply contains no JSON") from None
78
+ try:
79
+ data = json.loads(match.group(0))
80
+ except json.JSONDecodeError as error:
81
+ raise IntentError(f"the model reply is not valid JSON: {error}") from error
82
+ if not isinstance(data, dict):
83
+ raise IntentError("the model reply must be a JSON object")
84
+ return data
85
+
86
+
87
+ def request_intent(
88
+ request: str,
89
+ recipes: Sequence[Recipe],
90
+ *,
91
+ api_key: str | None = None,
92
+ base_url: str | None = None,
93
+ model: str | None = None,
94
+ ) -> Intent:
95
+ """Ask the model for an intent and validate it against the catalog."""
96
+ key = api_key or os.environ.get("OPENAI_API_KEY")
97
+ if not key:
98
+ raise IntentError("OPENAI_API_KEY is not set; the ask command needs it")
99
+ url = chat_url(base_url or os.environ.get("OPENAI_BASE_URL") or DEFAULT_BASE_URL)
100
+ chosen_model = model or os.environ.get("REPOCRAFT_MODEL") or DEFAULT_MODEL
101
+ messages = [
102
+ {"role": "system", "content": system_prompt(recipes)},
103
+ {"role": "user", "content": request},
104
+ ]
105
+ payload = post_chat(url=url, api_key=key, model=chosen_model, messages=messages)
106
+ return _validate_intent(parse_intent(chat_content(payload)), recipes)
107
+
108
+
109
+ def post_chat(
110
+ *, url: str, api_key: str, model: str, messages: list[dict[str, str]]
111
+ ) -> Any:
112
+ """POST a chat completion request and return the decoded JSON payload."""
113
+ body = json.dumps(
114
+ {"model": model, "temperature": 0, "messages": messages}
115
+ ).encode("utf-8")
116
+ http_request = urllib.request.Request(
117
+ url,
118
+ data=body,
119
+ headers={
120
+ "Authorization": f"Bearer {api_key}",
121
+ "Content-Type": "application/json",
122
+ },
123
+ method="POST",
124
+ )
125
+ try:
126
+ with urllib.request.urlopen(http_request, timeout=_TIMEOUT_SECONDS) as response:
127
+ return json.loads(response.read().decode("utf-8"))
128
+ except urllib.error.HTTPError as error:
129
+ detail = error.read().decode("utf-8", "replace")[:200]
130
+ raise IntentError(f"the endpoint returned HTTP {error.code}: {detail}") from error
131
+ except (urllib.error.URLError, TimeoutError) as error:
132
+ raise IntentError(f"cannot reach the endpoint: {error}") from error
133
+ except json.JSONDecodeError as error:
134
+ raise IntentError(f"the endpoint returned invalid JSON: {error}") from error
135
+
136
+
137
+ def chat_content(payload: Any) -> str:
138
+ """Return the text content of a chat completion response payload."""
139
+ try:
140
+ content = payload["choices"][0]["message"]["content"]
141
+ except (KeyError, IndexError, TypeError) as error:
142
+ raise IntentError("unexpected response shape from the endpoint") from error
143
+ if not isinstance(content, str):
144
+ raise IntentError("the endpoint returned no text content")
145
+ return content
146
+
147
+
148
+ def _validate_intent(data: dict[str, Any], recipes: Sequence[Recipe]) -> Intent:
149
+ recipe_id = data.get("recipe")
150
+ if recipe_id is None:
151
+ reason = data.get("reason")
152
+ explanation = reason if isinstance(reason, str) and reason else "no reason given"
153
+ raise IntentError(f"the model rejected the request: {explanation}")
154
+ if not isinstance(recipe_id, str):
155
+ raise IntentError("the intent recipe must be a string or null")
156
+ recipe = next((entry for entry in recipes if entry.id == recipe_id), None)
157
+ if recipe is None:
158
+ raise IntentError(f"the model chose unknown recipe {recipe_id!r}")
159
+ raw_parameters = data.get("parameters", {})
160
+ if not isinstance(raw_parameters, dict):
161
+ raise IntentError("the intent parameters must be a mapping")
162
+ overrides: dict[str, str] = {}
163
+ for name, value in raw_parameters.items():
164
+ if isinstance(value, bool) or not isinstance(value, int):
165
+ raise IntentError("the intent parameters must map names to integers")
166
+ overrides[name] = str(value)
167
+ return Intent(recipe=recipe, parameters=resolve_parameters(recipe, overrides))