open-prompt-format 0.2.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.
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: open-prompt-format
3
+ Version: 0.2.0
4
+ Summary: Load and render Open Prompt Format files
5
+ License: MIT License
6
+
7
+ Copyright (c) 2026 Open Prompt Format contributors
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+
27
+ Project-URL: Repository, https://github.com/stovo-team/open-prompt-format
28
+ Keywords: prompt,llm,prompt-format,prompt-management
29
+ Classifier: Development Status :: 3 - Alpha
30
+ Classifier: Intended Audience :: Developers
31
+ Classifier: License :: OSI Approved :: MIT License
32
+ Classifier: Programming Language :: Python :: 3
33
+ Classifier: Programming Language :: Python :: 3.10
34
+ Classifier: Programming Language :: Python :: 3.11
35
+ Classifier: Programming Language :: Python :: 3.12
36
+ Classifier: Programming Language :: Python :: 3.13
37
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
38
+ Requires-Python: >=3.10
39
+ Description-Content-Type: text/markdown
40
+ License-File: LICENSE
41
+ Requires-Dist: PyYAML>=6.0
42
+ Provides-Extra: jinja
43
+ Requires-Dist: Jinja2>=3.1; extra == "jinja"
44
+ Dynamic: license-file
45
+
46
+ # Open Prompt Format for Python
47
+
48
+ Load and render [OPF](../../README.md) prompt files from Python.
49
+
50
+ ## Install
51
+
52
+ ```sh
53
+ python -m pip install open-prompt-format
54
+ ```
55
+
56
+ For the current source checkout, run `python -m pip install ./packages/python` from the repository root.
57
+
58
+ ## Use
59
+
60
+ ```python
61
+ from opf import load_by_id
62
+
63
+ prompt = load_by_id("support.reply", "prompts")
64
+ messages = prompt.render(customer_message="My order is late.")
65
+ print(prompt.source_digest)
66
+ ```
67
+
68
+ `messages` is an ordered list of dictionaries with `role` and `content` strings. See the [syntax proposal](../../spec/SYNTAX.md) for file structure and validation rules.
69
+
70
+ ## CLI
71
+
72
+ ```sh
73
+ opf validate prompts/support.reply.md
74
+ opf validate-collection prompts
75
+ opf render prompts/support.reply.md --input customer_message="My order is late."
76
+ opf scan .
77
+ opf migrate inspect prompts/legacy.md --role system
78
+ opf migrate apply prompts/legacy.md --role system
79
+ ```
80
+
81
+ Migration inspection is read-only. Apply writes only generated paths that are absent or already identical. Supported adapter inputs are intentionally narrow; consult the [migration guide](../../examples/migration/README.md) for limits and compatibility findings.
82
+
83
+ Licensed under MIT; see [LICENSE](LICENSE).
84
+
85
+ ## Git-backed registry
86
+
87
+ ```python
88
+ from opf import Registry
89
+
90
+ registry = Registry.local("opf.yaml")
91
+ prepared = registry.get("support.reply", channel="production").render({"customer_message": "Hello"})
92
+ print(prepared.messages)
93
+ print(prepared.receipt)
94
+ ```
95
+
96
+ The registry also supports `release`, `promote`, `verify`, `verify-all`, and `export` through the `opf` CLI. Run `opf verify-all --registry opf.yaml` in CI after fetching Git tags. `Registry.from_bundle("prompt.json")` loads an exported release without Git. Existing Markdown/Jinja projects can use the `jinja2` renderer with `pip install 'open-prompt-format[jinja]'`. The model is selected by the application and can be attached with `prepared.call_receipt(provider=..., model=...)`. See the [registry contract](../../spec/REGISTRY.md).
97
+
98
+ After `opf publish ID@VERSION --to langfuse`, `Registry.langfuse().get(ID, version=VERSION)` explicitly loads the verified remote bundle using Langfuse credentials from the environment.
99
+
100
+
101
+ ## CLI onboarding and review
102
+
103
+ The Python distribution includes the `opf` CLI. `opf init . --id support.reply` creates a sample prompt, registry entry, and an OPF-owned guidance block in `AGENTS.md`. Add `--github` to also create a read-only GitHub Actions workflow that calls the published reusable OPF check workflow. It does not replace existing prompt files or content outside its markers; any conflicting target causes init to stop without partial writes. The generated workflow requires the matching OPF GitHub release and Python package to be published. `opf check .` validates discovered OPF prompts and registry references locally; `--format json` and `--strict` are available for CI.
104
+
105
+ Use `opf diff ID --base VERSION_OR_CHANNEL --target VERSION_OR_WORKING_TREE` to inspect source changes and shared prefix evidence. A stable prefix is only a cacheability candidate; it cannot establish a provider cache hit. Heuristic injection findings need human review and do not guarantee safety.
106
+
107
+ The reusable GitHub workflow has an optional paired Promptfoo job (`run-eval`, default false). It requires a protected `prompt-eval` environment with required reviewers and environment-scoped provider keys. It runs the same eval config against the PR base prompt and candidate prompt, writes a sanitized comparison to the workflow summary, skips forks, and deletes raw files. Each comparison makes two sets of provider calls and can cost money. `block-on-regression` also defaults false; ungraded rows are never counted as passes. Report states are `unchanged`, `regression`, `improved`, `changed`, `error`, and `ungraded`; provider/test/prompt matrix mismatches or missing base files abort comparison. Nondeterminism means a measured regression needs review, and a source diff by itself does not establish behavior quality. The included sample cases validate config wiring only; live model behavior is not verified by ordinary CI.
@@ -0,0 +1,27 @@
1
+ open_prompt_format-0.2.0.dist-info/licenses/LICENSE,sha256=T98G_qfsZ_MjpQUn7ZgUX4xotDpqoe2NqPogBIM7u4M,1088
2
+ opf/__init__.py,sha256=3Xaxf1sbxeiOt1VfUQIAzfBVObNhgUf8s_kffjZHXBQ,521
3
+ opf/check.py,sha256=o1NDG6eMyQue9JwoqhKKg_uboP5UjmJyB26NATrPp1U,4597
4
+ opf/cli.py,sha256=0efL3mQAh5AeihlbVhuFnFGaHKc0BWkwXUsPpuZU_yQ,16255
5
+ opf/compatibility.py,sha256=6mJFJfy5I1zAAObnO-mn0dvsECE6fV821xKpvlA9Dj8,1146
6
+ opf/core.py,sha256=as975a2I5xNYGvgV5I9TKSR6aa5CAnITBbXk552DCvo,18030
7
+ opf/diff.py,sha256=F5AZ2FLKGj1uMtUBOcK8r5GEYVVHySP3lu0NnzXEu7c,4734
8
+ opf/discovery.py,sha256=jqBsejUXQshFl2Z5lBxgYYu9rRNheay31wmIne2G1hQ,8170
9
+ opf/init.py,sha256=OJYXIx5AVefTgL4lgWPSL2nQ-3yIeyY0NudZCe26q5I,6799
10
+ opf/migrate.py,sha256=sk9WA3ZIt_tzD2tpTTi73XVmOclH75ig2CfDQbtd9dU,8245
11
+ opf/publish.py,sha256=FUG9BOWXS7iCbIr8TZp_jjw_nd17jO4DGRgOlzfCyXw,9590
12
+ opf/registry.py,sha256=oWMgflP5P2Ip8FuAz5f2i1Yh2rkqlCT3H3zt4Rwdi6M,27818
13
+ opf/safety.py,sha256=VU1L6hh_IEGaWlFRvVkbjn-6ihc8hPbCsvdL9KEt4_w,2366
14
+ opf/adapters/__init__.py,sha256=DXfVEEQkgiBfXcQF_G9s9S8TipxzMBaJqqWX5YmS0VM,427
15
+ opf/adapters/autogen.py,sha256=7NnHwBxFz8haLarj0FBFJl-jCPJy8C-DQEC45IqlevU,2527
16
+ opf/adapters/base.py,sha256=jBwLhClwaKZOmoDr8eNYmHcAKB5hgn5dG3ErZOKlMTE,3469
17
+ opf/adapters/common.py,sha256=VFCMfIAgGkSHbQSodetvZkSyTiGZz2rhH_TEEg9cMd8,3047
18
+ opf/adapters/crewai.py,sha256=05FsaO1bStJ5vwkTUF6ct1GqyoCC2J8AqiVgHtzKI0Y,3544
19
+ opf/adapters/jinja.py,sha256=vZ-g9p-tQuNWBrJvNKFkEDI1R39Mfi-VMWR7eJcUbOo,6132
20
+ opf/adapters/langchain.py,sha256=sQRFRAi3bVz_e79Fhl6M_fjRm_9bSuDXhVI6OtiJ11Q,4347
21
+ opf/adapters/markdown.py,sha256=KbgYdj8XsNACPv0eS5rEKBXl2bD6gNzC9m4qaH2AI-Q,5393
22
+ opf/adapters/openai.py,sha256=wumTQ12ahRIUjAOSy1SWuKmv6Pt3VVT3mOmPXpd75CI,5638
23
+ open_prompt_format-0.2.0.dist-info/METADATA,sha256=m3oKUHzN0CX9H431WsN_MJ-S7-dOg3OlIbl6onjVKCY,6300
24
+ open_prompt_format-0.2.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
25
+ open_prompt_format-0.2.0.dist-info/entry_points.txt,sha256=wyYPFI7wyWm2n3vwl_hAwcS29Ok-7zdCQDGjkmpJI_c,37
26
+ open_prompt_format-0.2.0.dist-info/top_level.txt,sha256=HtakgkwCPwYEzbSr5n-MefOkNx5jFr8wLTNBNwPwiXk,4
27
+ open_prompt_format-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ opf = opf.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Open Prompt Format contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ opf
opf/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Minimal reader and renderer for OPF 0.1 prompt files."""
2
+
3
+ from .core import OPFError, Prompt, load, load_by_id, load_collection, parse
4
+ from .compatibility import CompatibilityFinding, CompatibilityReport
5
+ from .discovery import PromptFinding, scan
6
+ from .registry import PreparedPrompt, RegisteredPrompt, Registry
7
+
8
+ __all__ = ["OPFError", "Prompt", "PreparedPrompt", "RegisteredPrompt", "Registry", "CompatibilityFinding", "CompatibilityReport", "PromptFinding", "load", "load_by_id", "load_collection", "parse", "scan"]
@@ -0,0 +1,10 @@
1
+ """Optional source import adapters. Framework packages are not imported here."""
2
+
3
+ from .autogen import AutoGenAdapter
4
+ from .crewai import CrewAIAdapter
5
+ from .jinja import JinjaAdapter
6
+ from .langchain import LangChainAdapter
7
+ from .markdown import MarkdownAdapter
8
+ from .openai import OpenAIPromptAdapter
9
+
10
+ __all__ = ["AutoGenAdapter", "CrewAIAdapter", "JinjaAdapter", "LangChainAdapter", "MarkdownAdapter", "OpenAIPromptAdapter"]
@@ -0,0 +1,53 @@
1
+ """Extract only literal system_message values from AutoGen Python source."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from pathlib import Path
7
+
8
+ from ..compatibility import CompatibilityFinding
9
+ from ..core import OPFError
10
+ from .base import SourcePrompt, read_source
11
+ from .common import plan_messages
12
+ from .markdown import ID_RE
13
+
14
+
15
+ class AutoGenAdapter:
16
+ source_kind = "autogen-python"
17
+ converter = "opf-migrate-autogen"
18
+
19
+ def inspect(self, path: str | Path, *, root: str | Path = ".") -> SourcePrompt:
20
+ source = read_source(path, root, self.source_kind)
21
+ try:
22
+ ast.parse(source.text, filename=source.relative_path)
23
+ except SyntaxError as exc:
24
+ raise OPFError("AutoGen source is not valid Python: {}".format(exc)) from exc
25
+ return SourcePrompt(source.path, source.relative_path, source.source_kind, source.text, source.source_digest, "python-ast-static/1")
26
+
27
+ def plan(self, source: SourcePrompt, prompt_id: str, *, role: str | None = None):
28
+ if not ID_RE.fullmatch(prompt_id):
29
+ raise OPFError("invalid prompt id")
30
+ tree = ast.parse(source.text)
31
+ candidates: list[str] = []
32
+ for node in ast.walk(tree):
33
+ if not isinstance(node, ast.Call):
34
+ continue
35
+ for keyword in node.keywords:
36
+ if keyword.arg != "system_message":
37
+ continue
38
+ try:
39
+ value = ast.literal_eval(keyword.value)
40
+ except (ValueError, TypeError):
41
+ raise OPFError("dynamic AutoGen system_message requires manual migration")
42
+ if not isinstance(value, str):
43
+ raise OPFError("AutoGen system_message must be a string literal")
44
+ candidates.append(value)
45
+ if len(candidates) != 1:
46
+ raise OPFError("expected exactly one explicit system_message; found {}".format(len(candidates)))
47
+ findings = [CompatibilityFinding("autogen.runtime.excluded", "warning", "dropped", "AutoGen tools, agent runtime, and control flow are not part of this migration")]
48
+ return plan_messages(source, prompt_id, [{"role": "system", "content": candidates[0]}], converter=self.converter, source_format_version=source.source_format_version, findings=findings)
49
+
50
+ def convert(self, source: SourcePrompt, plan):
51
+ if source.source_digest != plan.source.source_digest:
52
+ raise OPFError("source changed after migration plan was created")
53
+ return plan.output
opf/adapters/base.py ADDED
@@ -0,0 +1,98 @@
1
+ """Common types and interfaces for prompt import adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from abc import ABC, abstractmethod
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any, Mapping, Optional
10
+
11
+ from ..compatibility import CompatibilityReport
12
+ from ..core import OPFError
13
+
14
+
15
+ def normalized_digest(source: str) -> str:
16
+ normalized = source.replace("\r\n", "\n").replace("\r", "\n")
17
+ return "sha256:" + hashlib.sha256(normalized.encode("utf-8")).hexdigest()
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class SourcePrompt:
22
+ path: Path
23
+ relative_path: str
24
+ source_kind: str
25
+ text: str
26
+ source_digest: str
27
+ source_format_version: Optional[str] = None
28
+ data: Mapping[str, Any] | None = None
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class MigrationOutput:
33
+ files: Mapping[str, str]
34
+ registry_entry: Mapping[str, Any] | None
35
+ manifest_record: Mapping[str, Any]
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class MigrationPlan:
40
+ prompt_id: str
41
+ source: SourcePrompt
42
+ output: MigrationOutput
43
+ compatibility: CompatibilityReport
44
+ converter: str
45
+ converter_version: str = "0.3.0"
46
+
47
+ def to_dict(self) -> dict[str, Any]:
48
+ return {
49
+ "prompt_id": self.prompt_id,
50
+ "source": {
51
+ "path": self.source.relative_path,
52
+ "kind": self.source.source_kind,
53
+ "format_version": self.source.source_format_version,
54
+ "digest": self.source.source_digest,
55
+ },
56
+ "generated_files": dict(self.output.files),
57
+ "registry_entry": dict(self.output.registry_entry) if self.output.registry_entry is not None else None,
58
+ "manifest_record": dict(self.output.manifest_record),
59
+ "compatibility": self.compatibility.to_dict(),
60
+ "converter": self.converter,
61
+ "converter_version": self.converter_version,
62
+ }
63
+
64
+
65
+ class SourceAdapter(ABC):
66
+ source_kind = "unknown"
67
+ converter = "opf-migrate-unknown"
68
+
69
+ @abstractmethod
70
+ def inspect(self, path: str | Path, *, root: str | Path = ".") -> SourcePrompt:
71
+ """Read a source prompt without modifying it."""
72
+
73
+ @abstractmethod
74
+ def plan(self, source: SourcePrompt, prompt_id: str, *, role: str | None = None) -> MigrationPlan:
75
+ """Build a deterministic migration plan without filesystem writes."""
76
+
77
+ @abstractmethod
78
+ def convert(self, source: SourcePrompt, plan: MigrationPlan) -> MigrationOutput:
79
+ """Return generated files and metadata for the previously inspected source."""
80
+
81
+
82
+ def read_source(path: str | Path, root: str | Path, source_kind: str) -> SourcePrompt:
83
+ base = Path(root).resolve()
84
+ source_path = Path(path)
85
+ if not source_path.is_absolute():
86
+ source_path = base / source_path
87
+ try:
88
+ resolved = source_path.resolve(strict=True)
89
+ relative_path = resolved.relative_to(base).as_posix()
90
+ except (OSError, ValueError) as exc:
91
+ raise OPFError("source prompt must exist inside the migration root: {}".format(path)) from exc
92
+ if source_path.is_symlink() or not resolved.is_file():
93
+ raise OPFError("source prompt must be a regular file: {}".format(path))
94
+ try:
95
+ text = resolved.read_text(encoding="utf-8")
96
+ except (OSError, UnicodeError) as exc:
97
+ raise OPFError("cannot read source prompt {}: {}".format(relative_path, exc)) from exc
98
+ return SourcePrompt(resolved, relative_path, source_kind, text, normalized_digest(text))
opf/adapters/common.py ADDED
@@ -0,0 +1,55 @@
1
+ """Shared conversion helpers for source formats with static messages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from typing import Any, Iterable
7
+
8
+ import yaml
9
+
10
+ from ..compatibility import CompatibilityFinding, CompatibilityReport
11
+ from ..core import OPFError, VARIABLE_RE, parse
12
+ from .base import MigrationOutput, MigrationPlan, SourcePrompt
13
+ from .markdown import ID_RE
14
+
15
+
16
+ def plan_messages(
17
+ source: SourcePrompt,
18
+ prompt_id: str,
19
+ messages: list[dict[str, str]],
20
+ *,
21
+ converter: str,
22
+ source_format_version: str | None = None,
23
+ inputs: Iterable[str] = (),
24
+ extensions: dict[str, Any] | None = None,
25
+ findings: Iterable[CompatibilityFinding] = (),
26
+ ) -> MigrationPlan:
27
+ if not ID_RE.fullmatch(prompt_id):
28
+ raise OPFError("prompt id must match [a-z0-9]+(?:[._-][a-z0-9]+)*")
29
+ if not messages or any(not isinstance(item, dict) or set(item) != {"role", "content"} or not isinstance(item["role"], str) or item["role"] not in {"system", "developer", "user", "assistant"} or not isinstance(item["content"], str) for item in messages):
30
+ raise OPFError("source must provide ordered text messages with supported roles")
31
+ declared = set(inputs)
32
+ for item in messages:
33
+ declared.update(VARIABLE_RE.findall(item["content"]))
34
+ metadata: dict[str, Any] = {"format": "opf/0.3", "id": prompt_id}
35
+ if declared:
36
+ metadata["inputs"] = {name: {"type": "string", "required": True} for name in sorted(declared)}
37
+ if extensions:
38
+ metadata["extensions"] = extensions
39
+ body = "\n\n".join("## {}\n{}".format(item["role"], item["content"]) for item in messages)
40
+ content = "---\n{}\n---\n\n{}".format(yaml.safe_dump(metadata, allow_unicode=True, sort_keys=False).rstrip(), body)
41
+ parse(content)
42
+ output_path = "prompts/{}.opf.md".format(prompt_id)
43
+ all_findings = tuple(findings) + (CompatibilityFinding("messages.preserved", "info", "preserved", "Ordered text messages were mapped to OPF core"),)
44
+ report = CompatibilityReport(source.source_kind, "opf/0.3", all_findings, all(item.disposition == "preserved" for item in all_findings), not any(item.severity == "error" for item in all_findings))
45
+ record = {
46
+ "source_path": source.relative_path,
47
+ "source_kind": source.source_kind,
48
+ **({"source_format_version": source_format_version or source.source_format_version} if (source_format_version or source.source_format_version) else {}),
49
+ "source_digest": source.source_digest,
50
+ "converter": converter,
51
+ "converter_version": "0.3.0",
52
+ "migrated_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
53
+ "findings": [{"code": item.code, "severity": item.severity, "disposition": item.disposition, "message": item.message, **({"path": item.source_path} if item.source_path else {})} for item in all_findings],
54
+ }
55
+ return MigrationPlan(prompt_id, source, MigrationOutput({output_path: content}, {"renderer": "opf", "source": output_path}, record), report, converter)
opf/adapters/crewai.py ADDED
@@ -0,0 +1,67 @@
1
+ """Import explicit static CrewAI agent prompt templates from YAML or JSON."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import yaml
11
+
12
+ from ..compatibility import CompatibilityFinding
13
+ from ..core import OPFError
14
+ from .base import SourcePrompt, read_source
15
+ from .common import plan_messages
16
+ from .markdown import ID_RE
17
+
18
+ PLACEHOLDER_RE = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)\}")
19
+
20
+
21
+ class CrewAIAdapter:
22
+ source_kind = "crewai-agent-template"
23
+ converter = "opf-migrate-crewai"
24
+
25
+ def inspect(self, path: str | Path, *, root: str | Path = ".") -> SourcePrompt:
26
+ source = read_source(path, root, self.source_kind)
27
+ try:
28
+ value = json.loads(source.text) if source.path.suffix.lower() == ".json" else yaml.safe_load(source.text)
29
+ except Exception as exc:
30
+ raise OPFError("CrewAI input must be static JSON or YAML: {}".format(exc)) from exc
31
+ if not isinstance(value, dict):
32
+ raise OPFError("CrewAI input must be a mapping")
33
+ return SourcePrompt(source.path, source.relative_path, source.source_kind, source.text, source.source_digest, "static-agent-template/1", {"value": value})
34
+
35
+ def plan(self, source: SourcePrompt, prompt_id: str, *, role: str | None = None):
36
+ if not ID_RE.fullmatch(prompt_id):
37
+ raise OPFError("invalid prompt id")
38
+ value: dict[str, Any] = (source.data or {}).get("value", {})
39
+ known = {"role", "goal", "backstory", "system_template", "prompt_template", "custom_prompts"}
40
+ if set(value) - known:
41
+ raise OPFError("unsupported CrewAI field(s): {}".format(", ".join(sorted(set(value) - known))))
42
+ messages = []
43
+ findings = [CompatibilityFinding("crewai.orchestration.excluded", "warning", "dropped", "Agent execution, tools, and orchestration are outside the prompt format")]
44
+ for key, message_role in (("system_template", "system"), ("prompt_template", role or "user")):
45
+ template = value.get(key)
46
+ if template is None:
47
+ continue
48
+ if not isinstance(template, str):
49
+ raise OPFError("{} must be a static string".format(key))
50
+ scrubbed = PLACEHOLDER_RE.sub("", template)
51
+ if "{" in scrubbed or "}" in scrubbed:
52
+ raise OPFError("unsupported CrewAI placeholder syntax in {}".format(key))
53
+ text = PLACEHOLDER_RE.sub(lambda m: "{{ " + m.group(1) + " }}", template)
54
+ messages.append({"role": message_role, "content": text})
55
+ if not messages:
56
+ for key in ("backstory", "goal"):
57
+ if key in value:
58
+ raise OPFError("CrewAI {} is agent configuration; provide system_template or prompt_template for migration".format(key))
59
+ raise OPFError("CrewAI input requires system_template or prompt_template")
60
+ extension_data = {key: value[key] for key in ("role", "goal", "backstory", "custom_prompts") if key in value}
61
+ extensions = {"com.crewai.agent": {"version": "1", "required": False, "data": extension_data}} if extension_data else None
62
+ return plan_messages(source, prompt_id, messages, converter=self.converter, source_format_version=source.source_format_version, extensions=extensions, findings=findings)
63
+
64
+ def convert(self, source: SourcePrompt, plan):
65
+ if source.source_digest != plan.source.source_digest:
66
+ raise OPFError("source changed after migration plan was created")
67
+ return plan.output
opf/adapters/jinja.py ADDED
@@ -0,0 +1,87 @@
1
+ """Inspect Jinja sources and either simplify them or register them unchanged."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import replace
7
+ from datetime import datetime, timezone
8
+ from pathlib import Path
9
+
10
+ from ..compatibility import CompatibilityFinding, CompatibilityReport
11
+ from ..core import OPFError, VARIABLE_RE
12
+ from .base import MigrationOutput, MigrationPlan, SourceAdapter, SourcePrompt, read_source
13
+ from .markdown import MarkdownAdapter, ID_RE
14
+
15
+ INCLUDE_RE = re.compile(r"{%\s*(?:include|import|from)\s+['\"]([^'\"]+)['\"]")
16
+ DYNAMIC_INCLUDE_RE = re.compile(r"{%\s*(?:include|import|from)\s+(?!['\"])\S+")
17
+ SIMPLE_VARIABLE_RE = re.compile(r"{{\s*[A-Za-z_][A-Za-z0-9_]*\s*}}")
18
+
19
+
20
+ class JinjaAdapter(SourceAdapter):
21
+ source_kind = "jinja2"
22
+ converter = "opf-migrate-jinja"
23
+
24
+ def inspect(self, path: str | Path, *, root: str | Path = ".") -> SourcePrompt:
25
+ source = read_source(path, root, self.source_kind)
26
+ if source.path.suffix.lower() != ".j2" and "{{" not in source.text and "{%" not in source.text:
27
+ raise OPFError("source does not appear to use Jinja syntax")
28
+ static = sorted(set(INCLUDE_RE.findall(source.text)))
29
+ data = {"static_includes": static, "dynamic_include": bool(DYNAMIC_INCLUDE_RE.search(source.text))}
30
+ return SourcePrompt(source.path, source.relative_path, source.source_kind, source.text, source.source_digest, "jinja2", data)
31
+
32
+ def plan(self, source: SourcePrompt, prompt_id: str, *, role: str | None = None) -> MigrationPlan:
33
+ if not ID_RE.fullmatch(prompt_id):
34
+ raise OPFError("prompt id must match [a-z0-9]+(?:[._-][a-z0-9]+)*")
35
+ if role is None or role not in {"system", "developer", "user", "assistant"}:
36
+ finding = CompatibilityFinding("jinja.role.required", "error", "manual", "Choose one explicit role with --role before importing a standalone Jinja file")
37
+ report = CompatibilityReport(source.source_kind, "opf-registry/1", (finding,), False, False)
38
+ now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
39
+ record = {"source_path": source.relative_path, "source_kind": source.source_kind, "source_format_version": "jinja2", "source_digest": source.source_digest, "converter": self.converter, "converter_version": "0.3.0", "migrated_at": now, "findings": [{"code": finding.code, "severity": finding.severity, "disposition": finding.disposition, "message": finding.message}]}
40
+ return MigrationPlan(prompt_id, source, MigrationOutput({}, None, record), report, self.converter)
41
+
42
+ data = dict(source.data or {})
43
+ findings = []
44
+ if data.get("dynamic_include"):
45
+ finding = CompatibilityFinding("jinja.include.dynamic", "error", "manual", "Dynamic Jinja include/import targets cannot be pinned into a reproducible bundle", source_path=source.relative_path)
46
+ findings.append(finding)
47
+ stripped = SIMPLE_VARIABLE_RE.sub("", source.text)
48
+ simple = not data.get("dynamic_include") and not re.search(r"{%|{#|\|", source.text) and not re.search(r"{{|}}|[{}]", stripped)
49
+ if simple:
50
+ markdown = MarkdownAdapter()
51
+ plan = markdown.plan(source, prompt_id, role=role)
52
+ record = dict(plan.output.manifest_record)
53
+ record["source_kind"] = self.source_kind
54
+ record["source_format_version"] = "jinja2"
55
+ record["converter"] = self.converter
56
+ findings.extend(plan.compatibility.findings)
57
+ findings.append(CompatibilityFinding("jinja.simple.variables", "warning", "approximated", "Simple Jinja variables were migrated to OPF interpolation; whitespace trimming may differ"))
58
+ report = CompatibilityReport(self.source_kind, "opf/0.3", tuple(findings), False, not any(item.severity == "error" for item in findings))
59
+ output = replace(plan.output, manifest_record=record)
60
+ return MigrationPlan(prompt_id, source, output, report, self.converter)
61
+
62
+ variable_names = sorted(set(VARIABLE_RE.findall(source.text)))
63
+ inputs = {name: {"type": "string", "required": True} for name in variable_names}
64
+ entry = {"renderer": "jinja2", "messages": [{"role": role, "file": source.relative_path}]}
65
+ if inputs:
66
+ entry["inputs"] = inputs
67
+ findings.append(CompatibilityFinding("jinja.source.preserved", "info", "preserved", "Original Jinja source and its template semantics are kept in the OPF local registry", source_path=source.relative_path))
68
+ if data.get("static_includes"):
69
+ findings.append(CompatibilityFinding("jinja.dependencies.static", "info", "preserved", "Static template dependencies will be pinned when the registry releases the prompt", source_path=source.relative_path))
70
+ findings.append(CompatibilityFinding("jinja.template.runtime", "warning", "preserved", "Rendering still requires the optional Python Jinja2 runtime", capability="jinja2"))
71
+ report = CompatibilityReport(self.source_kind, "opf-registry/1", tuple(findings), not data.get("dynamic_include", False), not any(item.severity == "error" for item in findings))
72
+ record = {
73
+ "source_path": source.relative_path,
74
+ "source_kind": source.source_kind,
75
+ "source_format_version": "jinja2",
76
+ "source_digest": source.source_digest,
77
+ "converter": self.converter,
78
+ "converter_version": "0.3.0",
79
+ "migrated_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
80
+ "findings": [{"code": item.code, "severity": item.severity, "disposition": item.disposition, "message": item.message, **({"path": item.source_path} if item.source_path else {})} for item in findings],
81
+ }
82
+ return MigrationPlan(prompt_id, source, MigrationOutput({}, entry, record), report, self.converter)
83
+
84
+ def convert(self, source: SourcePrompt, plan: MigrationPlan) -> MigrationOutput:
85
+ if source.source_digest != plan.source.source_digest:
86
+ raise OPFError("source changed after migration plan was created")
87
+ return plan.output
@@ -0,0 +1,77 @@
1
+ """Offline import of a deliberately small LangChain prompt configuration subset."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import yaml
11
+
12
+ from ..compatibility import CompatibilityFinding
13
+ from ..core import OPFError
14
+ from .base import SourcePrompt, read_source
15
+ from .common import plan_messages
16
+ from .markdown import ID_RE
17
+
18
+ _FIELD = re.compile(r"(?<!\{)\{([A-Za-z_][A-Za-z0-9_]*)\}(?!\})")
19
+
20
+
21
+ class LangChainAdapter:
22
+ source_kind = "langchain-prompt"
23
+ converter = "opf-migrate-langchain"
24
+
25
+ def inspect(self, path: str | Path, *, root: str | Path = ".") -> SourcePrompt:
26
+ source = read_source(path, root, self.source_kind)
27
+ try:
28
+ value = json.loads(source.text) if source.path.suffix.lower() == ".json" else yaml.safe_load(source.text)
29
+ except Exception as exc:
30
+ raise OPFError("LangChain prompt input must be static JSON or YAML: {}".format(exc)) from exc
31
+ if not isinstance(value, dict):
32
+ raise OPFError("LangChain prompt input must be a mapping")
33
+ kind = value.get("_type", value.get("type"))
34
+ if kind not in {"prompt", "prompt_template", "chat", "chat_prompt"}:
35
+ raise OPFError("unsupported LangChain prompt type; expected PromptTemplate or ChatPromptTemplate")
36
+ data: dict[str, Any] = {"value": value, "kind": kind}
37
+ return SourcePrompt(source.path, source.relative_path, source.source_kind, source.text, source.source_digest, str(value.get("version", "unknown")), data)
38
+
39
+ def plan(self, source: SourcePrompt, prompt_id: str, *, role: str | None = None):
40
+ if not ID_RE.fullmatch(prompt_id):
41
+ raise OPFError("invalid prompt id")
42
+ value = (source.data or {}).get("value", {})
43
+ variables = value.get("input_variables", [])
44
+ if not isinstance(variables, list) or not all(isinstance(x, str) for x in variables):
45
+ raise OPFError("LangChain input_variables must be a list of names")
46
+ findings = [CompatibilityFinding("langchain.template.converted", "warning", "approximated", "Only simple single-brace variables are converted to OPF interpolation")]
47
+ kind = (source.data or {}).get("kind")
48
+ if kind in {"prompt", "prompt_template"}:
49
+ template = value.get("template")
50
+ if not isinstance(template, str):
51
+ raise OPFError("PromptTemplate requires a static string template")
52
+ fields = set(_FIELD.findall(template))
53
+ scrubbed = _FIELD.sub("", template)
54
+ if "{" in scrubbed or "}" in scrubbed or fields - set(variables):
55
+ raise OPFError("complex format fields or undeclared variables require manual migration")
56
+ converted = _FIELD.sub(lambda m: "{{ " + m.group(1) + " }}", template)
57
+ messages = [{"role": role or "user", "content": converted}]
58
+ else:
59
+ raw_messages = value.get("messages")
60
+ if not isinstance(raw_messages, list) or not raw_messages:
61
+ raise OPFError("ChatPromptTemplate requires a static ordered messages list")
62
+ messages = []
63
+ for item in raw_messages:
64
+ if not isinstance(item, dict) or not isinstance(item.get("role"), str) or item.get("role") not in {"system", "developer", "user", "assistant"} or not isinstance(item.get("content"), str):
65
+ raise OPFError("ChatPromptTemplate supports only static role/content message mappings")
66
+ content = item["content"]
67
+ fields = set(_FIELD.findall(content))
68
+ scrubbed = _FIELD.sub("", content)
69
+ if "{" in scrubbed or "}" in scrubbed or fields - set(variables):
70
+ raise OPFError("complex format fields or undeclared variables require manual migration")
71
+ messages.append({"role": item["role"], "content": _FIELD.sub(lambda m: "{{ " + m.group(1) + " }}", content)})
72
+ return plan_messages(source, prompt_id, messages, converter=self.converter, source_format_version=source.source_format_version, inputs=variables, findings=findings)
73
+
74
+ def convert(self, source: SourcePrompt, plan):
75
+ if source.source_digest != plan.source.source_digest:
76
+ raise OPFError("source changed after migration plan was created")
77
+ return plan.output