Metadata-Version: 2.4
Name: uone-prompt-manager
Version: 0.1.0
Summary: Load, version, render, and convert prompts in CDEX, Jinja2, and LangChain formats
Author: Yu Wang
License-Expression: MIT
Project-URL: Homepage, https://github.com/qizhu8/uone-prompt-manager
Project-URL: Repository, https://github.com/qizhu8/uone-prompt-manager
Project-URL: Issues, https://github.com/qizhu8/uone-prompt-manager/issues
Keywords: prompt,llm,template,jinja2,langchain,prompt-engineering
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: langchain-core<2,>=0.3.86
Requires-Dist: jinja2<4,>=3.1.6
Requires-Dist: pyyaml<7,>=6.0.3
Dynamic: license-file

# uone-prompt-manager

`uone-prompt-manager` loads, versions, renders, and converts prompt templates for
LLM applications. The PyPI project name uses a hyphen; the Python import uses
an underscore: `import prompt_manager`.

## Features

- CDEX text templates (`#variable#`)
- Jinja2 templates (`{{ variable }}`), including conditionals, loops, and filters
- LangChain prompt files in JSON or YAML
- Completion strings and ChatML-style role messages
- Version discovery from `v1`, `v1.2`, and similar directories
- CDEX/LangChain-to-Jinja2 conversion and a searchable template registry

Python 3.9 through 3.12 is supported.

## Installation

```bash
python -m pip install uone-prompt-manager
```

## Quick Start

Create `greeting.jinja2`:

```jinja2
{% if formal %}Hello{% else %}Hi{% endif %}, {{ name }}!
```

Render it:

```python
from prompt_manager import PromptGeneratorLight, PromptMode

generator = PromptGeneratorLight("greeting.jinja2", prompt_style="jinja2")
result = generator.generate_prompt(
    data={"customer_name": "Ada", "use_formal_tone": True},
    vars_in_data=["customer_name", "use_formal_tone"],
    vars_in_prompt=["name", "formal"],
    prompt_mode=PromptMode.COMPLETION,
)
assert result == "Hello, Ada!"
```

`vars_in_data` names keys in the input mapping. `vars_in_prompt` names the
corresponding template variables. Both lists must have the same length.
Lowercase mode strings (`"completion"` and `"chat"`) are also accepted.

To supply a constant instead of reading an input key, prefix the mapped value
with `_C`. For example, mapping `_Cconcise` to `tone` renders `tone` as
`"concise"`.

## Versioned Prompt Classes

Use `MyPromptBase` when an application keeps one prompt per version directory:

```text
prompt_lib/
  headline/
    v1/
      prompt.jinja2
    v2.1/
      prompt.jinja2
```

```python
from pathlib import Path
from prompt_manager import MyPromptBase


class HeadlinePrompt(MyPromptBase):
    DEFAULT_PROMPT_DIR = Path("prompt_lib/headline")
    DEFAULT_PROMPT_FILE = "prompt.jinja2"
    DEFAULT_VERSION = "v2.1"
    DEFAULT_PROMPT_TYPE = "jinja2"

    def __init__(self, version="v2.1"):
        super().__init__(
            description="Generate a headline",
            prompt_path=self.DEFAULT_PROMPT_DIR / version / self.DEFAULT_PROMPT_FILE,
            prompt_type=self.DEFAULT_PROMPT_TYPE,
            keys_to_extract=("headline",),
            vars_in_data_dict={"product": "product_name"},
            version=version,
        )


prompt = HeadlinePrompt()
text = prompt.generate_completion_prompt({"product_name": "Trail shoes"})
```

In `vars_in_data_dict`, each key is a template variable and each value is an
input-data key. `keys_to_extract` and `output_key_rename_dict` are configuration
metadata for downstream output processing; this package does not parse model
responses.

If `DEFAULT_VERSION` is `None`, the numerically latest available version is
selected. For example, `v2.0.1 > v0.11 > v0.2.1 > v0.2 > v0.1`.

## Chat Prompts

Chat templates may use ChatML-style role blocks:

```text
<|im_start|>system
You are a concise assistant.<|im_end|>
<|im_start|>user
Summarize {{ document }}<|im_end|>
```

Chat mode returns tuples such as
`(("system", "..."), ("user", "..."))`. If a rendered prompt has no role
blocks, it becomes one `user` message. Text outside detected role blocks is
dropped and produces a once-per-process `UserWarning`.

## Convert Templates

```python
from prompt_manager import TemplateConverter

converted = TemplateConverter.cdex_to_jinja2("Hello #name#")
assert converted == "Hello {{ name }}"

content, output_path = TemplateConverter.cdex_file_to_jinja2("legacy.txt")
```

Batch conversion methods recurse through a directory and return successful
conversions. They print individual conversion errors and continue, so callers
that require all-or-nothing conversion should verify the returned file count.
See [CONVERTER_GUIDE.md](CONVERTER_GUIDE.md) for the complete conversion API.

## Template Registry

`clean_and_load_library` normalizes CDEX, LangChain, and Jinja2 source trees into
a separate Jinja2 output directory. The output directory must not be inside the
source directory.

```python
from prompt_manager import PromptTemplateRegistry, TemplateConverter

clean_result = TemplateConverter.clean_and_load_library(
    source_root="prompt_lib",
    output_root="prompt_lib_cleaned",
)
registry = PromptTemplateRegistry.from_clean_result(clean_result)

key, rendered = registry.render_resolved(
    prefix="headline",
    template_name="prompt",
    context={"product": "Trail shoes"},
)
```

Resolution prefers the latest numeric version, then native Jinja2 over
LangChain over CDEX, then the base key over collision variants.

## Security

Jinja2 templates are parsed and rendered with `SandboxedEnvironment`, and YAML
prompt files use `yaml.safe_load`. The sandbox blocks common Python object and
runtime access, but it is not a CPU or memory quota. Do not render untrusted
templates without process-level time and resource limits. Prompt text output is
not HTML-escaped.

## Common Errors

- `FileNotFoundError`: the prompt file or default version directory is missing.
- `ValueError: Variable ... not found in data`: fix the `vars_in_data` or
  `vars_in_data_dict` mapping.
- `ValueError: Unsupported prompt mode/style`: use `completion`/`chat` and
  `cdex`/`jinja2`/`langchain` respectively.
- Direct Jinja2 loading raises syntax errors immediately. Library cleaning keeps
  invalid templates with `loaded_template=None` and a `parse_error` value.

## Development

```bash
git clone https://github.com/qizhu8/uone-prompt-manager.git
cd uone-prompt-manager
python -m pip install -e . pytest
pytest -q
```
