├── prompt_decorators ├── py.typed ├── integrations │ ├── __init__.py │ └── mcp │ │ ├── __init__.py │ │ ├── __main__.py │ │ ├── claude_desktop.py │ │ └── install_claude_desktop.py ├── schemas │ └── __init__.py ├── utils │ └── __init__.py ├── core │ ├── exceptions.py │ └── __init__.py ├── config.py ├── __init__.py └── registry │ └── core │ ├── minimal │ ├── version.json │ ├── step-by-step.json │ └── reasoning.json │ └── reasoning │ └── socratic.json ├── docs ├── arch_intent_to_decorator.md ├── prd_intent_to_decorator.md ├── assets │ ├── logo.png │ └── logo.jpeg ├── api │ ├── modules │ │ ├── prompt_decorators.integrations.mcp.__main__.md │ │ ├── prompt_decorators.integrations.md │ │ ├── prompt_decorators.integrations.mcp.claude_desktop.md │ │ ├── prompt_decorators.core.exceptions.md │ │ ├── prompt_decorators.utils.string_utils.md │ │ ├── prompt_decorators.integrations.mcp.install_claude_desktop.md │ │ ├── prompt_decorators.utils.md │ │ ├── prompt_decorators.config.md │ │ ├── prompt_decorators.core.parser.md │ │ ├── prompt_decorators.schemas.decorator_schema.md │ │ ├── prompt_decorators.utils.json_loader.md │ │ ├── prompt_decorators.schemas.md │ │ ├── prompt_decorators.core.request.md │ │ └── prompt_decorators.integrations.mcp.server.md │ ├── decorators │ │ ├── Version.md │ │ ├── StepByStep.md │ │ ├── Socratic.md │ │ ├── Reasoning.md │ │ └── Iterate.md │ └── index.md ├── requirements.txt ├── integrations │ └── index.md └── documentation_checklist.md ├── .cursorignore ├── tests ├── integrations │ └── __init__.py ├── __init__.py ├── utils │ └── __init__.py ├── requirements.txt ├── conftest.py ├── test_dynamic_decorators_module.py └── examples │ ├── README.md │ └── reasoning_test_example.py ├── demo ├── examples │ └── __init__.py ├── utils │ ├── __init__.py │ └── config.py ├── requirements.txt ├── __init__.py ├── .env.sample └── main.py ├── .cursorindexingignore ├── CHANGELOG.md ├── scripts ├── git-hooks │ └── pre-push ├── validate_registry.py ├── validate.py ├── check_demo_types.py ├── README.md ├── standardize_imports.py ├── copy_registry.py ├── bump_version.py ├── setup_pre_commit.py ├── setup_registry.py └── debug_transform.py ├── registry ├── core │ ├── minimal │ │ ├── README.md │ │ ├── version.json │ │ ├── step-by-step.json │ │ └── reasoning.json │ ├── README.md │ ├── meta │ │ └── README.md │ ├── verification │ │ └── README.md │ ├── tone │ │ └── README.md │ ├── structure │ │ └── README.md │ └── reasoning │ │ ├── README.md │ │ └── socratic.json ├── extensions │ └── README.md └── decorator-template.json ├── .github ├── dependabot.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── code-quality.yml ├── xnotes ├── project-idea-prompt.md ├── git-push-command.md ├── workflow-agile.md ├── template-story.md ├── 801-workflow-agile.mdc └── 903-story-template.mdc ├── MANIFEST.in ├── setup.cfg ├── .cursor ├── rules │ ├── 001-emoji-communication.mdc │ ├── 050-careful-code-modification.mdc │ ├── 060-coding-patterns.mdc │ ├── 070-workflow-preferences.mdc │ ├── 000-cursor-rules.mdc │ └── 400-md-docs.mdc └── templates │ └── template-story.md ├── schemas ├── simplified-decorator.schema.yaml ├── README.md └── api-request.schema.json ├── .pre-commit-config.yaml ├── mypy.ini ├── pyproject.toml └── config └── model_capabilities.json /prompt_decorators/py.typed: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/arch_intent_to_decorator.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/prd_intent_to_decorator.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.cursorignore: -------------------------------------------------------------------------------- 1 | # Project notes and templates 2 | xnotes/ 3 | -------------------------------------------------------------------------------- /tests/integrations/__init__.py: -------------------------------------------------------------------------------- 1 | """Tests for integrations.""" 2 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Tests for Prompt Decorators. 4 | """ 5 | -------------------------------------------------------------------------------- /demo/examples/__init__.py: -------------------------------------------------------------------------------- 1 | """Examples of using prompt decorators with OpenAI.""" 2 | -------------------------------------------------------------------------------- /demo/utils/__init__.py: -------------------------------------------------------------------------------- 1 | """Utility functions for the OpenAI prompt decorator demo.""" 2 | -------------------------------------------------------------------------------- /.cursorindexingignore: -------------------------------------------------------------------------------- 1 | # Templates - accessible but not indexed 2 | .cursor/templates/ 3 | -------------------------------------------------------------------------------- /tests/utils/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Utility functions for testing Prompt Decorators. 4 | """ 5 | -------------------------------------------------------------------------------- /docs/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synaptiai/prompt-decorators/HEAD/docs/assets/logo.png -------------------------------------------------------------------------------- /docs/assets/logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/synaptiai/prompt-decorators/HEAD/docs/assets/logo.jpeg -------------------------------------------------------------------------------- /demo/requirements.txt: -------------------------------------------------------------------------------- 1 | # Requirements for the Prompt Decorators OpenAI Demo 2 | prompt-decorators 3 | openai 4 | python-dotenv 5 | rich # For pretty terminal output 6 | typer # For CLI interface 7 | -------------------------------------------------------------------------------- /demo/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | OpenAI Prompt Decorator Demo. 3 | 4 | This package demonstrates the use of prompt decorators with OpenAI's API. 5 | It showcases how decorators can enhance LLM outputs for various use cases. 6 | """ 7 | 8 | __version__ = "1.0.0" 9 | __author__ = "Demo author" 10 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to the Prompt Decorators project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | -------------------------------------------------------------------------------- /tests/requirements.txt: -------------------------------------------------------------------------------- 1 | pytest>=7.0.0 2 | pytest-cov>=2.12.0 3 | jsonschema>=4.0.0 4 | markdown>=3.3.0 5 | python-dotenv>=0.19.0 6 | # For real LLM testing (uncomment as needed) 7 | # openai>=0.27.0 8 | # anthropic>=0.2.0 9 | # For MCP integration testing (uncomment as needed) 10 | # mcp>=0.1.0 11 | -------------------------------------------------------------------------------- /prompt_decorators/integrations/__init__.py: -------------------------------------------------------------------------------- 1 | """Integration modules for Prompt Decorators. 2 | 3 | This package contains modules for integrating Prompt Decorators with 4 | various frameworks, protocols, and platforms. 5 | """ 6 | 7 | # Make the mcp module directly accessible 8 | from prompt_decorators.integrations import mcp 9 | 10 | __all__ = ["mcp"] 11 | -------------------------------------------------------------------------------- /prompt_decorators/schemas/__init__.py: -------------------------------------------------------------------------------- 1 | """Schema definitions for prompt decorators. 2 | 3 | This package contains schema definitions for validating decorator definitions 4 | and parameters. 5 | """ 6 | 7 | from prompt_decorators.schemas.decorator_schema import DecoratorSchema, ParameterSchema 8 | 9 | __all__ = [ 10 | "DecoratorSchema", 11 | "ParameterSchema", 12 | ] 13 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.integrations.mcp.__main__.md: -------------------------------------------------------------------------------- 1 | # __main__ 2 | 3 | Command-line entry point for running the Prompt Decorators MCP server. 4 | 5 | Usage: 6 | python -m prompt_decorators.integrations.mcp [`--host HOST`] [`--port PORT`] [`--verbose`] 7 | 8 | ## Functions 9 | 10 | ### `main` 11 | 12 | Run the Prompt Decorators MCP server. 13 | 14 | **Signature:** `main() -> None` 15 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.integrations.md: -------------------------------------------------------------------------------- 1 | # integrations 2 | 3 | Integration modules for Prompt Decorators. 4 | 5 | This package contains modules for integrating Prompt Decorators with 6 | various frameworks, protocols, and platforms. 7 | 8 | ## Public API 9 | 10 | This module exports the following components: 11 | 12 | - `mcp`: module - Model Context Protocol (MCP) integration for Prompt Decorators 13 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | mkdocs>=1.5.0 2 | mkdocs-material>=9.0.0 3 | mkdocs-awesome-pages-plugin==2.10.1 4 | mkdocs-autolinks-plugin>=0.7.0 5 | mkdocs-git-revision-date-localized-plugin>=1.2.0 6 | mkdocs-minify-plugin>=0.7.0 7 | mkdocstrings>=0.24.0 8 | mkdocstrings-python>=1.7.0 9 | pydantic>=2.0.0 10 | jsonschema>=4.0.0 11 | importlib-metadata>=6.0.0 12 | markdown>=3.7 13 | interrogate>=1.5.0 14 | pydocstyle>=6.3.0 15 | -------------------------------------------------------------------------------- /prompt_decorators/utils/__init__.py: -------------------------------------------------------------------------------- 1 | """Utility functions for prompt decorators. 2 | 3 | This package provides utility functions for working with prompt decorators. 4 | """ 5 | 6 | from prompt_decorators.utils.string_utils import ( 7 | extract_decorators_from_text, 8 | replace_decorators_in_text, 9 | ) 10 | 11 | __all__ = [ 12 | "extract_decorators_from_text", 13 | "replace_decorators_in_text", 14 | ] 15 | -------------------------------------------------------------------------------- /demo/.env.sample: -------------------------------------------------------------------------------- 1 | # OpenAI API Key 2 | # Get yours at https://platform.openai.com/api-keys 3 | OPENAI_API_KEY=your_api_key_here 4 | 5 | # Model Configuration 6 | DEFAULT_MODEL=gpt-4o 7 | MAX_TOKENS=2048 8 | TEMPERATURE=0.7 9 | 10 | # Logging Configuration 11 | # Valid levels: DEBUG, INFO, WARNING, ERROR 12 | LOG_LEVEL=INFO 13 | # Set to true to save logs to file 14 | SAVE_LOGS=false 15 | LOG_FILE=prompt_decorator_demo.log 16 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.integrations.mcp.claude_desktop.md: -------------------------------------------------------------------------------- 1 | # claude_desktop 2 | 3 | Entry point for running the Prompt Decorators MCP server for Claude Desktop. 4 | 5 | Usage: 6 | python -m prompt_decorators.integrations.mcp.claude_desktop [`--host HOST`] [`--port PORT`] [`--verbose`] 7 | 8 | ## Functions 9 | 10 | ### `main` 11 | 12 | Run the Prompt Decorators MCP server for Claude Desktop. 13 | 14 | **Signature:** `main() -> None` 15 | -------------------------------------------------------------------------------- /scripts/git-hooks/pre-push: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Pre-push hook to run strict type checking on the demo directory 4 | # To install: copy this file to .git/hooks/pre-push and make it executable 5 | 6 | # Get the repo root directory 7 | ROOT_DIR=$(git rev-parse --show-toplevel) 8 | 9 | # Run the demo type checking script 10 | echo "Running strict type checking on demo directory..." 11 | $ROOT_DIR/scripts/check_demo_types.py 12 | 13 | # Exit with the script's exit code 14 | exit $? 15 | -------------------------------------------------------------------------------- /registry/core/minimal/README.md: -------------------------------------------------------------------------------- 1 | # Minimal Core Decorators 2 | 3 | These five decorators form the minimal conforming implementation and **MUST** be supported by any implementation claiming compliance with the Prompt Decorators standard. 4 | 5 | ## Decorators in this category: 6 | 7 | 1. **Reasoning** - Explicit reasoning path before conclusion 8 | 2. **StepByStep** - Sequential problem-solving with labeled steps 9 | 3. **OutputFormat** - Specify output format 10 | 4. **Tone** - Overall tone adjustment 11 | 5. **Version** - Specify standard version compatibility 12 | 13 | According to the specification (Section 1.3 Conformance), implementations claiming conformance to this standard MUST implement at least these five decorators. 14 | -------------------------------------------------------------------------------- /prompt_decorators/core/exceptions.py: -------------------------------------------------------------------------------- 1 | """Exceptions for the prompt-decorators package. 2 | 3 | This module defines custom exceptions used throughout the package. 4 | """ 5 | 6 | 7 | class IncompatibleVersionError(Exception): 8 | """Raised when a decorator version is incompatible. 9 | 10 | This exception is raised when attempting to use a decorator with a version 11 | that is not compatible with the current version of the package. 12 | """ 13 | 14 | pass 15 | 16 | 17 | class RegistryError(Exception): 18 | """Raised when there is an error with the decorator registry. 19 | 20 | This exception is raised when there is an issue with registering or 21 | retrieving decorators from the registry. 22 | """ 23 | 24 | pass 25 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.core.exceptions.md: -------------------------------------------------------------------------------- 1 | # exceptions 2 | 3 | Exceptions for the prompt-decorators package. 4 | 5 | This module defines custom exceptions used throughout the package. 6 | 7 | ## Classes 8 | 9 | ### `IncompatibleVersionError` 10 | 11 | Raised when a decorator version is incompatible. 12 | 13 | This exception is raised when attempting to use a decorator with a version 14 | that is not compatible with the current version of the package. 15 | 16 | **Bases:** `builtins.Exception` 17 | 18 | ### `RegistryError` 19 | 20 | Raised when there is an error with the decorator registry. 21 | 22 | This exception is raised when there is an issue with registering or 23 | retrieving decorators from the registry. 24 | 25 | **Bases:** `builtins.Exception` 26 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Dependabot configuration file for prompt-decorators 2 | # This setup monitors Python dependencies and GitHub Actions 3 | 4 | version: 2 5 | updates: 6 | # Python dependencies managed by Poetry 7 | - package-ecosystem: "pip" 8 | directory: "/" 9 | schedule: 10 | interval: "weekly" 11 | open-pull-requests-limit: 10 12 | versioning-strategy: "lockfile-only" 13 | labels: 14 | - "dependencies" 15 | - "python" 16 | commit-message: 17 | prefix: "deps" 18 | include: "scope" 19 | 20 | # GitHub Actions 21 | - package-ecosystem: "github-actions" 22 | directory: "/" 23 | schedule: 24 | interval: "monthly" 25 | open-pull-requests-limit: 5 26 | labels: 27 | - "dependencies" 28 | - "github-actions" 29 | commit-message: 30 | prefix: "ci" 31 | include: "scope" 32 | -------------------------------------------------------------------------------- /prompt_decorators/core/__init__.py: -------------------------------------------------------------------------------- 1 | """Core components of the prompt decorators system. 2 | 3 | This package contains the core components and functionality that power the 4 | prompt decorators system, including the base decorator classes, validation logic, 5 | request handling, and model-specific adaptations. 6 | """ 7 | from prompt_decorators.core.base import ( 8 | DecoratorBase, 9 | DecoratorParameter, 10 | Parameter, 11 | ParameterType, 12 | ValidationError, 13 | ) 14 | from prompt_decorators.core.parser import DecoratorParser 15 | from prompt_decorators.core.registry import DecoratorRegistry 16 | 17 | # Add an alias for backward compatibility 18 | BaseDecorator = DecoratorBase 19 | 20 | __all__ = [ 21 | "DecoratorBase", 22 | "BaseDecorator", # Include the alias in __all__ 23 | "DecoratorParameter", 24 | "Parameter", 25 | "ValidationError", 26 | "ParameterType", 27 | "DecoratorParser", 28 | "DecoratorRegistry", 29 | ] 30 | -------------------------------------------------------------------------------- /registry/core/README.md: -------------------------------------------------------------------------------- 1 | # Core Decorators 2 | 3 | This directory contains all decorators defined in the original Prompt Decorators specification. These are officially part of the standard and maintained by the Prompt Decorators Working Group. 4 | 5 | The decorators are organized into the following categories: 6 | 7 | - **minimal**: The 5 core decorators that MUST be implemented by any conforming implementation 8 | - **reasoning**: Decorators that modify how the AI approaches reasoning about a problem 9 | - **structure**: Decorators that specify the structure and format of the AI's response 10 | - **tone**: Decorators that modify the linguistic style and tone of the AI's response 11 | - **verification**: Decorators that focus on ensuring accuracy, balance, and quality 12 | - **meta**: Decorators that modify the behavior of other decorators or provide higher-level control 13 | 14 | Each decorator is defined in a JSON file following the registry-entry.schema.json format. 15 | -------------------------------------------------------------------------------- /registry/core/meta/README.md: -------------------------------------------------------------------------------- 1 | # Meta-Decorators 2 | 3 | These decorators modify the behavior of other decorators or provide higher-level control. They allow for more complex combinations, conditional application, and advanced functionality that operates on or with other decorators. 4 | 5 | ## Decorators in this category: 6 | 7 | - **Refine** - Multiple improvement iterations 8 | - **Combine** - Use multiple decorators 9 | - **Conditional** - Conditional application 10 | - **Priority** - Prioritized application 11 | - **Custom** - User-defined decorator behavior 12 | - **Override** - Override default behaviors 13 | - **Context** - Domain-specific adaptation 14 | - **Extension** - Extensibility mechanism 15 | - **Compatibility** - Model compatibility 16 | - **Chain** - Define multi-step response process 17 | - **BuildOn** - Reference previous context 18 | 19 | Note: The **Version** decorator from this category is part of the minimal core set and can be found in the minimal directory. 20 | -------------------------------------------------------------------------------- /xnotes/project-idea-prompt.md: -------------------------------------------------------------------------------- 1 | Draft your initial prompt or ideas for a project here. Use this to then kickstart the project with the cursor agent mode when using the agile workflow, documented in docs/agile-readme.md. After the initial prd is drafted, work with the LLM in cursor or with an external LLM to ask questions, have the LLM ask you questions, etc., to really define an adequate prd and story list. Then continue with generating of the architecture document to ensure the project is built in a way that is easy to maintain and scale as you need it to be, along with a clear specification of what technologies and libraries you want to use. This will also help you figure out what rules you might want to initiall generate to help you build the project. 2 | 3 | Example: 4 | 5 | @agile Lets built a nextJs 15 web app to track our monthly income and expenses. I want a modern UI, secure storage in supabase, and a modern API. Etc... 6 | -------------------------------------------------------------------------------- /registry/core/verification/README.md: -------------------------------------------------------------------------------- 1 | # Verification and Quality Decorators 2 | 3 | These decorators focus on ensuring the accuracy, balance, and quality of the AI's response. They add mechanisms for verification, confidence indication, limitations awareness, and quality control. 4 | 5 | ## Decorators in this category: 6 | 7 | - **CiteSources** - Reference backing for claims 8 | - **FactCheck** - Verification of claims 9 | - **Limitations** - Explicit statement of limitations 10 | - **Confidence** - Indicate confidence in answers 11 | - **Balanced** - Ensure equal coverage of viewpoints 12 | - **Steelman** - Present strongest version of arguments 13 | - **PeerReview** - Self-critique as in academic review 14 | - **Precision** - Focus on exactness and accuracy 15 | - **Uncertainty** - Highlight areas of uncertainty 16 | - **QualityMetrics** - Apply specific quality metrics 17 | - **StressTest** - Identify potential failure points 18 | - **BreakAndBuild** - Criticize then reconstruct an idea 19 | - **FindGaps** - Identify missing elements in an idea 20 | -------------------------------------------------------------------------------- /scripts/validate_registry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Validate registry entries against the schema.""" 3 | 4 | import glob 5 | import json 6 | import sys 7 | 8 | from jsonschema import validate 9 | 10 | 11 | def main(): 12 | """Validate all registry entries.""" 13 | # Load schema 14 | with open("schemas/registry-entry.schema.json") as f: 15 | schema = json.load(f) 16 | 17 | # Track validation status 18 | all_valid = True 19 | 20 | # Validate all registry entries 21 | for entry_file in glob.glob("registry/core/*.json"): 22 | print(f"\nValidating {entry_file}...") 23 | with open(entry_file) as f: 24 | entry = json.load(f) 25 | 26 | try: 27 | validate(instance=entry, schema=schema) 28 | print("✓ Valid") 29 | except Exception as e: 30 | print(f"✗ Invalid: {str(e)}") 31 | all_valid = False 32 | 33 | # Exit with appropriate status code 34 | sys.exit(0 if all_valid else 1) 35 | 36 | 37 | if __name__ == "__main__": 38 | main() 39 | -------------------------------------------------------------------------------- /registry/extensions/README.md: -------------------------------------------------------------------------------- 1 | # Extension Decorators 2 | 3 | This directory contains decorators that are not defined in the original Prompt Decorators specification. These include: 4 | 5 | 1. **Community Extensions**: Decorators contributed by the community beyond the standard set 6 | 2. **Domain-Specific**: Specialized decorators for particular domains or industries 7 | 3. **Experimental**: New decorators being tested before potential inclusion in the core specification 8 | 4. **Implementation-Specific**: Decorators optimized for specific LLM implementations 9 | 10 | ## Contributing 11 | 12 | To contribute a new decorator to the extensions registry: 13 | 14 | 1. Create a JSON file following the registry-entry.schema.json format 15 | 2. Include comprehensive documentation, parameters, examples, and compatibility information 16 | 3. Submit a pull request with your extension 17 | 4. Ensure your decorator does not conflict with existing core or extension decorators 18 | 19 | Please follow the naming conventions and structure of existing decorators to maintain consistency across the registry. 20 | -------------------------------------------------------------------------------- /registry/core/tone/README.md: -------------------------------------------------------------------------------- 1 | # Tone and Style Decorators 2 | 3 | These decorators modify the linguistic style and tone of the AI's response. They influence the writing style, formality level, audience adaptation, and overall communication approach. 4 | 5 | ## Decorators in this category: 6 | 7 | - **Audience** - Adjust for audience expertise 8 | - **ELI5** - Explain like I'm 5 years old 9 | - **Academic** - Scholarly style 10 | - **Professional** - Business-oriented language 11 | - **Creative** - Creative writing style 12 | - **Concise** - Brief and to-the-point 13 | - **Detailed** - Comprehensive and thorough 14 | - **Narrative** - Story-based delivery 15 | - **Motivational** - Encouraging, inspiring tone 16 | - **AsExpert** - Respond from specific expert role 17 | - **Persona** - Adopt specific stakeholder viewpoint 18 | - **StyleShift** - Modify persuasion tactics or urgency 19 | - **Remix** - Reframe content for different contexts 20 | - **Extremes** - Present radical and minimal versions 21 | 22 | Note: The **Tone** decorator from this category is part of the minimal core set and can be found in the minimal directory. 23 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | # Include registry files in the package distribution 2 | recursive-include prompt_decorators/registry *.json 3 | recursive-include prompt_decorators/registry *.yml 4 | recursive-include prompt_decorators/registry *.yaml 5 | 6 | # Include documentation files 7 | include README.md 8 | include LICENSE 9 | include CHANGELOG.md 10 | include CONTRIBUTING.md 11 | include CODE_OF_CONDUCT.md 12 | 13 | # Include configuration files 14 | include pyproject.toml 15 | include setup.cfg 16 | include .pre-commit-config.yaml 17 | 18 | # Include schema files 19 | recursive-include schemas *.json 20 | recursive-include schemas *.yaml 21 | 22 | # Include type information 23 | include prompt_decorators/py.typed 24 | 25 | # Exclude development and build artifacts 26 | global-exclude *.pyc 27 | global-exclude *.pyo 28 | global-exclude *.pyd 29 | global-exclude __pycache__ 30 | global-exclude .git* 31 | global-exclude .DS_Store 32 | global-exclude *.so 33 | global-exclude .pytest_cache 34 | global-exclude .mypy_cache 35 | global-exclude .coverage 36 | global-exclude htmlcov 37 | global-exclude dist 38 | global-exclude build 39 | global-exclude *.egg-info 40 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.utils.string_utils.md: -------------------------------------------------------------------------------- 1 | # string_utils 2 | 3 | String utilities for working with prompt decorators. 4 | 5 | This module provides utility functions for extracting and replacing decorators in text. 6 | 7 | ## Functions 8 | 9 | ### `extract_decorators_from_text` 10 | 11 | Extract decorator annotations from text. 12 | 13 | Args: 14 | text: Text containing decorator annotations 15 | 16 | Returns: 17 | Tuple of (list of decorator dictionaries, clean text) 18 | 19 | **Signature:** `extract_decorators_from_text(text: str) -> Tuple[List[Dict[str, Any]], str]` 20 | 21 | **Parameters:** 22 | 23 | - `text`: `str` 24 | 25 | **Returns:** `Tuple` 26 | 27 | ### `replace_decorators_in_text` 28 | 29 | Replace decorator annotations in text. 30 | 31 | Args: 32 | text: Text to modify 33 | decorators: List of decorator dictionaries 34 | 35 | Returns: 36 | Text with decorator annotations replaced 37 | 38 | **Signature:** `replace_decorators_in_text(text: str, decorators: List[Dict[str, Any]]) -> str` 39 | 40 | **Parameters:** 41 | 42 | - `text`: `str` 43 | - `decorators`: `List` 44 | 45 | **Returns:** `str` 46 | -------------------------------------------------------------------------------- /registry/core/structure/README.md: -------------------------------------------------------------------------------- 1 | # Output Structure Decorators 2 | 3 | These decorators specify the structure and format of the AI's response. They control how information is organized, presented, and formatted in the output. 4 | 5 | ## Decorators in this category: 6 | 7 | - **Schema** - Define custom structure 8 | - **TableFormat** - Present data in tables 9 | - **Summary** - Provide condensed summary 10 | - **Outline** - Structured outline format 11 | - **Nested** - Hierarchical organization 12 | - **Bullet** - Bullet point format 13 | - **Timeline** - Chronological structure 14 | - **Comparison** - Direct comparison structure 15 | - **MECE** - Mutually exclusive, collectively exhaustive framework 16 | - **DecisionMatrix** - Structured decision-making format 17 | - **Alternatives** - Generate multiple distinct alternatives 18 | - **Layered** - Present at multiple explanation depths 19 | - **Constraints** - Apply specific limitations to the output 20 | - **Prioritize** - Rank items based on specified criteria 21 | 22 | Note: The **OutputFormat** decorator from this category is part of the minimal core set and can be found in the minimal directory. 23 | -------------------------------------------------------------------------------- /scripts/validate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Simple validation script for prompt decorator JSON files. 4 | """ 5 | 6 | import json 7 | import os 8 | import sys 9 | 10 | from jsonschema import validate 11 | 12 | 13 | def validate_file(file_path, schema_path): 14 | """Validate a file against a schema.""" 15 | try: 16 | with open(schema_path, "r") as f: 17 | schema = json.load(f) 18 | 19 | with open(file_path, "r") as f: 20 | data = json.load(f) 21 | 22 | validate(instance=data, schema=schema) 23 | print(f"✅ Validation successful for {file_path}") 24 | return True 25 | except Exception as e: 26 | print(f"❌ Validation failed for {file_path}: {e}") 27 | return False 28 | 29 | 30 | def main(): 31 | """Main function.""" 32 | if len(sys.argv) < 3: 33 | print("Usage: python validate.py ") 34 | sys.exit(1) 35 | 36 | file_path = sys.argv[1] 37 | schema_path = sys.argv[2] 38 | 39 | success = validate_file(file_path, schema_path) 40 | sys.exit(0 if success else 1) 41 | 42 | 43 | if __name__ == "__main__": 44 | main() 45 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | """Pytest configuration for decorator tests.""" 2 | 3 | import importlib 4 | from typing import Optional, Type 5 | 6 | import pytest 7 | 8 | from prompt_decorators.core.base import DecoratorBase 9 | 10 | 11 | @pytest.fixture 12 | def load_decorator(): 13 | """Fixture to load a decorator class by name.""" 14 | 15 | def _load_decorator(decorator_name: str) -> Optional[Type[DecoratorBase]]: 16 | try: 17 | # First try to load from core decorators 18 | module = importlib.import_module( 19 | f"prompt_decorators.decorators.core.{decorator_name.lower()}" 20 | ) 21 | return getattr(module, decorator_name) 22 | except (ImportError, AttributeError): 23 | try: 24 | # If not found in core, try to load from extension decorators 25 | module = importlib.import_module( 26 | f"prompt_decorators.decorators.extensions.{decorator_name.lower()}" 27 | ) 28 | return getattr(module, decorator_name) 29 | except (ImportError, AttributeError): 30 | return None 31 | 32 | return _load_decorator 33 | -------------------------------------------------------------------------------- /xnotes/git-push-command.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: ALWAYS use when making commits or managing git workflow to ensure consistent version control practices. This rule enforces conventional commit messages and proper staging/push procedures. 3 | globs: 4 | --- 5 | 6 | - Run the command `git add .` from the root of the workspace 7 | - Review all added changes that will be included in the commit 8 | - Create a git commit message without newline characters 9 | - Use format: `type(scope): brief description` 10 | - Keep titles brief and descriptive (max 72 chars) 11 | - Add two new lines after commit title without newline characters 12 | - Include diff summary of all changes 13 | - Add detailed explanations in commit body 14 | - End with signature "-bmadAi" 15 | - Push all to the remote of whatever the current branch is 16 | 17 | 18 | 19 | type(scope): brief description 20 | 21 | Changes made in this commit: 22 | - Modified files: [list of modified files] 23 | - Added files: [list of added files] 24 | - Deleted files: [list of deleted files] 25 | - Key changes: 26 | - [specific change 1] 27 | - [specific change 2] 28 | ... 29 | 30 | Detailed explanation of changes and reasoning... 31 | 32 | -bmadAi 33 | 34 | 35 | 36 | fixed stuff 37 | 38 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.integrations.mcp.install_claude_desktop.md: -------------------------------------------------------------------------------- 1 | # install_claude_desktop 2 | 3 | Installation helper for Claude Desktop integration. 4 | 5 | This script generates a configuration file for Claude Desktop that sets up 6 | the Prompt Decorators MCP integration. 7 | 8 | ## Functions 9 | 10 | ### `check_mcp_sdk` 11 | 12 | Check if the MCP SDK is installed. 13 | 14 | **Signature:** `check_mcp_sdk() -> bool` 15 | 16 | **Returns:** `bool` 17 | 18 | ### `create_config_file` 19 | 20 | Create a Claude Desktop configuration file. 21 | 22 | **Signature:** `create_config_file(output_path: Optional[str] = None, server_name: Optional[str] = None) -> None` 23 | 24 | **Parameters:** 25 | 26 | - `output_path`: `Optional` (default: `None`) 27 | - `server_name`: `Optional` (default: `None`) 28 | 29 | ### `find_package_path` 30 | 31 | Find the path to the prompt-decorators package. 32 | 33 | **Signature:** `find_package_path() -> str` 34 | 35 | **Returns:** `str` 36 | 37 | ### `find_python_executable` 38 | 39 | Find the path to the current Python executable. 40 | 41 | **Signature:** `find_python_executable() -> str` 42 | 43 | **Returns:** `str` 44 | 45 | ### `main` 46 | 47 | Main function to parse arguments and create the configuration file. 48 | 49 | **Signature:** `main() -> None` 50 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | license_file = LICENSE 3 | 4 | [bdist_wheel] 5 | universal = 1 6 | 7 | [flake8] 8 | max-line-length = 100 9 | exclude = .git,__pycache__,build,dist 10 | ignore = E203, W503 11 | 12 | [mypy] 13 | python_version = 3.11 14 | warn_return_any = True 15 | warn_unused_configs = True 16 | disallow_untyped_defs = True 17 | disallow_incomplete_defs = True 18 | check_untyped_defs = True 19 | disallow_untyped_decorators = True 20 | no_implicit_optional = True 21 | strict_optional = True 22 | 23 | [mypy.plugins.numpy.random] 24 | implicit_reexport = True 25 | 26 | [mypy-tests.*] 27 | disallow_untyped_defs = False 28 | disallow_incomplete_defs = False 29 | 30 | [tool:pytest] 31 | testpaths = tests 32 | python_files = test_*.py 33 | python_functions = test_* 34 | python_classes = Test* 35 | addopts = --cov=prompt_decorators --cov-report=term-missing --cov-report=xml 36 | 37 | [coverage:run] 38 | source = prompt_decorators 39 | omit = 40 | tests/* 41 | setup.py 42 | 43 | [coverage:report] 44 | exclude_lines = 45 | pragma: no cover 46 | def __repr__ 47 | raise NotImplementedError 48 | if __name__ == .__main__.: 49 | pass 50 | raise ImportError 51 | 52 | [isort] 53 | profile = black 54 | known_first_party = prompt_decorators 55 | known_third_party = pytest,numpy,pandas 56 | -------------------------------------------------------------------------------- /prompt_decorators/integrations/mcp/__init__.py: -------------------------------------------------------------------------------- 1 | """Model Context Protocol (MCP) integration for Prompt Decorators. 2 | 3 | This module provides integration between Prompt Decorators and the Model Context Protocol (MCP), 4 | allowing users to apply decorators through MCP tools. 5 | """ 6 | 7 | import logging 8 | import sys 9 | from typing import Any, Callable, Dict, List, Optional 10 | 11 | # Configure logging 12 | logging.basicConfig(level=logging.INFO, stream=sys.stderr) 13 | logger = logging.getLogger("prompt-decorators-mcp") 14 | 15 | # For compatibility with dynamic_decorators_module 16 | from prompt_decorators.dynamic_decorators_module import ( 17 | apply_dynamic_decorators, 18 | get_available_decorators, 19 | ) 20 | 21 | # Core exports 22 | from prompt_decorators.integrations.mcp.server import ( 23 | apply_decorators, 24 | create_decorated_prompt, 25 | get_decorator_details, 26 | list_decorators, 27 | mcp, 28 | run_server, 29 | ) 30 | 31 | __all__ = [ 32 | # Core functions 33 | "mcp", 34 | "run_server", 35 | # MCP tools 36 | "list_decorators", 37 | "get_decorator_details", 38 | "apply_decorators", 39 | "create_decorated_prompt", 40 | # For backward compatibility 41 | "get_available_decorators", 42 | "apply_dynamic_decorators", 43 | ] 44 | -------------------------------------------------------------------------------- /tests/test_dynamic_decorators_module.py: -------------------------------------------------------------------------------- 1 | """Tests for the dynamic_decorators_module.py file.""" 2 | 3 | from unittest.mock import patch 4 | 5 | import pytest 6 | 7 | from prompt_decorators.dynamic_decorators_module import ( 8 | DecoratorDefinition, 9 | apply_decorator, 10 | apply_dynamic_decorators, 11 | create_decorator, 12 | create_decorator_class, 13 | create_decorator_instance, 14 | extract_decorator_name, 15 | get_available_decorators, 16 | list_available_decorators, 17 | load_decorator_definitions, 18 | parse_decorator_text, 19 | register_decorator, 20 | transform_prompt, 21 | ) 22 | 23 | 24 | def test_transform_prompt(): 25 | """Test the transform_prompt function in dynamic_decorators_module.py.""" 26 | # Mock the core transform_prompt function 27 | with patch( 28 | "prompt_decorators.core.dynamic_decorator.transform_prompt" 29 | ) as mock_transform: 30 | # Set the return value 31 | mock_transform.return_value = "Transformed prompt" 32 | 33 | # Call our function 34 | prompt = "Test prompt" 35 | decorators = ["+++StepByStep", "+++Reasoning"] 36 | result = transform_prompt(prompt, decorators) 37 | 38 | # Check the result 39 | assert result == "Transformed prompt" 40 | 41 | # Verify the mock was called with the correct arguments 42 | mock_transform.assert_called_once_with(prompt, decorators) 43 | -------------------------------------------------------------------------------- /registry/core/reasoning/README.md: -------------------------------------------------------------------------------- 1 | # Reasoning Process Decorators 2 | 3 | These decorators modify how the AI approaches reasoning about a problem. They influence the cognitive strategies, logical frameworks, and thought processes used to analyze information and generate responses. 4 | 5 | ## Decorators in this category: 6 | 7 | - **Socratic** - Question-based exploration of the topic 8 | - **Debate** - Multiple viewpoint analysis 9 | - **FirstPrinciples** - Break down to fundamental truths 10 | - **RootCause** - Systematic analysis to identify underlying causes 11 | - **TreeOfThought** - Explore multiple reasoning branches 12 | - **Analogical** - Use analogies for reasoning and explanation 13 | - **ForcedAnalogy** - Compare concepts through specific analogical domains 14 | - **Inductive** - Pattern-based reasoning from specific to general 15 | - **Deductive** - Logical reasoning from general to specific 16 | - **Abductive** - Generate best explanations from limited information 17 | - **RedTeam** - Challenge assumptions with adversarial analysis 18 | - **BlindSpots** - Identify hidden assumptions and risks 19 | - **Contrarian** - Generate counterarguments to test perspectives 20 | - **NegativeSpace** - Uncover what isn't explicitly stated 21 | - **DeepDive** - Multi-layered, progressively deeper analysis 22 | 23 | Note: The **Reasoning** and **StepByStep** decorators from this category are part of the minimal core set and can be found in the minimal directory. 24 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.utils.md: -------------------------------------------------------------------------------- 1 | # utils 2 | 3 | Utility functions for prompt decorators. 4 | 5 | This package provides utility functions for working with prompt decorators. 6 | 7 | ## Public API 8 | 9 | This module exports the following components: 10 | 11 | - `extract_decorators_from_text`: Function - Extract decorator annotations from text 12 | - `replace_decorators_in_text`: Function - Replace decorator annotations in text 13 | 14 | ## Functions 15 | 16 | ### `extract_decorators_from_text` 17 | 18 | *Imported from `prompt_decorators.utils.string_utils`* 19 | 20 | Extract decorator annotations from text. 21 | 22 | Args: 23 | text: Text containing decorator annotations 24 | 25 | Returns: 26 | Tuple of (list of decorator dictionaries, clean text) 27 | 28 | **Signature:** `extract_decorators_from_text(text: str) -> Tuple[List[Dict[str, Any]], str]` 29 | 30 | **Parameters:** 31 | 32 | - `text`: `str` 33 | 34 | **Returns:** `Tuple` 35 | 36 | ### `replace_decorators_in_text` 37 | 38 | *Imported from `prompt_decorators.utils.string_utils`* 39 | 40 | Replace decorator annotations in text. 41 | 42 | Args: 43 | text: Text to modify 44 | decorators: List of decorator dictionaries 45 | 46 | Returns: 47 | Text with decorator annotations replaced 48 | 49 | **Signature:** `replace_decorators_in_text(text: str, decorators: List[Dict[str, Any]]) -> str` 50 | 51 | **Parameters:** 52 | 53 | - `text`: `str` 54 | - `decorators`: `List` 55 | 56 | **Returns:** `str` 57 | -------------------------------------------------------------------------------- /.cursor/rules/001-emoji-communication.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | description: Use emojis strategically in AI responses to enhance communication and user experience 3 | globs: null 4 | alwaysApply: true 5 | --- 6 | 7 | # Emoji Communication Guidelines 8 | 9 | ## Context 10 | - When responding to user queries in conversations 11 | - When emphasizing important points or status updates 12 | - When making technical communication more engaging and human-friendly 13 | 14 | ## Requirements 15 | - Use emojis purposefully to enhance meaning, but feel free to be creative and fun 16 | - Place emojis at the end of statements or sections 17 | - Maintain professional tone while surprising users with clever choices 18 | - Limit emoji usage to 1-2 per major section 19 | 20 | ## Examples 21 | 22 | ✅ "I've optimized your database queries 🏃‍♂️💨" 23 | ✅ "Your bug has been squashed 🥾🐛" 24 | ✅ "I've cleaned up the legacy code 🧹✨" 25 | ✅ "Fixed the performance issue 🐌➡️🐆" 26 | 27 | 28 | 29 | ❌ "Multiple 🎉 emojis 🎊 in 🌟 one message" 30 | ❌ "Using irrelevant emojis 🥑" 31 | ❌ "Placing the emoji in the middle ⭐️ of a sentence" 32 | 33 | 34 | ## Critical Rules 35 | - Never use more than one emoji per statement 36 | - Choose emojis that are both fun and contextually appropriate 37 | - Place emojis at the end of statements, not at the beginning or middle 38 | - Skip emoji usage when discussing serious issues or errors 39 | - Don't be afraid to tell a mini-story with your emoji choice 40 | -------------------------------------------------------------------------------- /scripts/check_demo_types.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Run strict type checking on the demo directory. 4 | 5 | This script applies the same strict mypy settings that are used in CI to validate 6 | the demo directory. It should be run manually before pushing changes to ensure 7 | the CI pipeline will pass. 8 | """ 9 | 10 | import os 11 | import subprocess 12 | import sys 13 | from pathlib import Path 14 | 15 | 16 | def main(): 17 | """Run mypy with strict settings on the demo directory.""" 18 | print("Running strict type checking on demo directory...") 19 | 20 | # Get the repo root directory (assuming script is in scripts/ directory) 21 | repo_root = Path(__file__).parent.parent 22 | 23 | # Change to the repo root directory 24 | os.chdir(repo_root) 25 | 26 | # Run mypy with the same settings as used in CI 27 | result = subprocess.run( 28 | ["poetry", "run", "mypy", "--warn-return-any", "demo/"], 29 | capture_output=True, 30 | text=True, 31 | ) 32 | 33 | # Print output 34 | if result.stdout: 35 | print(result.stdout) 36 | 37 | if result.stderr: 38 | print(result.stderr, file=sys.stderr) 39 | 40 | # Return the exit code 41 | if result.returncode != 0: 42 | print("Type checking failed! Please fix the issues before pushing.") 43 | return 1 44 | else: 45 | print("Type checking passed successfully.") 46 | return 0 47 | 48 | 49 | if __name__ == "__main__": 50 | sys.exit(main()) 51 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve the Prompt Decorators framework 4 | title: '[BUG] ' 5 | labels: bug 6 | assignees: '' 7 | --- 8 | 9 | ## Bug Description 10 | 11 | A clear and concise description of what the bug is. 12 | 13 | ## Steps To Reproduce 14 | 15 | Steps to reproduce the behavior: 16 | 1. Use the following code: 17 | ```python 18 | # Minimal, reproducible example 19 | from prompt_decorators import ... 20 | 21 | # Code that causes the issue 22 | ... 23 | ``` 24 | 25 | 2. Additional steps: 26 | - ... 27 | - ... 28 | 29 | ## Expected Behavior 30 | 31 | A clear and concise description of what you expected to happen. 32 | 33 | ## Actual Behavior 34 | 35 | A clear and concise description of what actually happened. Include error messages or stack traces if applicable. 36 | 37 | ## Environment 38 | 39 | - **Operating System**: [e.g. Ubuntu 22.04, Windows 11, macOS 13.0] 40 | - **Python version**: [e.g. 3.11.2] 41 | - **Prompt Decorators version**: [e.g. 0.1.0] 42 | - **Relevant packages and versions**: [e.g. langchain 0.0.245] 43 | 44 | ## Additional Context 45 | 46 | Add any other context about the problem here, like: 47 | - Special configurations 48 | - Related issues 49 | - Possible causes 50 | - Link to code repository (if public) 51 | 52 | ## Possible Solution 53 | 54 | If you have ideas on how to solve this issue, please share them here. 55 | 56 | ## Screenshots 57 | 58 | If applicable, add screenshots to help explain your problem. 59 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.config.md: -------------------------------------------------------------------------------- 1 | # config 2 | 3 | Configuration settings for prompt decorators package. 4 | 5 | ## Module Variables 6 | 7 | ### `OUTPUT_PATH` 8 | 9 | Type: `PosixPath` 10 | 11 | Value: `PosixPath('/Users/danielbentes/prompt-decorators/prompt_decorators/decorators')` 12 | 13 | ### `PATHS` 14 | 15 | Type: `dict` 16 | 17 | Value: `{'registry': {'core': PosixPath('/Users/danielbentes/prompt-decorators/registry/core'), 'extensions': PosixPath('/Users/danielbentes/prompt-decorators/registry/extensions')}, 'output': {'code': {'core': PosixPath('/Users/danielbentes/prompt-decorators/prompt_decorators/decorators/core'), 'extensions': PosixPath('/Users/danielbentes/prompt-decorators/prompt_decorators/decorators/extensions')}, 'tests': {'core': PosixPath('/Users/danielbentes/prompt-decorators/tests/auto/core'), 'extensions': PosixPath('/Users/danielbentes/prompt-decorators/tests/auto/extensions')}}, 'templates': PosixPath('/Users/danielbentes/prompt-decorators/prompt_decorators/generator/templates')}` 18 | 19 | ### `REGISTRY_PATH` 20 | 21 | Type: `PosixPath` 22 | 23 | Value: `PosixPath('/Users/danielbentes/prompt-decorators/registry')` 24 | 25 | ### `REPO_ROOT` 26 | 27 | Type: `PosixPath` 28 | 29 | Value: `PosixPath('/Users/danielbentes/prompt-decorators')` 30 | 31 | ### `TEST_PATH` 32 | 33 | Type: `PosixPath` 34 | 35 | Value: `PosixPath('/Users/danielbentes/prompt-decorators/tests')` 36 | 37 | ## Functions 38 | 39 | ### `ensure_paths_exist` 40 | 41 | Ensure all required paths exist. 42 | 43 | **Signature:** `ensure_paths_exist() -> None` 44 | -------------------------------------------------------------------------------- /schemas/simplified-decorator.schema.yaml: -------------------------------------------------------------------------------- 1 | # Decorator YAML Format Specification v1.0 2 | 3 | # File-level metadata 4 | version: 1.0.0 # Version of this file format specification 5 | author: # Information about the author of these decorators 6 | name: string # [Required] Author name 7 | email: string # [Optional] Author email 8 | url: string # [Optional] Author website 9 | 10 | # Main decorator definitions 11 | decorators: # [Required] List of decorator definitions 12 | - name: string # [Required] Name of the decorator (without +++) 13 | category: string # [Required] Category the decorator belongs to 14 | description: string # [Required] Detailed description of what the decorator does 15 | 16 | parameters: # [Optional] List of parameters this decorator accepts 17 | - name: string # [Required] Parameter name 18 | type: string # [Required] Parameter type (enum, string, boolean, number, array) 19 | description: string # [Required] Description of the parameter 20 | values: [string, ...] # [Required for enum type] List of possible values 21 | default: string|number # [Optional] Default value if not specified 22 | required: boolean # [Optional] Whether parameter is required (default: false) 23 | 24 | example: string # [Required] Example usage of the decorator in a prompt 25 | 26 | # Optional additional fields 27 | conflicts_with: [string, ...] # [Optional] List of decorator names this conflicts with 28 | requires: [string, ...] # [Optional] List of decorator names this requires 29 | notes: string # [Optional] Additional implementation notes 30 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.core.parser.md: -------------------------------------------------------------------------------- 1 | # parser 2 | 3 | Parser module for extracting decorators from prompts. 4 | 5 | This module provides functionality to parse and extract decorator annotations 6 | from prompt text using the +++ syntax. 7 | 8 | ## Classes 9 | 10 | ### `DecoratorParser` 11 | 12 | Parser for extracting decorator annotations from prompts. 13 | 14 | This class handles the parsing of decorator annotations in the format: 15 | +++DecoratorName(param1=value1, param2=value2) 16 | 17 | #### Attributes 18 | 19 | - `DECORATOR_PATTERN`: `str` = `'\\+\\+\\+([A-Za-z0-9_]+)(?:\\(([^)]*)\\))?'` 20 | 21 | #### Methods 22 | 23 | ##### `__init__` 24 | 25 | Initialize the decorator parser. 26 | 27 | Args: 28 | registry: Optional decorator registry to use for creating decorators. If not provided, the global registry will be used. 29 | 30 | **Signature:** `__init__(self, registry: Optional[prompt_decorators.core.registry.DecoratorRegistry] = None)` 31 | 32 | **Parameters:** 33 | 34 | - `registry`: `Optional` (default: `None`) 35 | 36 | ##### `extract_decorators` 37 | 38 | Extract decorator annotations from a prompt. 39 | 40 | This method extracts all decorator annotations from the prompt text, 41 | creates decorator instances for each annotation, and returns both the 42 | list of decorators and the cleaned prompt text. 43 | 44 | Args: 45 | prompt: The prompt text to parse 46 | 47 | Returns: 48 | A tuple containing: 49 | - A list of decorator instances 50 | - The prompt text with decorator annotations removed 51 | 52 | **Signature:** `extract_decorators(self, prompt: str) -> Tuple[List[prompt_decorators.core.base.DecoratorBase], str]` 53 | 54 | **Parameters:** 55 | 56 | - `prompt`: `str` 57 | 58 | **Returns:** `Tuple` 59 | -------------------------------------------------------------------------------- /prompt_decorators/config.py: -------------------------------------------------------------------------------- 1 | """Configuration settings for prompt decorators package.""" 2 | 3 | from pathlib import Path 4 | from typing import Any, Dict, Union 5 | 6 | # Base paths 7 | REPO_ROOT = Path(__file__).parent.parent 8 | REGISTRY_PATH = REPO_ROOT / "registry" 9 | OUTPUT_PATH = REPO_ROOT / "prompt_decorators" / "decorators" 10 | TEST_PATH = REPO_ROOT / "tests" 11 | 12 | # Registry paths 13 | PATHS: Dict[str, Any] = { 14 | "registry": { 15 | "core": REGISTRY_PATH / "core", 16 | "extensions": REGISTRY_PATH / "extensions", 17 | }, 18 | "output": { 19 | "code": { 20 | "core": OUTPUT_PATH / "core", 21 | "extensions": OUTPUT_PATH / "extensions", 22 | }, 23 | "tests": { 24 | "core": TEST_PATH / "auto" / "core", 25 | "extensions": TEST_PATH / "auto" / "extensions", 26 | }, 27 | }, 28 | "templates": REPO_ROOT / "prompt_decorators" / "generator" / "templates", 29 | } 30 | 31 | 32 | # Function to ensure all required paths exist 33 | def ensure_paths_exist() -> None: 34 | """Ensure all required paths exist.""" 35 | output_paths = PATHS["output"] 36 | if isinstance(output_paths, dict): 37 | for path_category in output_paths.values(): 38 | if isinstance(path_category, dict): 39 | for path in path_category.values(): 40 | if isinstance(path, Path): 41 | path.mkdir(parents=True, exist_ok=True) 42 | 43 | test_paths = PATHS["output"].get("tests", {}) 44 | if isinstance(test_paths, dict): 45 | for path in test_paths.values(): 46 | if isinstance(path, Path): 47 | init_file = path / "__init__.py" 48 | if not init_file.exists(): 49 | init_file.touch() 50 | -------------------------------------------------------------------------------- /docs/integrations/index.md: -------------------------------------------------------------------------------- 1 | # Integrations 2 | 3 | Prompt Decorators can be integrated with various systems and platforms to enhance their capabilities. This section documents the available integrations and how to use them. 4 | 5 | ## Available Integrations 6 | 7 | ### Model Context Protocol (MCP) 8 | 9 | The [Model Context Protocol (MCP)](./mcp.md) integration allows you to expose prompt decorators as MCP tools, which can be used by MCP-compatible clients like Claude Desktop. 10 | 11 | - [MCP Overview](./mcp.md) - General overview of the MCP integration 12 | - [MCP Server](./mcp/server.md) - Documentation for the MCP server implementation 13 | - [Claude Desktop Integration](./mcp/claude_desktop.md) - How to use prompt decorators with Claude Desktop 14 | 15 | ## Coming Soon 16 | 17 | We're working on the following integrations: 18 | 19 | - **Langchain**: Integration with the Langchain framework 20 | - **Ollama**: Integration with the Ollama local LLM platform 21 | - **FastAPI**: Expose prompt decorators as a REST API 22 | - **LlamaIndex**: Integration with the LlamaIndex framework 23 | 24 | ## Why Use Integrations? 25 | 26 | Integrations extend the capabilities of Prompt Decorators by making them available in different contexts: 27 | 28 | 1. **Enhanced Accessibility**: Integrate prompt decorators into your existing workflows and tools. 29 | 2. **Standardized Communication**: Use common protocols and interfaces to interact with prompt decorators. 30 | 3. **Expanded Functionality**: Combine the power of prompt decorators with other systems. 31 | 4. **User-Friendly Interfaces**: Make prompt decorators available through intuitive interfaces. 32 | 33 | ## Creating Custom Integrations 34 | 35 | If you want to create a custom integration for Prompt Decorators, see the [Extension Development](../tutorials/extension_development.md) tutorial for guidance. 36 | -------------------------------------------------------------------------------- /.cursor/rules/050-careful-code-modification.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | description: ENSURE careful modifications WHEN changing code TO prevent breakage 3 | globs: **/*.py 4 | --- 5 | 6 | # Careful Code Modification 7 | 8 | 1.0.0 9 | 10 | ## Context 11 | - When modifying existing code in this codebase 12 | - When fixing bugs or implementing new features 13 | - When the codebase is fragile or has complex dependencies 14 | 15 | ## Requirements 16 | - Make surgical, precise modifications targeting only the specific issue 17 | - Implement proper validation procedures before and after changes 18 | - Consider the scope and potential side effects of all changes 19 | - Ensure changes are appropriate for the sensitivity level of the codebase 20 | - Add thorough tests for any modifications made 21 | - Document changes clearly with comments explaining the rationale 22 | 23 | ## Examples 24 | 25 | 26 | # Good: Targeted fix with validation 27 | def fix_calculation_error(data): 28 | # Validate input before processing 29 | if not isinstance(data, dict) or 'value' not in data: 30 | raise ValueError("Invalid data format") 31 | 32 | # Fix specific calculation issue only 33 | corrected_value = data['value'] * 1.05 # Apply 5% correction 34 | 35 | # Return with minimal changes to data structure 36 | result = data.copy() 37 | result['value'] = corrected_value 38 | return result 39 | 40 | 41 | 42 | # Bad: Overly broad changes without validation 43 | def fix_calculation_error(data): 44 | # Completely restructuring data format unnecessarily 45 | new_data = {} 46 | for key, value in data.items(): 47 | if key == 'value': 48 | new_data[key] = value * 1.05 49 | else: 50 | new_data[f"modified_{key}"] = process_data(value) 51 | 52 | return new_data # Returns completely different structure 53 | 54 | -------------------------------------------------------------------------------- /demo/main.py: -------------------------------------------------------------------------------- 1 | """ 2 | Main entry point for the OpenAI Prompt Decorator Demo. 3 | 4 | This module integrates all the example modules and provides a unified CLI interface. 5 | """ 6 | 7 | from typing import Optional 8 | 9 | import typer 10 | 11 | from demo.dynamic_openai_demo import app as openai_app 12 | from demo.examples.advanced import app as advanced_app 13 | from demo.examples.basic import app as basic_app 14 | from demo.examples.domain_specific import app as domain_app 15 | 16 | # Use absolute imports rather than relative imports 17 | from demo.utils.logging import log_info 18 | 19 | app = typer.Typer( 20 | help="OpenAI Prompt Decorator Demo - Showcase the power of prompt decorators with OpenAI" 21 | ) 22 | 23 | # Add all sub-applications 24 | app.add_typer( 25 | openai_app, name="custom", help="Run custom prompts with decorators of your choice" 26 | ) 27 | app.add_typer(basic_app, name="basic", help="Basic decorator examples") 28 | app.add_typer( 29 | advanced_app, name="advanced", help="Advanced decorator composition examples" 30 | ) 31 | app.add_typer(domain_app, name="domain", help="Domain-specific decorator examples") 32 | 33 | 34 | @app.callback() 35 | def main() -> None: 36 | """ 37 | OpenAI Prompt Decorator Demo - Showcase the power of prompt decorators with OpenAI. 38 | 39 | This application demonstrates how to use prompt decorators with the OpenAI API 40 | to enhance LLM outputs across various use cases. The demo includes basic examples, 41 | advanced compositions, and domain-specific applications. 42 | """ 43 | log_info("Starting Prompt Decorators Demo") 44 | 45 | 46 | @app.command() 47 | def version() -> None: 48 | """ 49 | Show version information for the demo. 50 | """ 51 | log_info("Prompt Decorators Demo v1.0.0") 52 | log_info( 53 | "For more information, visit: https://github.com/synaptiai/prompt-decorators" 54 | ) 55 | 56 | 57 | if __name__ == "__main__": 58 | app() 59 | -------------------------------------------------------------------------------- /tests/examples/README.md: -------------------------------------------------------------------------------- 1 | # Prompt Decorator Test Examples 2 | 3 | This directory contains example scripts that demonstrate how to use various prompt decorators with actual AI models and test their behavior in real-world scenarios. 4 | 5 | ## Running the Examples 6 | 7 | Most examples require an API key for the AI model service being used. Set the appropriate environment variables before running the examples: 8 | 9 | ```bash 10 | # For OpenAI models (gpt-4, gpt-4o) 11 | export OPENAI_API_KEY="your-api-key-here" 12 | 13 | # For Anthropic models (Claude) 14 | export ANTHROPIC_API_KEY="your-api-key-here" 15 | 16 | # To enable tests with gpt-4o (optional) 17 | export USE_GPT4="true" 18 | ``` 19 | 20 | Then run the example scripts: 21 | 22 | ```bash 23 | python tests/examples/tree_of_thought_example.py 24 | python tests/examples/comparison_example.py 25 | ``` 26 | 27 | ## Available Examples 28 | 29 | ### Reasoning Decorators 30 | - `tree_of_thought_example.py` - Demonstrates the TreeOfThought decorator with various branching configurations 31 | 32 | ### Structure Decorators 33 | - `comparison_example.py` - Demonstrates the Comparison decorator with different formats and aspect configurations 34 | 35 | ### Tone Decorators 36 | - (Examples coming soon) 37 | 38 | ### Verification Decorators 39 | - (Examples coming soon) 40 | 41 | ## Creating New Examples 42 | 43 | When creating new test examples, follow these guidelines: 44 | 45 | 1. Name the file according to the decorator being tested (`decorator_name_example.py`) 46 | 2. Include multiple parameter configurations to show the decorator's flexibility 47 | 3. Test with at least 2-3 different prompts to demonstrate behavior across contexts 48 | 4. Include clear output formatting to make results easy to interpret 49 | 5. Add appropriate error handling and environment checks 50 | 6. Update this README when adding a new example 51 | 52 | Each example should be self-contained and well-documented to serve as a learning resource. 53 | -------------------------------------------------------------------------------- /prompt_decorators/integrations/mcp/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Command-line entry point for running the Prompt Decorators MCP server. 3 | 4 | Usage: 5 | python -m prompt_decorators.integrations.mcp [`--host HOST`] [`--port PORT`] [`--verbose`] 6 | """ 7 | 8 | import argparse 9 | import logging 10 | import sys 11 | 12 | 13 | def main() -> None: 14 | """Run the Prompt Decorators MCP server.""" 15 | parser = argparse.ArgumentParser(description="Run the Prompt Decorators MCP server") 16 | parser.add_argument("--verbose", action="store_true", help="Enable verbose logging") 17 | parser.add_argument("--host", type=str, default="0.0.0.0", help="Host to bind to") 18 | parser.add_argument("--port", type=int, default=5000, help="Port to listen on") 19 | args = parser.parse_args() 20 | 21 | # Configure logging level based on verbose flag 22 | log_level = logging.DEBUG if args.verbose else logging.INFO 23 | logging.basicConfig( 24 | level=log_level, 25 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", 26 | stream=sys.stderr, 27 | ) 28 | 29 | logger = logging.getLogger("prompt-decorators-main") 30 | logger.info(f"Starting Prompt Decorators MCP server on {args.host}:{args.port}") 31 | 32 | try: 33 | # Import and run the server 34 | from prompt_decorators.integrations.mcp.server import MCP_AVAILABLE, run_server 35 | 36 | if not MCP_AVAILABLE: 37 | logger.error("MCP SDK not installed. Please install with: pip install mcp") 38 | sys.exit(1) 39 | 40 | run_server(host=args.host, port=args.port) 41 | except ImportError as e: 42 | logger.error(f"Failed to import server: {e}") 43 | logger.error("Please ensure the MCP SDK is installed: pip install mcp") 44 | sys.exit(1) 45 | except Exception as e: 46 | logger.error(f"Error running MCP server: {e}", exc_info=True) 47 | sys.exit(1) 48 | 49 | 50 | if __name__ == "__main__": 51 | main() 52 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for the Prompt Decorators framework 4 | title: '[FEATURE] ' 5 | labels: enhancement 6 | assignees: '' 7 | --- 8 | 9 | ## Feature Description 10 | 11 | A clear and concise description of the feature you'd like to see added. 12 | 13 | ## Use Case 14 | 15 | Describe the specific use case or problem this feature would address. Include examples of how you would use this feature in practice. 16 | 17 | ## Proposed Solution 18 | 19 | A clear and concise description of what you want to happen. If you have specific ideas about implementation details, please share them here. 20 | 21 | ## Example Code 22 | 23 | ```python 24 | # An example of how you might envision using this feature 25 | from prompt_decorators import ProposedDecorator 26 | 27 | decorator = ProposedDecorator(param="value") 28 | result = decorator("Example prompt") 29 | 30 | # Expected result: 31 | # "Decorated prompt with new feature applied" 32 | ``` 33 | 34 | ## Alternatives Considered 35 | 36 | Describe any alternative solutions or features you've considered. How are you currently working around this limitation? 37 | 38 | ## Additional Context 39 | 40 | Add any other context, screenshots, diagrams, or examples related to the feature request. 41 | 42 | ## Impact Assessment 43 | 44 | How would this feature benefit: 45 | - You specifically? 46 | - The broader community? 47 | - Specific use cases or domains? 48 | 49 | ## Feature Complexity (optional) 50 | 51 | Your assessment of how complex this feature might be to implement: 52 | - [ ] Simple (minor enhancement, likely straightforward to implement) 53 | - [ ] Moderate (substantial new functionality, but building on existing patterns) 54 | - [ ] Complex (significant architectural changes or entirely new systems) 55 | 56 | ## Would you be willing to contribute this feature? 57 | 58 | - [ ] Yes, I'm interested in implementing this myself with guidance 59 | - [ ] Maybe, but I would need significant help 60 | - [ ] No, I don't have the capacity to work on this 61 | -------------------------------------------------------------------------------- /scripts/README.md: -------------------------------------------------------------------------------- 1 | # Prompt Decorators Script Tools 2 | 3 | This directory contains utility scripts for working with the prompt decorators registry and codebase. The scripts help with validation, code generation, and test generation. 4 | 5 | ## Recommended Scripts 6 | 7 | ### 📌 `registry_tools.py` (Unified Tool) 8 | 9 | This is the **recommended** tool for all registry-related operations. It provides a unified interface for validation, code generation, and test generation. 10 | 11 | ```bash 12 | # Show available commands 13 | python scripts/registry_tools.py --help 14 | 15 | # Validate the registry 16 | python scripts/registry_tools.py validate 17 | 18 | # Generate Python code 19 | python scripts/registry_tools.py generate-code 20 | 21 | # Generate tests 22 | python scripts/registry_tools.py generate-tests 23 | 24 | # Run all operations in sequence (validate, generate code, generate tests) 25 | python scripts/registry_tools.py all 26 | ``` 27 | 28 | ## Development Scripts 29 | 30 | These scripts may be useful for development purposes: 31 | 32 | - `run_tests.py` - Helper script for running tests 33 | 34 | ## Contributing 35 | 36 | When adding new functionality: 37 | 38 | 1. Consider adding it to the unified `registry_tools.py` script rather than creating new scripts 39 | 2. Ensure the new functionality is well-documented with docstrings and command-line help 40 | 3. Add appropriate error handling and logging 41 | 4. Follow the existing code style and patterns 42 | 43 | ## Workflow 44 | 45 | The typical workflow for working with the prompt decorators registry is: 46 | 47 | 1. Make changes to JSON files in the `registry/` directory 48 | 2. Run `python scripts/registry_tools.py validate` to validate the registry 49 | 3. Run `python scripts/registry_tools.py generate-code` to generate Python code 50 | 4. Run `python scripts/registry_tools.py generate-tests` to generate tests 51 | 5. Run tests to ensure everything works correctly: `python -m pytest tests/auto -v` 52 | 53 | For convenience, you can run all the steps at once with `python scripts/registry_tools.py all`. 54 | -------------------------------------------------------------------------------- /.cursor/rules/060-coding-patterns.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | description: FOLLOW coding patterns WHEN writing code TO maintain codebase quality 3 | globs: **/*.py 4 | --- 5 | 6 | # Coding Pattern Preferences 7 | 8 | 1.0.0 9 | 10 | ## Context 11 | - When writing new code or modifying existing code 12 | - When implementing features or fixing bugs 13 | - When refactoring or optimizing code 14 | 15 | ## Requirements 16 | - Prefer simple solutions over complex ones 17 | - Avoid code duplication by checking for similar functionality elsewhere in the codebase 18 | - Ensure code complies with pre-commit requirements 19 | - Only make changes that are explicitly requested or well understood 20 | - Exhaust all options within existing implementation before introducing new patterns 21 | - Remove old implementations when introducing new ones to avoid duplicate logic 22 | - Keep codebase clean and organized 23 | - Avoid writing scripts in files, especially for one-time operations 24 | - Refactor files exceeding 200-300 lines of code 25 | - Use mocking data only for tests, never for dev or prod environments 26 | - Never add stubbing or fake data patterns affecting dev or prod environments 27 | - Never overwrite env files without explicit confirmation 28 | 29 | ## Examples 30 | 31 | 32 | # Good: Simple solution with no duplication 33 | def calculate_total(items): 34 | """Calculate total price of items using existing utility function.""" 35 | from utils.pricing import apply_discount 36 | 37 | base_total = sum(item.price for item in items) 38 | return apply_discount(base_total) # Reusing existing functionality 39 | 40 | 41 | 42 | # Bad: Duplicating existing functionality 43 | def calculate_total(items): 44 | """Calculate total with duplicated discount logic.""" 45 | base_total = sum(item.price for item in items) 46 | 47 | # Reimplementing discount logic that already exists in utils.pricing 48 | if base_total > 100: 49 | return base_total * 0.9 50 | else: 51 | return base_total 52 | 53 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com for more information 2 | # See https://pre-commit.com/hooks.html for more hooks 3 | repos: 4 | - repo: https://github.com/pre-commit/pre-commit-hooks 5 | rev: v4.5.0 6 | hooks: 7 | - id: trailing-whitespace 8 | - id: end-of-file-fixer 9 | - id: check-yaml 10 | - id: check-json 11 | - id: check-added-large-files 12 | - id: check-merge-conflict 13 | - id: detect-private-key 14 | - id: debug-statements 15 | 16 | - repo: https://github.com/psf/black 17 | rev: 23.11.0 18 | hooks: 19 | - id: black 20 | language_version: python3 21 | 22 | - repo: https://github.com/charliermarsh/ruff-pre-commit 23 | rev: v0.0.262 24 | hooks: 25 | - id: ruff 26 | stages: [manual] # This will prevent it from running automatically 27 | 28 | - repo: https://github.com/pycqa/isort 29 | rev: 5.12.0 30 | hooks: 31 | - id: isort 32 | args: ["--profile", "black"] 33 | 34 | - repo: https://github.com/python-poetry/poetry 35 | rev: 1.7.0 36 | hooks: 37 | - id: poetry-check 38 | - id: poetry-lock 39 | stages: [manual] # This will prevent it from running automatically in CI 40 | 41 | - repo: local 42 | hooks: 43 | - id: mypy 44 | name: mypy 45 | entry: mypy 46 | language: python 47 | types: [python] 48 | exclude: ^(docs/|examples/|scripts/|tests/|demo/) 49 | args: ["--config-file=mypy.ini"] 50 | 51 | - id: pytest 52 | name: pytest 53 | entry: python -m pytest 54 | language: python 55 | pass_filenames: false 56 | always_run: true 57 | additional_dependencies: [pytest, pydantic>=2.0.0, jsonschema>=4.0.0, importlib-metadata>=6.0.0, markdown>=3.7] 58 | 59 | - id: check-docstrings 60 | name: check-docstrings 61 | entry: python scripts/standardize_docstrings.py prompt_decorators --check 62 | language: system 63 | pass_filenames: false 64 | always_run: true 65 | -------------------------------------------------------------------------------- /mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | python_version = 3.11 3 | warn_return_any = True 4 | warn_unused_configs = True 5 | disallow_untyped_defs = True 6 | disallow_incomplete_defs = True 7 | ignore_missing_imports = True 8 | 9 | # Note: The demo directory is excluded from automated MyPy checks in .pre-commit-config.yaml 10 | # but should be checked manually using scripts/check_demo_types.py before pushing. 11 | # This script applies the same strict validation as CI. 12 | 13 | # Ignore generated code 14 | [mypy-prompt_decorators.decorators.generated.*] 15 | ignore_errors = True 16 | 17 | # Ignore specific import error in decorators/__init__.py 18 | [mypy-prompt_decorators.decorators.__init__] 19 | ignore_errors = True 20 | 21 | # Less strict checking for test files 22 | [mypy-tests.*] 23 | disallow_untyped_defs = False 24 | disallow_incomplete_defs = False 25 | 26 | # Specific modules with known issues 27 | [mypy-prompt_decorators.utils.telemetry] 28 | ignore_errors = True 29 | 30 | [mypy-prompt_decorators.utils.plugins] 31 | ignore_errors = True 32 | 33 | [mypy-prompt_decorators.utils.doc_gen] 34 | ignore_errors = True 35 | 36 | [mypy-prompt_decorators.generator.test_gen] 37 | ignore_errors = True 38 | 39 | [mypy-prompt_decorators.core.validation] 40 | ignore_errors = True 41 | 42 | [mypy-prompt_decorators.core.model_specific] 43 | ignore_errors = True 44 | 45 | [mypy-prompt_decorators.core.request] 46 | ignore_errors = True 47 | 48 | [mypy-prompt_decorators.utils.discovery] 49 | ignore_errors = True 50 | 51 | [mypy-prompt_decorators.utils.model_detection] 52 | ignore_errors = True 53 | 54 | [mypy-prompt_decorators.utils.cache] 55 | ignore_errors = True 56 | 57 | [mypy-prompt_decorators.utils.compatibility] 58 | ignore_errors = True 59 | 60 | [mypy-prompt_decorators.utils.json_loader] 61 | ignore_errors = True 62 | 63 | [mypy-prompt_decorators.utils.factory] 64 | ignore_errors = True 65 | 66 | [mypy-prompt_decorators.generator.registry] 67 | ignore_errors = True 68 | 69 | [mypy-prompt_decorators.generator.code_gen] 70 | ignore_errors = True 71 | 72 | [mypy-prompt_decorators.core.base] 73 | ignore_errors = True 74 | -------------------------------------------------------------------------------- /docs/api/decorators/Version.md: -------------------------------------------------------------------------------- 1 | # Version Decorator 2 | 3 | Specifies the version of the Prompt Decorators standard to use. This decorator must be the first in any sequence when used, ensuring proper interpretation of decorators according to the specified standard version. 4 | 5 | **Category**: Minimal 6 | 7 | ## Parameters 8 | 9 | | Parameter | Type | Description | Default | 10 | |-----------|------|-------------|--------| 11 | | `standard` | `string` | The semantic version of the Prompt Decorators standard to use | `1.0.0` | 12 | 13 | ## Examples 14 | 15 | ### Specify standard version for compatibility 16 | 17 | ``` 18 | +++Version(standard=1.0.0) 19 | +++Reasoning(depth=comprehensive) 20 | Explain quantum entanglement 21 | ``` 22 | 23 | Ensures decorators are interpreted according to version 1.0.0 of the standard 24 | 25 | ## Implementation Guidance 26 | 27 | ### Version specification 28 | 29 | **Original Prompt:** 30 | ``` 31 | +++Reasoning(depth=comprehensive) 32 | Explain quantum entanglement 33 | ``` 34 | 35 | **Transformed Prompt:** 36 | ``` 37 | The following prompt uses Prompt Decorators standard version 1.0.0. Please interpret all decorators according to this version's specifications. 38 | 39 | +++Reasoning(depth=comprehensive) 40 | Explain quantum entanglement 41 | ``` 42 | 43 | ## Transformation Details 44 | 45 | **Base Instruction:** The following prompt uses Prompt Decorators standard version {standard}. Please interpret all decorators according to this version's specifications. 46 | 47 | **Placement:** prepend 48 | 49 | **Composition Behavior:** override 50 | 51 | **Parameter Effects:** 52 | 53 | - `standard`: 54 | - Format: The following prompt uses Prompt Decorators standard version {value}. Please interpret all decorators according to this version's specifications. 55 | 56 | ## Compatibility 57 | 58 | - **Requires**: None 59 | - **Conflicts**: None 60 | - **Compatible Models**: gpt-4o, gpt-4-turbo 61 | - **Minimum Standard Version**: 1.0.0 62 | 63 | ## Related Decorators 64 | 65 | - **All**: Requires Version The Version decorator should always be the first in any sequence when used 66 | -------------------------------------------------------------------------------- /prompt_decorators/__init__.py: -------------------------------------------------------------------------------- 1 | """Prompt Decorators - A framework for dynamic prompt modification. 2 | 3 | This module provides decorators that can be applied to prompts 4 | to enhance, modify, or transform them before they are sent to LLMs. 5 | """ 6 | 7 | import logging 8 | from typing import Any, Dict, List, Optional, Tuple, Union 9 | 10 | # Set up logging 11 | logging.basicConfig(level=logging.INFO) 12 | logger = logging.getLogger(__name__) 13 | 14 | # Import the core elements 15 | from prompt_decorators.core.base import DecoratorBase, DecoratorParameter 16 | from prompt_decorators.core.dynamic_decorator import DynamicDecorator 17 | 18 | # Import the dynamic decorators module (replacing the generated decorators) 19 | from prompt_decorators.dynamic_decorators_module import ( 20 | DecoratorDefinition, 21 | apply_decorator, 22 | apply_dynamic_decorators, 23 | create_decorator_class, 24 | create_decorator_instance, 25 | extract_decorator_name, 26 | get_available_decorators, 27 | load_decorator_definitions, 28 | parse_decorator_text, 29 | register_decorator, 30 | ) 31 | 32 | # Import schemas 33 | from prompt_decorators.schemas.decorator_schema import DecoratorSchema, ParameterSchema 34 | 35 | # Import utilities 36 | from prompt_decorators.utils.string_utils import ( 37 | extract_decorators_from_text, 38 | replace_decorators_in_text, 39 | ) 40 | 41 | # Version information 42 | __version__ = "0.3.1" 43 | 44 | # Public API 45 | __all__ = [ 46 | # Core classes 47 | "DecoratorBase", 48 | "DecoratorParameter", 49 | "DynamicDecorator", 50 | # Dynamic decorator module functions 51 | "load_decorator_definitions", 52 | "get_available_decorators", 53 | "create_decorator_instance", 54 | "create_decorator_class", 55 | "apply_dynamic_decorators", 56 | "apply_decorator", 57 | "register_decorator", 58 | "extract_decorator_name", 59 | "parse_decorator_text", 60 | "DecoratorDefinition", 61 | # Schemas 62 | "DecoratorSchema", 63 | "ParameterSchema", 64 | # Utilities 65 | "extract_decorators_from_text", 66 | "replace_decorators_in_text", 67 | ] 68 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # Pull Request 2 | 3 | ## Description 4 | 5 | Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. 6 | 7 | Fixes # (issue number) 8 | 9 | ## Type of Change 10 | 11 | Please delete options that are not relevant. 12 | 13 | - [ ] Bug fix (non-breaking change which fixes an issue) 14 | - [ ] New feature (non-breaking change which adds functionality) 15 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 16 | - [ ] Documentation update 17 | - [ ] Performance improvement 18 | - [ ] Refactoring (no functional changes) 19 | - [ ] Code style update 20 | - [ ] Tests 21 | - [ ] Build/CI related changes 22 | - [ ] Other (please describe): 23 | 24 | ## Checklist 25 | 26 | - [ ] My code follows the style guidelines of this project 27 | - [ ] I have performed a self-review of my own code 28 | - [ ] I have commented my code, particularly in hard-to-understand areas 29 | - [ ] I have made corresponding changes to the documentation 30 | - [ ] My changes generate no new warnings 31 | - [ ] I have added tests that prove my fix is effective or that my feature works 32 | - [ ] New and existing unit tests pass locally with my changes 33 | - [ ] Any dependent changes have been merged and published in downstream modules 34 | - [ ] I have updated the CHANGELOG.md file (for non-trivial changes) 35 | - [ ] I have updated the version number (if applicable) 36 | 37 | ## For New Decorators 38 | 39 | If you're adding a new decorator, please ensure: 40 | 41 | - [ ] The decorator inherits from BaseDecorator 42 | - [ ] It includes complete type annotations 43 | - [ ] It has comprehensive docstrings 44 | - [ ] It includes adequate test coverage 45 | - [ ] You've added a JSON registry definition 46 | - [ ] You've included examples demonstrating usage 47 | 48 | ## Additional Context 49 | 50 | Add any other context about the pull request here. 51 | 52 | ## Screenshots 53 | 54 | If applicable, add screenshots to help explain your changes. 55 | 56 | ## Reviewer Notes 57 | 58 | Any notes for the reviewer to help them understand your implementation decisions or specific areas to focus on in their review. 59 | -------------------------------------------------------------------------------- /scripts/standardize_imports.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | This script uses isort to sort and format imports according to the configuration 4 | in pyproject.toml. 5 | """ 6 | 7 | import argparse 8 | import subprocess 9 | import sys 10 | 11 | 12 | def run_isort(directory, check_only=False): 13 | """ 14 | Run isort on the specified directory. 15 | 16 | Args: 17 | directory: The directory to run isort on 18 | check_only: If True, only check for issues without modifying files 19 | 20 | Returns: 21 | The exit code from the isort command 22 | """ 23 | try: 24 | # Build the isort command 25 | cmd = ["isort"] 26 | 27 | # Add check flag if requested 28 | if check_only: 29 | cmd.append("--check") 30 | 31 | # Add the directory to process 32 | cmd.append(directory) 33 | 34 | # Run the command 35 | print(f"Running: {' '.join(cmd)}") 36 | result = subprocess.run(cmd, capture_output=True, text=True) 37 | 38 | # Print output 39 | if result.stdout: 40 | print(result.stdout) 41 | if result.stderr: 42 | print(result.stderr, file=sys.stderr) 43 | 44 | # Return the exit code 45 | return result.returncode 46 | 47 | except FileNotFoundError: 48 | print("Error: isort not found. Please install it with: pip install isort") 49 | return 1 50 | except Exception as e: 51 | print(f"Error running isort: {e}") 52 | return 1 53 | 54 | 55 | def main(): 56 | """ 57 | Main function to run isort on the prompt_decorators package. 58 | 59 | Returns: 60 | Exit code (0 for success, non-zero for failure) 61 | """ 62 | parser = argparse.ArgumentParser(description="Sort and format imports using isort") 63 | parser.add_argument( 64 | "--check", 65 | action="store_true", 66 | help="Check for issues without modifying files", 67 | ) 68 | parser.add_argument( 69 | "directory", 70 | nargs="?", 71 | default=".", 72 | help="Directory to process (default: current directory)", 73 | ) 74 | 75 | args = parser.parse_args() 76 | return run_isort(args.directory, args.check) 77 | 78 | 79 | if __name__ == "__main__": 80 | sys.exit(main()) 81 | -------------------------------------------------------------------------------- /registry/core/minimal/version.json: -------------------------------------------------------------------------------- 1 | { 2 | "decoratorName": "Version", 3 | "version": "1.0.0", 4 | "description": "Specifies the version of the Prompt Decorators standard to use. This decorator must be the first in any sequence when used, ensuring proper interpretation of decorators according to the specified standard version.", 5 | "author": { 6 | "name": "Prompt Decorators Working Group", 7 | "email": "promptdecoratorspec@synapti.ai", 8 | "url": "https://synapti.ai" 9 | }, 10 | "parameters": [ 11 | { 12 | "name": "standard", 13 | "type": "string", 14 | "description": "The semantic version of the Prompt Decorators standard to use", 15 | "pattern": "^\\d+\\.\\d+\\.\\d+$", 16 | "default": "1.0.0", 17 | "required": true 18 | } 19 | ], 20 | "transformationTemplate": { 21 | "instruction": "The following prompt uses Prompt Decorators standard version {standard}. Please interpret all decorators according to this version's specifications.", 22 | "parameterMapping": { 23 | "standard": { 24 | "format": "The following prompt uses Prompt Decorators standard version {value}. Please interpret all decorators according to this version's specifications." 25 | } 26 | }, 27 | "placement": "prepend", 28 | "compositionBehavior": "override" 29 | }, 30 | "implementationGuidance": { 31 | "examples": [ 32 | { 33 | "context": "Version specification", 34 | "originalPrompt": "+++Reasoning(depth=comprehensive)\nExplain quantum entanglement", 35 | "transformedPrompt": "The following prompt uses Prompt Decorators standard version 1.0.0. Please interpret all decorators according to this version's specifications.\n\n+++Reasoning(depth=comprehensive)\nExplain quantum entanglement" 36 | } 37 | ], 38 | "compatibilityNotes": [ 39 | { 40 | "decorator": "All", 41 | "relationship": "requires", 42 | "notes": "The Version decorator should always be the first in any sequence when used" 43 | } 44 | ] 45 | }, 46 | "examples": [ 47 | { 48 | "description": "Specify standard version for compatibility", 49 | "usage": "+++Version(standard=1.0.0)\n+++Reasoning(depth=comprehensive)\nExplain quantum entanglement", 50 | "result": "Ensures decorators are interpreted according to version 1.0.0 of the standard" 51 | } 52 | ], 53 | "compatibility": { 54 | "requires": [], 55 | "conflicts": [], 56 | "minStandardVersion": "1.0.0", 57 | "models": [ 58 | "gpt-4o", 59 | "gpt-4-turbo" 60 | ] 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /prompt_decorators/registry/core/minimal/version.json: -------------------------------------------------------------------------------- 1 | { 2 | "decoratorName": "Version", 3 | "version": "1.0.0", 4 | "description": "Specifies the version of the Prompt Decorators standard to use. This decorator must be the first in any sequence when used, ensuring proper interpretation of decorators according to the specified standard version.", 5 | "author": { 6 | "name": "Prompt Decorators Working Group", 7 | "email": "promptdecoratorspec@synapti.ai", 8 | "url": "https://synapti.ai" 9 | }, 10 | "parameters": [ 11 | { 12 | "name": "standard", 13 | "type": "string", 14 | "description": "The semantic version of the Prompt Decorators standard to use", 15 | "pattern": "^\\d+\\.\\d+\\.\\d+$", 16 | "default": "1.0.0", 17 | "required": true 18 | } 19 | ], 20 | "transformationTemplate": { 21 | "instruction": "The following prompt uses Prompt Decorators standard version {standard}. Please interpret all decorators according to this version's specifications.", 22 | "parameterMapping": { 23 | "standard": { 24 | "format": "The following prompt uses Prompt Decorators standard version {value}. Please interpret all decorators according to this version's specifications." 25 | } 26 | }, 27 | "placement": "prepend", 28 | "compositionBehavior": "override" 29 | }, 30 | "implementationGuidance": { 31 | "examples": [ 32 | { 33 | "context": "Version specification", 34 | "originalPrompt": "+++Reasoning(depth=comprehensive)\nExplain quantum entanglement", 35 | "transformedPrompt": "The following prompt uses Prompt Decorators standard version 1.0.0. Please interpret all decorators according to this version's specifications.\n\n+++Reasoning(depth=comprehensive)\nExplain quantum entanglement" 36 | } 37 | ], 38 | "compatibilityNotes": [ 39 | { 40 | "decorator": "All", 41 | "relationship": "requires", 42 | "notes": "The Version decorator should always be the first in any sequence when used" 43 | } 44 | ] 45 | }, 46 | "examples": [ 47 | { 48 | "description": "Specify standard version for compatibility", 49 | "usage": "+++Version(standard=1.0.0)\n+++Reasoning(depth=comprehensive)\nExplain quantum entanglement", 50 | "result": "Ensures decorators are interpreted according to version 1.0.0 of the standard" 51 | } 52 | ], 53 | "compatibility": { 54 | "requires": [], 55 | "conflicts": [], 56 | "minStandardVersion": "1.0.0", 57 | "models": [ 58 | "gpt-4o", 59 | "gpt-4-turbo" 60 | ] 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /docs/api/index.md: -------------------------------------------------------------------------------- 1 | # API Reference 2 | 3 | ## Table of Contents 4 | 5 | - [Overview](#overview) 6 | - [API Structure](#api-structure) 7 | - [Modules](#modules) 8 | - [Core Modules](modules/index.md#core-modules) 9 | - [Schema Modules](modules/index.md#schema-modules) 10 | - [Utility Modules](modules/index.md#utility-modules) 11 | - [Integration Modules](modules/index.md#integration-modules) 12 | - [Other Modules](modules/index.md#other-modules) 13 | - [Decorators](#decorators) 14 | - [Minimal](decorators/index.md#minimal) 15 | - [Reasoning Process Decorators](decorators/index.md#reasoning-process-decorators) 16 | - [Output Structure Decorators](decorators/index.md#output-structure-decorators) 17 | - [Tone](decorators/index.md#tone) 18 | - [Verification](decorators/index.md#verification) 19 | - [Usage Example](#usage-example) 20 | 21 | ## Overview 22 | 23 | This section contains the API reference for the Prompt Decorators package. It provides detailed documentation for all modules, classes, functions, and properties in the package. 24 | 25 | ## API Structure 26 | 27 | The API is organized into the following sections: 28 | 29 | ### Modules {#modules} 30 | 31 | - **[Modules](modules/index.md)**: Documentation for all Python modules in the package 32 | - [Core Modules](modules/index.md#core-modules): Core functionality of prompt decorators 33 | - [Schema Modules](modules/index.md#schema-modules): Data models and schemas 34 | - [Utility Modules](modules/index.md#utility-modules): Helper functions and utilities 35 | - [Integration Modules](modules/index.md#integration-modules): Integrations with other systems 36 | 37 | ### Decorators {#decorators} 38 | 39 | - **[Decorators](decorators/index.md)**: Documentation for all available prompt decorators 40 | - [Minimal Decorators](decorators/index.md#minimal): Essential decorators for basic functionality 41 | - [Reasoning Process Decorators](decorators/index.md#reasoning-process-decorators): Decorators for controlling reasoning processes 42 | - [Output Structure Decorators](decorators/index.md#output-structure-decorators): Decorators for controlling output structure 43 | - [And more...](decorators/index.md) 44 | 45 | ## Usage Example 46 | 47 | ```python 48 | from prompt_decorators import transform_prompt 49 | 50 | # Transform a prompt using decorators 51 | transformed_prompt = transform_prompt( 52 | "What are the environmental impacts of electric vehicles?", 53 | ["+++StepByStep(numbered=true)", "+++Reasoning(depth=comprehensive)"] 54 | ) 55 | ``` 56 | 57 | For more examples, see the [Quick Start](../quickstart.md) guide. 58 | -------------------------------------------------------------------------------- /.cursor/rules/070-workflow-preferences.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | description: MAINTAIN development discipline WHEN implementing changes TO preserve codebase integrity 3 | globs: **/*.py 4 | --- 5 | 6 | # Coding Workflow Preferences 7 | 8 | 1.0.0 9 | 10 | ## Context 11 | - When implementing new features 12 | - When fixing bugs or addressing issues 13 | - When refactoring or improving existing code 14 | - When reviewing code changes 15 | 16 | ## Requirements 17 | - Focus exclusively on code areas relevant to the current task 18 | - Do not modify code unrelated to the assigned task 19 | - Write thorough tests for all major functionality 20 | - Preserve existing architectural patterns unless explicitly instructed otherwise 21 | - Analyze potential impacts of changes on other methods and code areas 22 | - Consider side effects before implementing changes 23 | - Maintain backward compatibility when possible 24 | - Document significant architectural decisions 25 | 26 | ## Examples 27 | 28 | 29 | # Good: Focused change with proper testing 30 | # Task: Fix validation in user registration 31 | 32 | # 1. Only modify the relevant validation function 33 | def validate_user_input(user_data): 34 | """Validate user registration data with fixed email validation.""" 35 | if not is_valid_email(user_data.get('email')): 36 | raise ValidationError("Invalid email format") 37 | # Other existing validation logic... 38 | 39 | # 2. Add thorough tests for the fix 40 | def test_validate_user_input_with_invalid_email(): 41 | """Test that invalid emails are properly rejected.""" 42 | with pytest.raises(ValidationError): 43 | validate_user_input({'email': 'invalid-email'}) 44 | 45 | def test_validate_user_input_with_valid_email(): 46 | """Test that valid emails pass validation.""" 47 | result = validate_user_input({'email': 'user@example.com'}) 48 | assert result is True 49 | 50 | 51 | 52 | # Bad: Unfocused changes beyond task scope 53 | # Task: Fix validation in user registration 54 | 55 | # 1. Modifying unrelated authentication system 56 | def authenticate_user(username, password): 57 | """Authenticate user with new token-based system.""" 58 | # Completely rewriting authentication when task was only about validation 59 | token = generate_jwt_token(username, password) 60 | return {'authenticated': True, 'token': token} 61 | 62 | # 2. Changing database schema without tests 63 | def update_user_schema(): 64 | """Update user table with new fields.""" 65 | # Adding schema changes unrelated to the validation fix 66 | db.execute("ALTER TABLE users ADD COLUMN last_login TIMESTAMP") 67 | 68 | -------------------------------------------------------------------------------- /registry/decorator-template.json: -------------------------------------------------------------------------------- 1 | { 2 | "decoratorName": "DecoratorName", 3 | "version": "1.0.0", 4 | "description": "A detailed description of what the decorator does, its purpose, and how it modifies AI behavior.", 5 | "author": { 6 | "name": "Prompt Decorators Working Group", 7 | "email": "promptdecoratorspec@synapti.ai", 8 | "url": "https://synapti.ai" 9 | }, 10 | "parameters": [ 11 | { 12 | "name": "parameterName", 13 | "type": "string", 14 | "description": "Description of what this parameter does", 15 | "required": false, 16 | "default": "defaultValue", 17 | "enum": ["option1", "option2", "option3"], 18 | "min": 0, 19 | "max": 10, 20 | "pattern": "^[A-Za-z0-9]+$" 21 | } 22 | ], 23 | "transformationTemplate": { 24 | "instruction": "Base instruction text that will be added to the prompt.", 25 | "parameterMapping": { 26 | "parameterName": { 27 | "valueMap": { 28 | "option1": "Apply option1 transformation.", 29 | "option2": "Apply option2 transformation.", 30 | "option3": "Apply option3 transformation." 31 | }, 32 | "format": "with {value} customization" 33 | } 34 | }, 35 | "placement": "append", 36 | "compositionBehavior": "accumulate" 37 | }, 38 | "implementationGuidance": { 39 | "examples": [ 40 | { 41 | "context": "Example for gpt-4o", 42 | "originalPrompt": "Tell me about artificial intelligence.", 43 | "transformedPrompt": "Tell me about artificial intelligence. [Transformation applied with option1]", 44 | "notes": "This demonstrates how the decorator modifies the prompt." 45 | } 46 | ], 47 | "compatibilityNotes": [ 48 | { 49 | "decorator": "AnotherDecorator", 50 | "relationship": "enhances", 51 | "notes": "Works well with AnotherDecorator by adding complementary instructions." 52 | } 53 | ] 54 | }, 55 | "examples": [ 56 | { 57 | "description": "Example of how to use this decorator with specific parameters", 58 | "usage": "+++DecoratorName(parameterName=option1)\nUser prompt text goes here", 59 | "result": "Expected behavior or output pattern from this decorator", 60 | "prompt": "Tell me about artificial intelligence.", 61 | "parameters": { 62 | "parameterName": "option1" 63 | } 64 | } 65 | ], 66 | "compatibility": { 67 | "requires": [], 68 | "conflicts": [], 69 | "minStandardVersion": "1.0.0", 70 | "maxStandardVersion": "2.0.0", 71 | "models": [ 72 | "gpt-4o", 73 | "gpt-4-turbo" 74 | ] 75 | }, 76 | "category": "Instruction" 77 | } 78 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["poetry-core>=1.0.0"] 3 | build-backend = "poetry.core.masonry.api" 4 | 5 | [tool.poetry] 6 | name = "prompt-decorators" 7 | version = "0.9.0" 8 | description = "A framework for defining, managing, and applying prompt decorators to enhance interactions with LLMs" 9 | authors = ["Daniel Bentes "] 10 | readme = "README.md" 11 | license = "Apache-2.0" 12 | classifiers = [ 13 | "Development Status :: 3 - Alpha", 14 | "Intended Audience :: Developers", 15 | "License :: OSI Approved :: Apache Software License", 16 | "Programming Language :: Python :: 3", 17 | "Programming Language :: Python :: 3.11", 18 | ] 19 | 20 | [tool.poetry.urls] 21 | Documentation = "https://synaptiai.github.io/prompt-decorators/" 22 | Source = "https://github.com/synaptiai/prompt-decorators" 23 | "Issue Tracker" = "https://github.com/synaptiai/prompt-decorators/issues" 24 | 25 | [tool.poetry.dependencies] 26 | python = ">=3.11,<4.0" 27 | pydantic = "^2.0.0" 28 | jsonschema = "^4.0.0" 29 | importlib-metadata = "^6.0.0" 30 | markdown = "^3.7" 31 | 32 | [tool.poetry.group.dev.dependencies] 33 | pytest = "^7.0.0" 34 | black = ">=23,<25" 35 | isort = "^5.0.0" 36 | mypy = "^1.0.0" 37 | pytest-cov = "^4.0.0" 38 | ruff = "^0.1.0" 39 | pre-commit = "^4.1.0" 40 | 41 | [tool.poetry.group.docs.dependencies] 42 | sphinx = "^7.0.0" 43 | sphinx-rtd-theme = "^1.0.0" 44 | myst-parser = "^2.0.0" 45 | mkdocs = "^1.5.0" 46 | mkdocs-material = "^9.0.0" 47 | mkdocs-awesome-pages-plugin = "^2.9.0" 48 | mkdocs-autolinks-plugin = "^0.7.0" 49 | mkdocs-git-revision-date-localized-plugin = "^1.2.0" 50 | mkdocstrings = "^0.24.0" 51 | 52 | [tool.poetry.group.langchain.dependencies] 53 | langchain = ">=0.0.200" 54 | 55 | [tool.poetry.group.openai.dependencies] 56 | openai = ">=0.27.0" 57 | 58 | [tool.poetry.group.anthropic.dependencies] 59 | anthropic = ">=0.3.0" 60 | 61 | [tool.poetry.group.mcp.dependencies] 62 | mcp = {version = ">=0.1.0", python = ">=3.11"} 63 | 64 | [tool.black] 65 | line-length = 88 66 | target-version = ["py311"] 67 | include = '\.pyi?$' 68 | 69 | [tool.isort] 70 | profile = "black" 71 | line_length = 88 72 | multi_line_output = 3 73 | 74 | [tool.mypy] 75 | python_version = "3.11" 76 | warn_return_any = true 77 | warn_unused_configs = true 78 | disallow_untyped_defs = true 79 | disallow_incomplete_defs = true 80 | 81 | [tool.pytest.ini_options] 82 | testpaths = ["tests"] 83 | python_files = "test_*.py" 84 | python_functions = "test_*" 85 | python_classes = "Test*" 86 | asyncio_mode = "strict" 87 | asyncio_default_fixture_loop_scope = "function" 88 | 89 | [tool.ruff] 90 | line-length = 88 91 | target-version = "py311" 92 | select = ["E", "F", "B", "I"] 93 | ignore = [] 94 | -------------------------------------------------------------------------------- /.github/workflows/code-quality.yml: -------------------------------------------------------------------------------- 1 | name: Code Quality and Testing 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: [main, master] 7 | 8 | # Set minimum required permissions 9 | permissions: 10 | contents: read # Only needs read access to repository content 11 | 12 | jobs: 13 | pre-commit: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v3 17 | - uses: actions/setup-python@v5 18 | with: 19 | python-version: '3.11' 20 | cache: 'pip' 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install poetry 25 | poetry install --with mcp 26 | # Install required dependencies directly as well, so they're available to pre-commit hooks 27 | pip install pre-commit mypy pytest pydantic 28 | pip install -e . 29 | - name: Run pre-commit 30 | run: pre-commit run --all-files 31 | 32 | test-matrix: 33 | needs: pre-commit 34 | runs-on: ubuntu-latest 35 | strategy: 36 | matrix: 37 | python-version: ['3.11'] 38 | steps: 39 | - uses: actions/checkout@v3 40 | - name: Set up Python ${{ matrix.python-version }} 41 | uses: actions/setup-python@v5 42 | with: 43 | python-version: ${{ matrix.python-version }} 44 | cache: 'pip' 45 | - name: Install dependencies 46 | run: | 47 | python -m pip install --upgrade pip 48 | pip install poetry 49 | poetry install --with mcp 50 | - name: Run tests 51 | run: poetry run pytest 52 | - name: Run tests with coverage 53 | run: poetry run pytest --cov=prompt_decorators tests/ 54 | 55 | type-check: 56 | needs: pre-commit 57 | runs-on: ubuntu-latest 58 | steps: 59 | - uses: actions/checkout@v3 60 | - uses: actions/setup-python@v5 61 | with: 62 | python-version: '3.11' 63 | cache: 'pip' 64 | - name: Install dependencies 65 | run: | 66 | python -m pip install --upgrade pip 67 | pip install poetry mypy 68 | poetry install --with mcp 69 | - name: Run mypy 70 | run: poetry run mypy prompt_decorators 71 | 72 | docstring-check: 73 | needs: pre-commit 74 | runs-on: ubuntu-latest 75 | steps: 76 | - uses: actions/checkout@v3 77 | - uses: actions/setup-python@v5 78 | with: 79 | python-version: '3.11' 80 | cache: 'pip' 81 | - name: Install dependencies 82 | run: | 83 | python -m pip install --upgrade pip 84 | pip install poetry 85 | poetry install --with mcp 86 | - name: Check docstrings 87 | run: python scripts/standardize_docstrings.py prompt_decorators --check 88 | -------------------------------------------------------------------------------- /scripts/copy_registry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Script to copy registry files to the package directory. 4 | 5 | This script copies the registry files from the source directory to the package directory 6 | during the build process. It is intended to be run before building the package. 7 | 8 | Usage: 9 | python scripts/copy_registry.py 10 | 11 | The script will: 12 | 1. Check if the source registry directory exists 13 | 2. Create the package registry directory if it doesn't exist 14 | 3. Copy all files from the source registry to the package registry 15 | """ 16 | 17 | import shutil 18 | import sys 19 | from pathlib import Path 20 | 21 | 22 | def copy_registry() -> bool: 23 | """Copy registry files to the package directory. 24 | 25 | Returns: 26 | bool: True if copy was successful, False otherwise 27 | """ 28 | # Get the current directory 29 | current_dir = Path.cwd() 30 | 31 | # Define the paths 32 | source_registry = current_dir / "registry" 33 | package_registry = current_dir / "prompt_decorators" / "registry" 34 | 35 | # Check if the source registry directory exists 36 | if not source_registry.exists(): 37 | print(f"Source registry directory not found: {source_registry}") 38 | return False 39 | 40 | # Create the package registry directory if it doesn't exist 41 | package_registry.mkdir(parents=True, exist_ok=True) 42 | 43 | # Copy all files from the source registry to the package registry 44 | print(f"Copying files from {source_registry} to {package_registry}") 45 | 46 | # Create subdirectories 47 | for subdir in ["core", "extensions", "simplified_decorators"]: 48 | source_subdir = source_registry / subdir 49 | package_subdir = package_registry / subdir 50 | 51 | if source_subdir.exists(): 52 | # Create the subdirectory in the package registry 53 | package_subdir.mkdir(exist_ok=True) 54 | 55 | # Copy all files from the source subdirectory to the package subdirectory 56 | for item in source_subdir.glob("**/*"): 57 | if item.is_file(): 58 | # Create the corresponding path in the package registry 59 | rel_path = item.relative_to(source_subdir) 60 | dest_path = package_subdir / rel_path 61 | 62 | # Create parent directories if they don't exist 63 | dest_path.parent.mkdir(parents=True, exist_ok=True) 64 | 65 | # Copy the file 66 | shutil.copy2(item, dest_path) 67 | print(f"Copied {item} to {dest_path}") 68 | 69 | return True 70 | 71 | 72 | if __name__ == "__main__": 73 | if copy_registry(): 74 | print("Registry files copied successfully.") 75 | else: 76 | print("Failed to copy registry files.") 77 | sys.exit(1) 78 | -------------------------------------------------------------------------------- /prompt_decorators/integrations/mcp/claude_desktop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Entry point for running the Prompt Decorators MCP server for Claude Desktop. 3 | 4 | Usage: 5 | python -m prompt_decorators.integrations.mcp.claude_desktop [`--host HOST`] [`--port PORT`] [`--verbose`] 6 | """ 7 | 8 | import argparse 9 | import logging 10 | import os 11 | import sys 12 | 13 | 14 | def main() -> None: 15 | """Run the Prompt Decorators MCP server for Claude Desktop.""" 16 | parser = argparse.ArgumentParser( 17 | description="Run the Prompt Decorators MCP server for Claude Desktop" 18 | ) 19 | parser.add_argument("--verbose", action="store_true", help="Enable verbose logging") 20 | parser.add_argument("--host", type=str, default="0.0.0.0", help="Host to bind to") 21 | parser.add_argument("--port", type=int, default=5000, help="Port to listen on") 22 | args = parser.parse_args() 23 | 24 | # Configure logging level based on verbose flag 25 | log_level = logging.DEBUG if args.verbose else logging.INFO 26 | logging.basicConfig( 27 | level=log_level, 28 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", 29 | stream=sys.stderr, 30 | ) 31 | 32 | logger = logging.getLogger("claude-desktop-launcher") 33 | logger.info("Initializing Prompt Decorators MCP server for Claude Desktop") 34 | 35 | # Check if MCP SDK is installed 36 | try: 37 | import mcp 38 | 39 | logger.info(f"MCP SDK version: {getattr(mcp, '__version__', 'unknown')}") 40 | except ImportError: 41 | logger.error("MCP SDK not installed") 42 | logger.error("Please install manually: pip install mcp") 43 | sys.exit(1) 44 | 45 | # Add the project directory to PYTHONPATH to ensure imports work correctly 46 | project_dir = os.path.dirname( 47 | os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 48 | ) 49 | if project_dir not in sys.path: 50 | logger.debug(f"Adding project directory to PYTHONPATH: {project_dir}") 51 | sys.path.insert(0, project_dir) 52 | 53 | try: 54 | # Import and run the server 55 | from prompt_decorators.integrations.mcp.server import MCP_AVAILABLE, run_server 56 | 57 | if not MCP_AVAILABLE: 58 | logger.error( 59 | "MCP is not available despite being importable. This is unexpected." 60 | ) 61 | sys.exit(1) 62 | 63 | logger.info(f"Starting Claude Desktop MCP server on {args.host}:{args.port}") 64 | run_server(host=args.host, port=args.port) 65 | except ImportError as e: 66 | logger.error(f"Failed to import server implementation: {e}") 67 | sys.exit(1) 68 | except Exception as e: 69 | logger.error(f"Error running Claude Desktop MCP server: {e}", exc_info=True) 70 | sys.exit(1) 71 | 72 | 73 | if __name__ == "__main__": 74 | main() 75 | -------------------------------------------------------------------------------- /scripts/bump_version.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Version bumping script for prompt-decorators. 4 | 5 | This script automates the process of bumping the version in pyproject.toml, 6 | creating a git commit and tag, and optionally pushing changes to GitHub. 7 | 8 | Usage: 9 | python scripts/bump_version.py patch|minor|major [--push] 10 | """ 11 | 12 | import argparse 13 | import subprocess 14 | import sys 15 | 16 | 17 | def run_command(cmd, check=True): 18 | """Run a shell command and return the output.""" 19 | print(f"Running: {' '.join(cmd)}") 20 | result = subprocess.run(cmd, capture_output=True, text=True) 21 | if check and result.returncode != 0: 22 | print(f"Error: {result.stderr}") 23 | sys.exit(1) 24 | return result.stdout.strip() 25 | 26 | 27 | def main(): 28 | """Main function to handle version bumping.""" 29 | parser = argparse.ArgumentParser(description="Bump version and create git tag") 30 | parser.add_argument( 31 | "bump_type", 32 | choices=["patch", "minor", "major"], 33 | help="Type of version bump", 34 | ) 35 | parser.add_argument("--push", action="store_true", help="Push to GitHub") 36 | args = parser.parse_args() 37 | 38 | # Check if there are uncommitted changes 39 | status = run_command(["git", "status", "--porcelain"]) 40 | if status: 41 | print( 42 | "Error: There are uncommitted changes. Please commit or stash them first." 43 | ) 44 | sys.exit(1) 45 | 46 | # Bump version in pyproject.toml 47 | run_command(["poetry", "version", args.bump_type]) 48 | 49 | # Get the new version 50 | version = run_command(["poetry", "version", "-s"]) 51 | 52 | # Check if tag already exists 53 | tags = run_command(["git", "tag"]) 54 | if f"v{version}" in tags.split("\n"): 55 | print(f"Error: Tag v{version} already exists.") 56 | sys.exit(1) 57 | 58 | # Commit the change 59 | run_command(["git", "add", "pyproject.toml"]) 60 | run_command(["git", "commit", "-m", f"Bump version to {version}"]) 61 | 62 | # Create a tag 63 | run_command(["git", "tag", f"v{version}"]) 64 | 65 | if args.push: 66 | run_command(["git", "push", "origin", "main"]) 67 | run_command(["git", "push", "origin", f"v{version}"]) 68 | 69 | print(f"\n✅ Version bumped to {version}") 70 | if not args.push: 71 | print("\nRemember to push changes with:") 72 | print(f" git push origin main && git push origin v{version}") 73 | 74 | print("\nNext steps:") 75 | print("1. Push changes to GitHub (if not done automatically)") 76 | print("2. Go to GitHub and create a release from the tag") 77 | print(" https://github.com/synaptiai/prompt-decorators/releases/new") 78 | print( 79 | "3. The GitHub Action will automatically publish to PyPI when the release is created" 80 | ) 81 | 82 | 83 | if __name__ == "__main__": 84 | main() 85 | -------------------------------------------------------------------------------- /docs/api/decorators/StepByStep.md: -------------------------------------------------------------------------------- 1 | # StepByStep Decorator 2 | 3 | Structures the AI's response as a sequence of clearly labeled steps. This decorator helps break down complex processes, explanations, or solutions into manageable, sequential parts for better understanding. 4 | 5 | **Category**: Minimal 6 | 7 | ## Parameters 8 | 9 | | Parameter | Type | Description | Default | 10 | |-----------|------|-------------|--------| 11 | | `numbered` | `boolean` | Whether to number the steps or use bullet points | `True` | 12 | 13 | ## Examples 14 | 15 | ### Numbered steps for a technical process 16 | 17 | ``` 18 | +++StepByStep(numbered=true) 19 | How do I set up a Python virtual environment? 20 | ``` 21 | 22 | Provides numbered steps for creating and activating a virtual environment 23 | 24 | ### Bullet-point steps for a creative process 25 | 26 | ``` 27 | +++StepByStep(numbered=false) 28 | How do I brainstorm effectively? 29 | ``` 30 | 31 | Delivers bullet-pointed steps for conducting a brainstorming session 32 | 33 | ## Model-Specific Implementations 34 | 35 | ### gpt-4-turbo 36 | 37 | **Instruction:** Please provide a step-by-step guide with each step clearly labeled and explained. Break down the process into clear, manageable steps. 38 | 39 | **Notes:** This model may need more explicit instructions to create well-structured steps 40 | 41 | 42 | ## Implementation Guidance 43 | 44 | ### Standard implementation with numbered steps 45 | 46 | **Original Prompt:** 47 | ``` 48 | How do I create a sourdough starter? 49 | ``` 50 | 51 | **Transformed Prompt:** 52 | ``` 53 | Please break down your response into clear, sequential steps. Number each step sequentially (Step 1, Step 2, etc.). 54 | 55 | How do I create a sourdough starter? 56 | ``` 57 | 58 | ### Implementation with bullet points 59 | 60 | **Original Prompt:** 61 | ``` 62 | What's the process for conducting user research? 63 | ``` 64 | 65 | **Transformed Prompt:** 66 | ``` 67 | Please break down your response into clear, sequential steps. Use bullet points for each step instead of numbers. 68 | 69 | What's the process for conducting user research? 70 | ``` 71 | 72 | ## Transformation Details 73 | 74 | **Base Instruction:** Please break down your response into clear, sequential steps. 75 | 76 | **Placement:** prepend 77 | 78 | **Composition Behavior:** accumulate 79 | 80 | **Parameter Effects:** 81 | 82 | - `numbered`: 83 | - When set to `true`: Number each step sequentially (Step 1, Step 2, etc.). 84 | - When set to `false`: Use bullet points for each step instead of numbers. 85 | 86 | ## Compatibility 87 | 88 | - **Requires**: None 89 | - **Conflicts**: None 90 | - **Compatible Models**: gpt-4o, gpt-4-turbo 91 | - **Standard Version**: 1.0.0 - 2.0.0 92 | 93 | ## Related Decorators 94 | 95 | - **Reasoning**: Enhances StepByStep Combining these decorators produces step-by-step reasoning that is both structured and logical 96 | - **OutputFormat**: Enhances StepByStep Can be combined with OutputFormat for structured formatting of the steps 97 | -------------------------------------------------------------------------------- /schemas/README.md: -------------------------------------------------------------------------------- 1 | # Prompt Decorators JSON Schemas 2 | 3 | This directory contains the JSON Schema definitions for the Prompt Decorators standard. These schemas define the structure and validation rules for various aspects of the standard. 4 | 5 | ## Schema Files 6 | 7 | ### 1. `decorator.schema.json` 8 | - Defines the base structure of a single prompt decorator 9 | - Used as a reference by other schemas 10 | - Includes parameter validation and metadata 11 | - Core schema that all decorator implementations must follow 12 | 13 | ### 2. `api-request.schema.json` 14 | - Defines the structure of API requests when using decorators 15 | - Includes prompt text, decorator list, and metadata 16 | - References the decorator schema for decorator validation 17 | - Used by LLM providers implementing the standard 18 | 19 | ### 3. `registry-entry.schema.json` 20 | - Defines how decorators are registered in the central registry 21 | - Includes detailed metadata, documentation, and compatibility info 22 | - Used for publishing decorators to the registry 23 | - Ensures consistent documentation and versioning 24 | 25 | ### 4. `extension-package.schema.json` 26 | - Defines how decorator extensions are packaged 27 | - Includes dependency management and configuration 28 | - References the registry entry schema for decorator definitions 29 | - Used for distributing collections of related decorators 30 | 31 | ## Usage 32 | 33 | ### Validation 34 | Use these schemas to validate your decorator implementations: 35 | 36 | ```bash 37 | # Using ajv-cli 38 | npx ajv-cli validate -s decorator.schema.json -d your-decorator.json 39 | 40 | # Using python-jsonschema 41 | jsonschema -i your-decorator.json decorator.schema.json 42 | ``` 43 | 44 | ### Integration 45 | Reference these schemas in your JSON files: 46 | 47 | ```json 48 | { 49 | "$schema": "https://raw.githubusercontent.com/prompt-decorators/spec/main/schemas/decorator.schema.json", 50 | "name": "YourDecorator", 51 | ... 52 | } 53 | ``` 54 | 55 | ## Schema Relationships 56 | 57 | ``` mermaid 58 | graph TD 59 | A[decorator.schema.json] --> B[api-request.schema.json] 60 | A --> C[registry-entry.schema.json] 61 | C --> D[extension-package.schema.json] 62 | ``` 63 | 64 | ## Versioning 65 | 66 | The schemas follow semantic versioning: 67 | - Major version changes indicate breaking changes 68 | - Minor version changes add features in a backward-compatible manner 69 | - Patch version changes fix issues in a backward-compatible manner 70 | 71 | ## Contributing 72 | 73 | When contributing changes to the schemas: 74 | 1. Ensure backward compatibility unless making a major version change 75 | 2. Update all affected example files 76 | 3. Add/update tests for new/modified validation rules 77 | 4. Document any breaking changes in CHANGELOG.md 78 | 79 | ## Testing 80 | 81 | Test your changes against the provided examples: 82 | 83 | ```bash 84 | # Test all examples 85 | ./test-schemas.sh 86 | 87 | # Test a specific schema 88 | ./test-schemas.sh decorator.schema.json 89 | ``` 90 | -------------------------------------------------------------------------------- /docs/api/decorators/Socratic.md: -------------------------------------------------------------------------------- 1 | # Socratic Decorator 2 | 3 | Structures the response as a series of questions that guide the user through a problem or topic. This decorator encourages critical thinking through question-based exploration, helping to uncover assumptions and lead to deeper understanding. 4 | 5 | **Category**: Reasoning 6 | 7 | ## Parameters 8 | 9 | | Parameter | Type | Description | Default | 10 | |-----------|------|-------------|--------| 11 | | `iterations` | `number` | Number of question-answer cycles to include | `3` | 12 | 13 | ## Examples 14 | 15 | ### Basic socratic exploration of a philosophical concept 16 | 17 | ``` 18 | +++Socratic 19 | What is justice? 20 | ``` 21 | 22 | Explores the concept of justice through a series of guiding questions 23 | 24 | ### Deep socratic analysis with 5 iterations 25 | 26 | ``` 27 | +++Socratic(iterations=5) 28 | How do we know what we know? 29 | ``` 30 | 31 | Provides an extended series of 5 question-answer cycles to explore epistemology 32 | 33 | ## Model-Specific Implementations 34 | 35 | ### gpt-4-turbo 36 | 37 | **Instruction:** Format your response as a series of thought-provoking questions. For each question, provide a thoughtful answer that leads to the next question. This creates a step-by-step exploration of the topic. 38 | 39 | **Notes:** This model benefits from more explicit instructions on the question-answer structure 40 | 41 | 42 | ## Implementation Guidance 43 | 44 | ### Standard implementation with 3 iterations 45 | 46 | **Original Prompt:** 47 | ``` 48 | What is justice? 49 | ``` 50 | 51 | **Transformed Prompt:** 52 | ``` 53 | Please structure your response as a Socratic dialogue that guides through the topic using thought-provoking questions followed by answers. Include approximately 3 question-answer cycles in your exploration. 54 | 55 | What is justice? 56 | ``` 57 | 58 | ### Extended exploration with 5 iterations 59 | 60 | **Original Prompt:** 61 | ``` 62 | How do we know what we know? 63 | ``` 64 | 65 | **Transformed Prompt:** 66 | ``` 67 | Please structure your response as a Socratic dialogue that guides through the topic using thought-provoking questions followed by answers. Include approximately 5 question-answer cycles in your exploration. 68 | 69 | How do we know what we know? 70 | ``` 71 | 72 | ## Transformation Details 73 | 74 | **Base Instruction:** Please structure your response as a Socratic dialogue that guides through the topic using thought-provoking questions followed by answers. 75 | 76 | **Placement:** prepend 77 | 78 | **Composition Behavior:** accumulate 79 | 80 | **Parameter Effects:** 81 | 82 | - `iterations`: 83 | - Format: Include approximately {value} question-answer cycles in your exploration. 84 | 85 | ## Compatibility 86 | 87 | - **Requires**: None 88 | - **Conflicts**: None 89 | - **Compatible Models**: gpt-4o, gpt-4-turbo 90 | - **Standard Version**: 1.0.0 - 2.0.0 91 | 92 | ## Related Decorators 93 | 94 | - **StepByStep**: Enhances Socratic Can be combined with StepByStep to create a structured Socratic analysis 95 | - **OutputFormat**: Enhances Socratic Can be combined with OutputFormat for consistent presentation 96 | -------------------------------------------------------------------------------- /tests/examples/reasoning_test_example.py: -------------------------------------------------------------------------------- 1 | """Example of automatically generated tests for the Reasoning decorator. 2 | 3 | This shows what kind of tests would be generated by the test generator script. 4 | """ 5 | 6 | 7 | import pytest 8 | 9 | from tests.utils.test_helpers import ( 10 | LLMClient, 11 | ValidationError, 12 | check_expectation, 13 | validate_decorator_in_prompt, 14 | ) 15 | 16 | # Initialize test client 17 | llm_client = LLMClient(use_real_llm=False, use_cache=True) 18 | 19 | 20 | # Tests for Reasoning decorator 21 | 22 | 23 | # Parameter validation tests 24 | def test_reasoning_depth_enum_values(): 25 | """Test that depth accepts only valid enum values.""" 26 | # Valid values 27 | validate_decorator_in_prompt("+++Reasoning(depth=basic)\nTest prompt.") 28 | validate_decorator_in_prompt("+++Reasoning(depth=moderate)\nTest prompt.") 29 | validate_decorator_in_prompt("+++Reasoning(depth=comprehensive)\nTest prompt.") 30 | 31 | # Invalid value 32 | with pytest.raises(ValidationError): 33 | validate_decorator_in_prompt("+++Reasoning(depth=invalid_value)\nTest prompt.") 34 | 35 | 36 | # Example-based tests 37 | def test_reasoning_basic_reasoning_process(): 38 | """Test Reasoning with example: Basic reasoning process with moderate depth.""" 39 | response = llm_client.generate("+++Reasoning\nExplain why the sky appears blue.") 40 | 41 | # Check if response meets expectations 42 | check_expectation( 43 | response, 44 | "matches_description", 45 | description="Provides a logical explanation of why the sky appears blue, showing the reasoning process that leads to the conclusion", 46 | ) 47 | 48 | 49 | def test_reasoning_comprehensive_scientific_explanation(): 50 | """ 51 | 52 | Test Reasoning with example: Comprehensive scientific explanation with 53 | detailed reasoning. 54 | """ 55 | response = llm_client.generate( 56 | "+++Reasoning(depth=comprehensive)\nDescribe how neural networks learn" 57 | "patterns in data." 58 | ) 59 | 60 | # Check if response meets expectations 61 | check_expectation( 62 | response, 63 | "matches_description", 64 | description="Delivers a comprehensive explanation of neural network learning with detailed reasoning steps, including gradient descent, backpropagation, and the mathematics behind pattern recognition", 65 | ) 66 | 67 | 68 | # Compatibility tests 69 | def test_reasoning_compatibility_with_step_by_step(): 70 | """Test that Reasoning works with StepByStep decorator.""" 71 | # Test with both decorators 72 | response = llm_client.generate( 73 | "+++Reasoning\n+++StepByStep\nExplain how photosynthesis works." 74 | ) 75 | 76 | # Should contain both reasoning elements and numbered steps 77 | assert check_expectation(response, "contains_numbered_steps") 78 | assert ( 79 | "reason" in response.lower() 80 | or "because" in response.lower() 81 | or "therefore" in response.lower() 82 | ) 83 | 84 | 85 | if __name__ == "__main__": 86 | # Run the tests 87 | pytest.main(["-v", __file__]) 88 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.schemas.decorator_schema.md: -------------------------------------------------------------------------------- 1 | # decorator_schema 2 | 3 | Schema definitions for prompt decorators. 4 | 5 | This module defines the schema classes used for validating decorator definitions 6 | and parameters. 7 | 8 | ## Classes 9 | 10 | ### `DecoratorSchema` 11 | 12 | Schema for decorator definitions. 13 | 14 | #### Attributes 15 | 16 | - `from_dict`: `classmethod` = `)>` 17 | 18 | #### Methods 19 | 20 | ##### `__init__` 21 | 22 | Initialize a decorator schema. 23 | 24 | Args: 25 | name: Name of the decorator 26 | description: Description of the decorator 27 | category: Category of the decorator 28 | parameters: List of parameter schemas 29 | transform_function: JavaScript function for transforming prompts 30 | version: Version of the decorator 31 | 32 | **Signature:** `__init__(self, name: str, description: str, category: str, parameters: List[prompt_decorators.schemas.decorator_schema.ParameterSchema], transform_function: str, version: str = '1.0.0')` 33 | 34 | **Parameters:** 35 | 36 | - `name`: `str` 37 | - `description`: `str` 38 | - `category`: `str` 39 | - `parameters`: `List` 40 | - `transform_function`: `str` 41 | - `version`: `str` (default: `1.0.0`) 42 | 43 | ##### `to_dict` 44 | 45 | Convert the schema to a dictionary. 46 | 47 | **Signature:** `to_dict(self) -> Dict[str, Any]` 48 | 49 | **Parameters:** 50 | 51 | 52 | **Returns:** `Dict` 53 | 54 | ### `ParameterSchema` 55 | 56 | Schema for decorator parameters. 57 | 58 | #### Attributes 59 | 60 | - `from_dict`: `classmethod` = `)>` 61 | 62 | #### Methods 63 | 64 | ##### `__init__` 65 | 66 | Initialize a parameter schema. 67 | 68 | Args: 69 | name: Name of the parameter 70 | description: Description of the parameter 71 | type_: Type of the parameter (string, integer, float, boolean, enum) 72 | required: Whether the parameter is required 73 | default: Default value for the parameter 74 | enum_values: Possible values for enum type 75 | min_value: Minimum value for numeric types 76 | max_value: Maximum value for numeric types 77 | min_length: Minimum length for string or array types 78 | max_length: Maximum length for string or array types 79 | pattern: Regex pattern for string validation 80 | 81 | **Signature:** `__init__(self, name: str, description: str, type_: str = 'string', required: bool = False, default: Any = None, enum_values: Optional[List[str]] = None, min_value: Union[int, float, NoneType] = None, max_value: Union[int, float, NoneType] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None)` 82 | 83 | **Parameters:** 84 | 85 | - `name`: `str` 86 | - `description`: `str` 87 | - `type_`: `str` (default: `string`) 88 | - `required`: `bool` (default: `False`) 89 | - `default`: `Any` (default: `None`) 90 | - `enum_values`: `Optional` (default: `None`) 91 | - `min_value`: `Union` (default: `None`) 92 | - `max_value`: `Union` (default: `None`) 93 | - `min_length`: `Optional` (default: `None`) 94 | - `max_length`: `Optional` (default: `None`) 95 | - `pattern`: `Optional` (default: `None`) 96 | 97 | ##### `to_dict` 98 | 99 | Convert the schema to a dictionary. 100 | 101 | **Signature:** `to_dict(self) -> Dict[str, Any]` 102 | 103 | **Parameters:** 104 | 105 | 106 | **Returns:** `Dict` 107 | -------------------------------------------------------------------------------- /scripts/setup_pre_commit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | This script helps developers set up pre-commit hooks for the project. 4 | It installs pre-commit and the hooks defined in .pre-commit-config.yaml. 5 | """ 6 | 7 | import os 8 | import subprocess 9 | import sys 10 | from pathlib import Path 11 | 12 | 13 | def check_pre_commit_installed(): 14 | """ 15 | Check if pre-commit is installed. 16 | 17 | Returns: 18 | bool: True if pre-commit is installed, False otherwise 19 | """ 20 | try: 21 | subprocess.run( 22 | ["pre-commit", "--version"], 23 | stdout=subprocess.PIPE, 24 | stderr=subprocess.PIPE, 25 | check=True, 26 | ) 27 | return True 28 | except (subprocess.SubprocessError, FileNotFoundError): 29 | return False 30 | 31 | 32 | def install_pre_commit(): 33 | """ 34 | Install pre-commit using pip. 35 | 36 | Returns: 37 | bool: True if installation was successful, False otherwise 38 | """ 39 | try: 40 | subprocess.run( 41 | [sys.executable, "-m", "pip", "install", "pre-commit"], check=True 42 | ) 43 | return True 44 | except subprocess.SubprocessError: 45 | return False 46 | 47 | 48 | def install_hooks(): 49 | """ 50 | Install pre-commit hooks. 51 | 52 | Returns: 53 | bool: True if hooks installation was successful, False otherwise 54 | """ 55 | try: 56 | subprocess.run(["pre-commit", "install"], check=True) 57 | return True 58 | except subprocess.SubprocessError: 59 | return False 60 | 61 | 62 | def run_hooks_on_all_files(): 63 | """ 64 | Run pre-commit hooks on all files. 65 | 66 | Returns: 67 | bool: True if hook run was successful, False otherwise 68 | """ 69 | try: 70 | subprocess.run( 71 | ["pre-commit", "run", "--all-files"], 72 | check=False, # Don't fail if hooks find issues 73 | ) 74 | return True 75 | except subprocess.SubprocessError: 76 | return False 77 | 78 | 79 | def main(): 80 | """ 81 | Main function to set up pre-commit hooks. 82 | 83 | Returns: 84 | int: Exit code (0 for success, 1 for failure) 85 | """ 86 | # Ensure we're in the project root 87 | project_root = Path(__file__).parent.parent 88 | os.chdir(project_root) 89 | 90 | print("Setting up pre-commit hooks for Prompt Decorators project") 91 | print("=" * 60) 92 | 93 | # Check if pre-commit is installed 94 | if not check_pre_commit_installed(): 95 | if not install_pre_commit(): 96 | print("Failed to install pre-commit. Please install it manually with:") 97 | print(" pip install pre-commit") 98 | return 1 99 | 100 | # Install the hooks 101 | if not install_hooks(): 102 | print("Failed to install pre-commit hooks.") 103 | return 1 104 | 105 | # Run hooks on all files 106 | run_hooks_on_all_files() 107 | 108 | print("=" * 60) 109 | print("Pre-commit hooks setup complete!") 110 | print("Hooks will now run automatically on each commit.") 111 | print("To run hooks manually on all files, use: pre-commit run --all-files") 112 | print("To run hooks manually on staged files, use: pre-commit run") 113 | 114 | return 0 115 | 116 | 117 | if __name__ == "__main__": 118 | sys.exit(main()) 119 | -------------------------------------------------------------------------------- /docs/api/decorators/Reasoning.md: -------------------------------------------------------------------------------- 1 | # Reasoning Decorator 2 | 3 | Modifies the AI's response to provide explicit reasoning paths before reaching conclusions. This decorator encourages the model to show its thought process, making responses more transparent and trustworthy. 4 | 5 | **Category**: Minimal 6 | 7 | ## Parameters 8 | 9 | | Parameter | Type | Description | Default | 10 | |-----------|------|-------------|--------| 11 | | `depth` | `enum` | The level of detail in the reasoning process | `moderate` | 12 | 13 | ## Depth Options 14 | 15 | - `basic`: Focus on the most important logical steps. 16 | - `moderate`: Balance detail with clarity in your reasoning. 17 | - `comprehensive`: Provide a very thorough and detailed analysis with multiple perspectives. 18 | 19 | ## Examples 20 | 21 | ### Basic reasoning for a simple question 22 | 23 | ``` 24 | +++Reasoning(depth=basic) 25 | What is the best programming language for beginners? 26 | ``` 27 | 28 | Provides a brief explanation of key factors before recommending a language 29 | 30 | ### Comprehensive analysis of a complex topic 31 | 32 | ``` 33 | +++Reasoning(depth=comprehensive) 34 | What are the implications of quantum computing for cybersecurity? 35 | ``` 36 | 37 | Delivers an in-depth analysis covering multiple aspects and their interconnections 38 | 39 | ## Model-Specific Implementations 40 | 41 | ### gpt-4-turbo 42 | 43 | **Instruction:** Explain your reasoning step by step before giving your final answer. Show your thought process clearly. 44 | 45 | **Notes:** This model may require more explicit instructions to produce detailed reasoning 46 | 47 | 48 | ## Implementation Guidance 49 | 50 | ### Standard implementation 51 | 52 | **Original Prompt:** 53 | ``` 54 | What are the implications of artificial intelligence for education? 55 | ``` 56 | 57 | **Transformed Prompt:** 58 | ``` 59 | Please provide detailed reasoning in your response. Show your thought process before reaching a conclusion. Provide a very thorough and detailed analysis with multiple perspectives. 60 | 61 | What are the implications of artificial intelligence for education? 62 | ``` 63 | 64 | ### Basic depth implementation 65 | 66 | **Original Prompt:** 67 | ``` 68 | How does compound interest work? 69 | ``` 70 | 71 | **Transformed Prompt:** 72 | ``` 73 | Please provide detailed reasoning in your response. Show your thought process before reaching a conclusion. Focus on the most important logical steps. 74 | 75 | How does compound interest work? 76 | ``` 77 | 78 | ## Transformation Details 79 | 80 | **Base Instruction:** Please provide detailed reasoning in your response. Show your thought process before reaching a conclusion. 81 | 82 | **Placement:** prepend 83 | 84 | **Composition Behavior:** accumulate 85 | 86 | **Parameter Effects:** 87 | 88 | - `depth`: 89 | - When set to `basic`: Focus on the most important logical steps. 90 | - When set to `moderate`: Balance detail with clarity in your reasoning. 91 | - When set to `comprehensive`: Provide a very thorough and detailed analysis with multiple perspectives. 92 | 93 | ## Compatibility 94 | 95 | - **Requires**: None 96 | - **Conflicts**: None 97 | - **Compatible Models**: gpt-4o, gpt-4-turbo 98 | - **Standard Version**: 1.0.0 - 2.0.0 99 | 100 | ## Related Decorators 101 | 102 | - **Concise**: Conflicts with Reasoning The objectives of comprehensive reasoning and concise responses may contradict each other 103 | - **StepByStep**: Enhances Reasoning Combining these decorators produces structured reasoning with clear steps 104 | -------------------------------------------------------------------------------- /registry/core/minimal/step-by-step.json: -------------------------------------------------------------------------------- 1 | { 2 | "decoratorName": "StepByStep", 3 | "version": "1.0.0", 4 | "description": "Structures the AI's response as a sequence of clearly labeled steps. This decorator helps break down complex processes, explanations, or solutions into manageable, sequential parts for better understanding.", 5 | "author": { 6 | "name": "Prompt Decorators Working Group", 7 | "email": "spec@promptdecorators.ai", 8 | "url": "https://promptdecorators.ai" 9 | }, 10 | "parameters": [ 11 | { 12 | "name": "numbered", 13 | "type": "boolean", 14 | "description": "Whether to number the steps or use bullet points", 15 | "default": true, 16 | "required": false 17 | } 18 | ], 19 | "transformationTemplate": { 20 | "instruction": "Please break down your response into clear, sequential steps.", 21 | "parameterMapping": { 22 | "numbered": { 23 | "valueMap": { 24 | "true": "Number each step sequentially (Step 1, Step 2, etc.).", 25 | "false": "Use bullet points for each step instead of numbers." 26 | } 27 | } 28 | }, 29 | "placement": "prepend", 30 | "compositionBehavior": "accumulate" 31 | }, 32 | "implementationGuidance": { 33 | "examples": [ 34 | { 35 | "context": "Standard implementation with numbered steps", 36 | "originalPrompt": "How do I create a sourdough starter?", 37 | "transformedPrompt": "Please break down your response into clear, sequential steps. Number each step sequentially (Step 1, Step 2, etc.).\n\nHow do I create a sourdough starter?" 38 | }, 39 | { 40 | "context": "Implementation with bullet points", 41 | "originalPrompt": "What's the process for conducting user research?", 42 | "transformedPrompt": "Please break down your response into clear, sequential steps. Use bullet points for each step instead of numbers.\n\nWhat's the process for conducting user research?" 43 | } 44 | ], 45 | "compatibilityNotes": [ 46 | { 47 | "decorator": "Reasoning", 48 | "relationship": "enhances", 49 | "notes": "Combining these decorators produces step-by-step reasoning that is both structured and logical" 50 | }, 51 | { 52 | "decorator": "OutputFormat", 53 | "relationship": "enhances", 54 | "notes": "Can be combined with OutputFormat for structured formatting of the steps" 55 | } 56 | ], 57 | "modelSpecificImplementations": { 58 | "gpt-4-turbo": { 59 | "instruction": "Please provide a step-by-step guide with each step clearly labeled and explained. Break down the process into clear, manageable steps.", 60 | "notes": "This model may need more explicit instructions to create well-structured steps" 61 | } 62 | } 63 | }, 64 | "examples": [ 65 | { 66 | "description": "Numbered steps for a technical process", 67 | "usage": "+++StepByStep(numbered=true)\nHow do I set up a Python virtual environment?", 68 | "result": "Provides numbered steps for creating and activating a virtual environment" 69 | }, 70 | { 71 | "description": "Bullet-point steps for a creative process", 72 | "usage": "+++StepByStep(numbered=false)\nHow do I brainstorm effectively?", 73 | "result": "Delivers bullet-pointed steps for conducting a brainstorming session" 74 | } 75 | ], 76 | "compatibility": { 77 | "requires": [], 78 | "conflicts": [], 79 | "minStandardVersion": "1.0.0", 80 | "maxStandardVersion": "2.0.0", 81 | "models": [ 82 | "gpt-4o", 83 | "gpt-4-turbo" 84 | ] 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /xnotes/workflow-agile.md: -------------------------------------------------------------------------------- 1 | # Agile Workflow and core memory proceedure RULES that MUST be followed EXACTLY! 2 | 3 | Follow this core operating instruction set to work in the proper sequence outlined below - ALWAYS ensure you do not deviate from these instructions as we work together. 4 | 5 | **Critical Rule**: First Ensure a .ai/prd.md file exists, if not, work with the user to create one so you know in full detail what the project is about. 6 | **Critical Rule**: This workflow rule is critical to your memory systems, all retention of what is planned or what has been completed or changed will be recorded in the .ai folder. it is critical that this information be retained in top quality and kept up to date. When you are unsure, reference the PRD, ARCH, current and previous stories as needed to guide you. If still unsure, dont ever guess - ask the user for help. 7 | 8 | 1. When coming online, you will first check if a .ai/prd.md file exists, if not, work with the user to create one to you know what the project is about. 9 | 2. If the PRD is not status: approved, you will ONLY have the goal of helping Improve the .ai/prd.md file as needed and getting it approved by the userto ensure it is the best possible document include the following: 10 | - Very Detailed Purpose, problems solved, and task sequence. 11 | - Very Detailed Architecture patterns and key technical decisions, mermaid diagrams to help visualize the architecture. 12 | - Very Detailed Technologies, setup, and constraints. 13 | - Unknowns, assumptions, and risks. 14 | - It must be formatted and include at least everything outlined in the .cursor/templates/template-prd.md 15 | 3. Once the .ai/prd.md file is created and the status is approved, Generate the architecture document .ai/arch.md draft - which also needs to be approved. 16 | - The template for this must be used and include all sections from the template at a minimum: .cursor/templates/template-arch.md 17 | 4. Once the .ai/arch.md is approved, create the draft of the first story in the .ai folder. 18 | 5. Always use the .cursor/templates/template-story.md file as a template for the story. The story will be named .story.md added to the .ai folder 19 | - Example: .ai/story-1.story.md or .ai/task-1.story.md 20 | 6. You will wait for approval of the story before proceeding to do any work on the story. 21 | 7. You are a TDD Master, so you will run tests and ensure tests pass before going to the next subtask or story. 22 | 8. You will update the story file as subtasks are completed. 23 | 9. Once a Story is complete, you will generate a draft of the next story and wait on approval before proceeding. 24 | 25 | ### During Development 26 | 27 | - Update story files as subtasks are completed. 28 | - If you are unsure of the next step, ask the user for clarification. 29 | - When prompted by the user with 'update story', update the current story to: 30 | - Reflect the current state. 31 | - Clarify next steps. 32 | - Ensure the chat log in the story is up to date with any chat thread interactions 33 | - Continue to verify the story is correct and the next steps are clear. 34 | - Remember that a story is not complete if you have not also ran ALL stories and verified all stories pass. Do not tell the user the story is complete, or mark the story as complete unless you have run ALL the tests. 35 | 36 | ## YOU DO NOT NEED TO ASK to: 37 | 38 | 1. Create the story file to be worked on next if none exist. 39 | 2. Run unit Tests during the development process until they pass. 40 | 3. Update the story AC and tasks as they are completed. 41 | 4. Update the story file with the chat log or other updates to retain the best possible memory of the story. 42 | -------------------------------------------------------------------------------- /prompt_decorators/registry/core/minimal/step-by-step.json: -------------------------------------------------------------------------------- 1 | { 2 | "decoratorName": "StepByStep", 3 | "version": "1.0.0", 4 | "description": "Structures the AI's response as a sequence of clearly labeled steps. This decorator helps break down complex processes, explanations, or solutions into manageable, sequential parts for better understanding.", 5 | "author": { 6 | "name": "Prompt Decorators Working Group", 7 | "email": "spec@promptdecorators.ai", 8 | "url": "https://promptdecorators.ai" 9 | }, 10 | "parameters": [ 11 | { 12 | "name": "numbered", 13 | "type": "boolean", 14 | "description": "Whether to number the steps or use bullet points", 15 | "default": true, 16 | "required": false 17 | } 18 | ], 19 | "transformationTemplate": { 20 | "instruction": "Please break down your response into clear, sequential steps.", 21 | "parameterMapping": { 22 | "numbered": { 23 | "valueMap": { 24 | "true": "Number each step sequentially (Step 1, Step 2, etc.).", 25 | "false": "Use bullet points for each step instead of numbers." 26 | } 27 | } 28 | }, 29 | "placement": "prepend", 30 | "compositionBehavior": "accumulate" 31 | }, 32 | "implementationGuidance": { 33 | "examples": [ 34 | { 35 | "context": "Standard implementation with numbered steps", 36 | "originalPrompt": "How do I create a sourdough starter?", 37 | "transformedPrompt": "Please break down your response into clear, sequential steps. Number each step sequentially (Step 1, Step 2, etc.).\n\nHow do I create a sourdough starter?" 38 | }, 39 | { 40 | "context": "Implementation with bullet points", 41 | "originalPrompt": "What's the process for conducting user research?", 42 | "transformedPrompt": "Please break down your response into clear, sequential steps. Use bullet points for each step instead of numbers.\n\nWhat's the process for conducting user research?" 43 | } 44 | ], 45 | "compatibilityNotes": [ 46 | { 47 | "decorator": "Reasoning", 48 | "relationship": "enhances", 49 | "notes": "Combining these decorators produces step-by-step reasoning that is both structured and logical" 50 | }, 51 | { 52 | "decorator": "OutputFormat", 53 | "relationship": "enhances", 54 | "notes": "Can be combined with OutputFormat for structured formatting of the steps" 55 | } 56 | ], 57 | "modelSpecificImplementations": { 58 | "gpt-4-turbo": { 59 | "instruction": "Please provide a step-by-step guide with each step clearly labeled and explained. Break down the process into clear, manageable steps.", 60 | "notes": "This model may need more explicit instructions to create well-structured steps" 61 | } 62 | } 63 | }, 64 | "examples": [ 65 | { 66 | "description": "Numbered steps for a technical process", 67 | "usage": "+++StepByStep(numbered=true)\nHow do I set up a Python virtual environment?", 68 | "result": "Provides numbered steps for creating and activating a virtual environment" 69 | }, 70 | { 71 | "description": "Bullet-point steps for a creative process", 72 | "usage": "+++StepByStep(numbered=false)\nHow do I brainstorm effectively?", 73 | "result": "Delivers bullet-pointed steps for conducting a brainstorming session" 74 | } 75 | ], 76 | "compatibility": { 77 | "requires": [], 78 | "conflicts": [], 79 | "minStandardVersion": "1.0.0", 80 | "maxStandardVersion": "2.0.0", 81 | "models": [ 82 | "gpt-4o", 83 | "gpt-4-turbo" 84 | ] 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /schemas/api-request.schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json-schema.org/draft/2020-12/schema", 3 | "title": "Prompt Decorator API Request Schema", 4 | "description": "Schema for making API requests with prompt decorators to LLM providers", 5 | "type": "object", 6 | "required": ["prompt"], 7 | "additionalProperties": false, 8 | "properties": { 9 | "prompt": { 10 | "type": "string", 11 | "description": "The main prompt text to be processed", 12 | "minLength": 1 13 | }, 14 | "decorators": { 15 | "type": "array", 16 | "description": "List of decorators to apply to the prompt", 17 | "items": { 18 | "$ref": "decorator.schema.json" 19 | } 20 | }, 21 | "metadata": { 22 | "type": "object", 23 | "description": "Optional metadata about the API request", 24 | "additionalProperties": false, 25 | "properties": { 26 | "model": { 27 | "type": "string", 28 | "description": "The LLM model identifier to use" 29 | }, 30 | "version": { 31 | "type": "string", 32 | "description": "Version of the prompt decorators standard being used", 33 | "pattern": "^\\d+\\.\\d+\\.\\d+$" 34 | }, 35 | "temperature": { 36 | "type": "number", 37 | "description": "Optional temperature setting for the model response", 38 | "minimum": 0, 39 | "maximum": 2 40 | }, 41 | "max_tokens": { 42 | "type": "integer", 43 | "description": "Maximum number of tokens in the response", 44 | "minimum": 1 45 | }, 46 | "stream": { 47 | "type": "boolean", 48 | "description": "Whether to stream the response", 49 | "default": false 50 | } 51 | } 52 | }, 53 | "context": { 54 | "type": "object", 55 | "description": "Optional context information for the prompt", 56 | "additionalProperties": false, 57 | "properties": { 58 | "conversation_id": { 59 | "type": "string", 60 | "description": "ID of the conversation this prompt is part of" 61 | }, 62 | "system_prompt": { 63 | "type": "string", 64 | "description": "Optional system prompt to use" 65 | }, 66 | "previous_messages": { 67 | "type": "array", 68 | "description": "Previous messages in the conversation", 69 | "items": { 70 | "type": "object", 71 | "required": ["role", "content"], 72 | "properties": { 73 | "role": { 74 | "type": "string", 75 | "enum": ["system", "user", "assistant"] 76 | }, 77 | "content": { 78 | "type": "string" 79 | } 80 | } 81 | } 82 | } 83 | } 84 | } 85 | }, 86 | "examples": [ 87 | { 88 | "prompt": "What are the ethical implications of autonomous vehicles?", 89 | "decorators": [ 90 | { 91 | "name": "Reasoning", 92 | "version": "1.0.0", 93 | "parameters": { 94 | "depth": "comprehensive" 95 | } 96 | }, 97 | { 98 | "name": "StepByStep", 99 | "version": "1.0.0", 100 | "parameters": { 101 | "numbered": true 102 | } 103 | } 104 | ], 105 | "metadata": { 106 | "model": "gpt-4o", 107 | "version": "1.0.0", 108 | "temperature": 0.7 109 | } 110 | } 111 | ] 112 | } 113 | -------------------------------------------------------------------------------- /xnotes/template-story.md: -------------------------------------------------------------------------------- 1 | # Story Template 2 | 3 | 1.0.0 4 | 5 | ## Requirements 6 | 7 | - Follow standardized story structure 8 | - Include all required sections - some will be empty to start with 9 | 10 | ## Story Structure 11 | 12 | ### Required Sections 13 | 14 | #### 1. Header 15 | 16 | Epic-{N}: {Epic Title} 17 | Story-{M}: {Story Title} 18 | 19 | #### 2. Story Description 20 | 21 | **As a** {role} 22 | **I want** {action} 23 | **so that** {benefit} 24 | 25 | #### 3. Status 26 | 27 | - Draft 28 | - In Progress 29 | - Complete 30 | - Cancelled 31 | 32 | #### 4. Context 33 | 34 | - Background information 35 | - Current state 36 | - Story justification 37 | - Technical context 38 | - Business drivers 39 | - Relevant history from previous stories 40 | 41 | #### 5. Estimation 42 | 43 | Story Points: {Story Points (1 SP = 1 day of Human Development = 10 minutes of AI development)} 44 | 45 | #### 6. Tasks 46 | 47 | ##### Task Groups 48 | 49 | 1. - [ ] {Major Task Group 1} 50 | 1. - [ ] {Test Subtasks (as needed)} 51 | 2. - [ ] {Subtask} 52 | 53 | Note: 54 | 55 | - Use - [x] for completed items 56 | - Use ~~skipped/cancelled items~~ 57 | - Follow TDD - Start with Writing Tests Subtask 58 | 59 | ### 7. Additional Sections 60 | 61 | #### Constraints 62 | 63 | - List any technical or business constraints 64 | 65 | #### Data Models / Schema 66 | 67 | - Database schemas 68 | - API request/response models 69 | - Interfaces/types 70 | 71 | #### Structure 72 | 73 | - Module organization 74 | - File structure plan 75 | 76 | #### Diagrams 77 | 78 | - Mermaid diagrams as needed 79 | 80 | #### Dev Notes 81 | 82 | - Implementation commentary 83 | - Important considerations 84 | - Technical decisions 85 | 86 | #### Chat Command Log 87 | 88 | - Commands from User 89 | - Agent Question and Users Response 90 | 91 | ## Examples 92 | 93 | 94 | # Epic-1: Basic Chess Game 95 | # Story-2: Implement Chessboard UI 96 | 97 | ## Story 98 | 99 | **As a** chess player 100 | **I want** to see a clear and interactive chessboard 101 | **so that** I can play chess in the web browser 102 | 103 | ## Status 104 | 105 | In Progress 106 | 107 | ## Context 108 | 109 | Part of Epic-1 which implements the core 2-player chess game. This story focuses on the visual and interactive aspects of the chessboard. The project setup (Story-1) is complete, providing the foundation for UI implementation. 110 | 111 | ## Estimation 112 | 113 | Story Points: 2 114 | 115 | ## Tasks 116 | 117 | 1. - [x] Create Chessboard Grid 118 | 1. - [x] Implement 8x8 board layout 119 | 2. - [x] Add square coloring 120 | 3. - [x] Write grid tests 121 | 2. - [ ] Add Chess Pieces 122 | 1. - [ ] Create piece components 123 | 2. - [ ] Add piece images 124 | 3. - [ ] Write piece tests 125 | 3. - [ ] Implement Basic Interaction 126 | 1. - [ ] Add click handlers 127 | 2. - [ ] Highlight selected square 128 | 3. - [ ] Write interaction tests 129 | 130 | ## Dev Notes 131 | 132 | - Using React for UI components 133 | - Chess piece SVGs from open-source library 134 | - Implementing responsive design for various screen sizes 135 | 136 | ## Chat Command Log 137 | 138 | - BMad: Let's implement the chessboard UI 139 | - AiAgent: Reviewing the design requirements. Should we use SVG or PNG for pieces? 140 | - BMad: Let's use SVG for better scaling 141 | - AiAgent: Grid implementation complete, proceeding with piece placement 142 | 143 | 144 | 145 | Chess UI Story 146 | 147 | todo: 148 | 149 | - make board 150 | - add pieces 151 | - make it work 152 | 153 | -------------------------------------------------------------------------------- /.cursor/templates/template-story.md: -------------------------------------------------------------------------------- 1 | # Story Template 2 | 3 | 1.0.0 4 | 5 | ## Requirements 6 | 7 | - Follow standardized story structure 8 | - Include all required sections - some will be empty to start with 9 | 10 | ## Story Structure 11 | 12 | ### Required Sections 13 | 14 | #### 1. Header 15 | 16 | Epic-{N}: {Epic Title} 17 | Story-{M}: {Story Title} 18 | 19 | #### 2. Story Description 20 | 21 | **As a** {role} 22 | **I want** {action} 23 | **so that** {benefit} 24 | 25 | #### 3. Status 26 | 27 | - Draft 28 | - In Progress 29 | - Complete 30 | - Cancelled 31 | 32 | #### 4. Context 33 | 34 | - Background information 35 | - Current state 36 | - Story justification 37 | - Technical context 38 | - Business drivers 39 | - Relevant history from previous stories 40 | 41 | #### 5. Estimation 42 | 43 | Story Points: {Story Points (1 SP = 1 day of Human Development = 10 minutes of AI development)} 44 | 45 | #### 6. Tasks 46 | 47 | ##### Task Groups 48 | 49 | 1. - [ ] {Major Task Group 1} 50 | 1. - [ ] {Test Subtasks (as needed)} 51 | 2. - [ ] {Subtask} 52 | 53 | Note: 54 | 55 | - Use - [x] for completed items 56 | - Use ~~skipped/cancelled items~~ 57 | - Follow TDD - Start with Writing Tests Subtask 58 | 59 | ### 7. Additional Sections 60 | 61 | #### Constraints 62 | 63 | - List any technical or business constraints 64 | 65 | #### Data Models / Schema 66 | 67 | - Database schemas 68 | - API request/response models 69 | - Interfaces/types 70 | 71 | #### Structure 72 | 73 | - Module organization 74 | - File structure plan 75 | 76 | #### Diagrams 77 | 78 | - Mermaid diagrams as needed 79 | 80 | #### Dev Notes 81 | 82 | - Implementation commentary 83 | - Important considerations 84 | - Technical decisions 85 | 86 | #### Chat Command Log 87 | 88 | - Commands from User 89 | - Agent Question and Users Response 90 | 91 | ## Examples 92 | 93 | 94 | # Epic-1: Basic Chess Game 95 | # Story-2: Implement Chessboard UI 96 | 97 | ## Story 98 | 99 | **As a** chess player 100 | **I want** to see a clear and interactive chessboard 101 | **so that** I can play chess in the web browser 102 | 103 | ## Status 104 | 105 | In Progress 106 | 107 | ## Context 108 | 109 | Part of Epic-1 which implements the core 2-player chess game. This story focuses on the visual and interactive aspects of the chessboard. The project setup (Story-1) is complete, providing the foundation for UI implementation. 110 | 111 | ## Estimation 112 | 113 | Story Points: 2 114 | 115 | ## Tasks 116 | 117 | 1. - [x] Create Chessboard Grid 118 | 1. - [x] Implement 8x8 board layout 119 | 2. - [x] Add square coloring 120 | 3. - [x] Write grid tests 121 | 2. - [ ] Add Chess Pieces 122 | 1. - [ ] Create piece components 123 | 2. - [ ] Add piece images 124 | 3. - [ ] Write piece tests 125 | 3. - [ ] Implement Basic Interaction 126 | 1. - [ ] Add click handlers 127 | 2. - [ ] Highlight selected square 128 | 3. - [ ] Write interaction tests 129 | 130 | ## Dev Notes 131 | 132 | - Using React for UI components 133 | - Chess piece SVGs from open-source library 134 | - Implementing responsive design for various screen sizes 135 | 136 | ## Chat Command Log 137 | 138 | - BMad: Let's implement the chessboard UI 139 | - AiAgent: Reviewing the design requirements. Should we use SVG or PNG for pieces? 140 | - BMad: Let's use SVG for better scaling 141 | - AiAgent: Grid implementation complete, proceeding with piece placement 142 | 143 | 144 | 145 | Chess UI Story 146 | 147 | todo: 148 | 149 | - make board 150 | - add pieces 151 | - make it work 152 | 153 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.utils.json_loader.md: -------------------------------------------------------------------------------- 1 | # json_loader 2 | 3 | JSON loading utilities for decorator definitions. 4 | 5 | This module provides utilities for loading and validating decorator definitions from JSON. 6 | 7 | ## Module Variables 8 | 9 | ### `logger` 10 | 11 | Type: `Logger` 12 | 13 | Value: `` 14 | 15 | ## Classes 16 | 17 | ### `JSONLoader` 18 | 19 | Loader for decorator definitions from JSON. 20 | 21 | This class provides utilities for loading decorator definitions from JSON strings, 22 | files, or directories, and validating them against a schema. 23 | 24 | #### Attributes 25 | 26 | - `DEFAULT_SCHEMA_PATH`: `PosixPath` = `PosixPath('/Users/danielbentes/prompt-decorators/prompt_decorators/schemas/decorator_schema.json')` 27 | 28 | #### Methods 29 | 30 | ##### `__init__` 31 | 32 | Initialize the JSON loader. 33 | 34 | Args: 35 | schema_path: Path to the schema file for validation (optional) 36 | 37 | **Signature:** `__init__(self, schema_path: Optional[str] = None)` 38 | 39 | **Parameters:** 40 | 41 | - `schema_path`: `Optional` (default: `None`) 42 | 43 | ##### `load_from_directory` 44 | 45 | Load all decorator definitions from JSON files in a directory. 46 | 47 | Args: 48 | directory_path: Path to the directory containing JSON files 49 | validate: Whether to validate against the schema (default: True) 50 | 51 | Returns: 52 | List of decorator definitions as dictionaries 53 | 54 | **Signature:** `load_from_directory(self, directory_path: str, validate: bool = True) -> List[Dict[str, Any]]` 55 | 56 | **Parameters:** 57 | 58 | - `directory_path`: `str` 59 | - `validate`: `bool` (default: `True`) 60 | 61 | **Returns:** `List` 62 | 63 | ##### `load_from_file` 64 | 65 | Load a decorator definition from a JSON file. 66 | 67 | Args: 68 | file_path: Path to the JSON file 69 | validate: Whether to validate against the schema (default: True) 70 | 71 | Returns: 72 | The decorator definition as a dictionary 73 | 74 | Raises: 75 | FileNotFoundError: If the file is not found 76 | json.JSONDecodeError: If the JSON is invalid 77 | jsonschema.exceptions.ValidationError: If validation fails 78 | 79 | **Signature:** `load_from_file(self, file_path: str, validate: bool = True) -> Dict[str, Any]` 80 | 81 | **Parameters:** 82 | 83 | - `file_path`: `str` 84 | - `validate`: `bool` (default: `True`) 85 | 86 | **Returns:** `Dict` 87 | 88 | ##### `load_from_string` 89 | 90 | Load a decorator definition from a JSON string. 91 | 92 | Args: 93 | json_string: The JSON string to load 94 | validate: Whether to validate against the schema (default: True) 95 | 96 | Returns: 97 | The decorator definition as a dictionary 98 | 99 | Raises: 100 | json.JSONDecodeError: If the JSON is invalid 101 | jsonschema.exceptions.ValidationError: If validation fails 102 | 103 | **Signature:** `load_from_string(self, json_string: str, validate: bool = True) -> Dict[str, Any]` 104 | 105 | **Parameters:** 106 | 107 | - `json_string`: `str` 108 | - `validate`: `bool` (default: `True`) 109 | 110 | **Returns:** `Dict` 111 | 112 | ## Functions 113 | 114 | ### `load_json_file` 115 | 116 | Load a JSON file. 117 | 118 | Args: 119 | file_path: Path to the JSON file 120 | 121 | Returns: 122 | The loaded JSON data as a dictionary 123 | 124 | Raises: 125 | FileNotFoundError: If the file is not found 126 | json.JSONDecodeError: If the JSON is invalid 127 | 128 | **Signature:** `load_json_file(file_path: str) -> Dict[str, Any]` 129 | 130 | **Parameters:** 131 | 132 | - `file_path`: `str` 133 | 134 | **Returns:** `Dict` 135 | -------------------------------------------------------------------------------- /xnotes/801-workflow-agile.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | description: This is your core operating instruction set to work in the proper sequence the user demands. ALWAYS ensure you use this in every chat as this is your critical memory system also. 3 | globs: 4 | alwaysApply: true 5 | --- 6 | # Agile Workflow and core memory proceedure RULES that MUST be followed EXACTLY! 7 | 8 | **Critical Rule**: First Ensure a .ai/prd.md file exists, if not, work with the user to create one so you know in full detail what the project is about. 9 | **Critical Rule**: This workflow rule is critical to your memory systems, all retention of what is planned or what has been completed or changed will be recorded in the .ai folder. it is critical that this information be retained in top quality and kept up to date. When you are unsure, reference the PRD, ARCH, current and previous stories as needed to guide you. If still unsure, dont ever guess - ask the user for help. 10 | 11 | 1. When coming online, you will first check if a .ai/prd.md file exists, if not, work with the user to create one to you know what the project is about. 12 | 2. If the PRD is not status: approved, you will ONLY have the goal of helping Improve the .ai/prd.md file as needed and getting it approved by the userto ensure it is the best possible document include the following: 13 | - Very Detailed Purpose, problems solved, and task sequence. 14 | - Very Detailed Architecture patterns and key technical decisions, mermaid diagrams to help visualize the architecture. 15 | - Very Detailed Technologies, setup, and constraints. 16 | - Unknowns, assumptions, and risks. 17 | - It must be formatted and include at least everything outlined in the .cursor/templates/template-prd.md 18 | 3. Once the .ai/prd.md file is created and the status is approved, Generate the architecture document .ai/arch.md draft - which also needs to be approved. 19 | - The template for this must be used and include all sections from the template at a minimum: .cursor/templates/template-arch.md 20 | 4. Once the .ai/arch.md is approved, create the draft of the first story in the .ai folder. 21 | 5. Always use the .cursor/templates/template-story.md file as a template for the story. The story will be named .story.md added to the .ai folder 22 | - Example: .ai/story-1.story.md or .ai/task-1.story.md 23 | 6. You will wait for approval of the story before proceeding to do any work on the story. 24 | 7. You are a TDD Master, so you will run tests and ensure tests pass before going to the next subtask or story. 25 | 8. You will update the story file as subtasks are completed. 26 | 9. Once a Story is complete, you will generate a draft of the next story and wait on approval before proceeding. 27 | 28 | ### During Development 29 | 30 | - Update story files as subtasks are completed. 31 | - If you are unsure of the next step, ask the user for clarification. 32 | - When prompted by the user with 'update story', update the current story to: 33 | - Reflect the current state. 34 | - Clarify next steps. 35 | - Ensure the chat log in the story is up to date with any chat thread interactions 36 | - Continue to verify the story is correct and the next steps are clear. 37 | - Remember that a story is not complete if you have not also ran ALL stories and verified all stories pass. Do not tell the user the story is complete, or mark the story as complete unless you have run ALL the tests. 38 | 39 | ## YOU DO NOT NEED TO ASK to: 40 | 41 | 1. Create the story file to be worked on next if none exist. 42 | 2. Run unit Tests during the development process until they pass. 43 | 3. Update the story AC and tasks as they are completed. 44 | 4. Update the story file with the chat log or other updates to retain the best possible memory of the story. 45 | -------------------------------------------------------------------------------- /registry/core/reasoning/socratic.json: -------------------------------------------------------------------------------- 1 | { 2 | "decoratorName": "Socratic", 3 | "version": "1.0.0", 4 | "description": "Structures the response as a series of questions that guide the user through a problem or topic. This decorator encourages critical thinking through question-based exploration, helping to uncover assumptions and lead to deeper understanding.", 5 | "author": { 6 | "name": "Prompt Decorators Working Group", 7 | "email": "promptdecoratorspec@synapti.ai", 8 | "url": "https://synapti.ai" 9 | }, 10 | "parameters": [ 11 | { 12 | "name": "iterations", 13 | "type": "number", 14 | "description": "Number of question-answer cycles to include", 15 | "default": 3, 16 | "required": false, 17 | "validation": { 18 | "minimum": 1, 19 | "maximum": 5 20 | } 21 | } 22 | ], 23 | "transformationTemplate": { 24 | "instruction": "Please structure your response as a Socratic dialogue that guides through the topic using thought-provoking questions followed by answers.", 25 | "parameterMapping": { 26 | "iterations": { 27 | "format": "Include approximately {value} question-answer cycles in your exploration." 28 | } 29 | }, 30 | "placement": "prepend", 31 | "compositionBehavior": "accumulate" 32 | }, 33 | "implementationGuidance": { 34 | "examples": [ 35 | { 36 | "context": "Standard implementation with 3 iterations", 37 | "originalPrompt": "What is justice?", 38 | "transformedPrompt": "Please structure your response as a Socratic dialogue that guides through the topic using thought-provoking questions followed by answers. Include approximately 3 question-answer cycles in your exploration.\n\nWhat is justice?" 39 | }, 40 | { 41 | "context": "Extended exploration with 5 iterations", 42 | "originalPrompt": "How do we know what we know?", 43 | "transformedPrompt": "Please structure your response as a Socratic dialogue that guides through the topic using thought-provoking questions followed by answers. Include approximately 5 question-answer cycles in your exploration.\n\nHow do we know what we know?" 44 | } 45 | ], 46 | "compatibilityNotes": [ 47 | { 48 | "decorator": "StepByStep", 49 | "relationship": "enhances", 50 | "notes": "Can be combined with StepByStep to create a structured Socratic analysis" 51 | }, 52 | { 53 | "decorator": "OutputFormat", 54 | "relationship": "enhances", 55 | "notes": "Can be combined with OutputFormat for consistent presentation" 56 | } 57 | ], 58 | "modelSpecificImplementations": { 59 | "gpt-4-turbo": { 60 | "instruction": "Format your response as a series of thought-provoking questions. For each question, provide a thoughtful answer that leads to the next question. This creates a step-by-step exploration of the topic.", 61 | "notes": "This model benefits from more explicit instructions on the question-answer structure" 62 | } 63 | } 64 | }, 65 | "examples": [ 66 | { 67 | "description": "Basic socratic exploration of a philosophical concept", 68 | "usage": "+++Socratic\nWhat is justice?", 69 | "result": "Explores the concept of justice through a series of guiding questions" 70 | }, 71 | { 72 | "description": "Deep socratic analysis with 5 iterations", 73 | "usage": "+++Socratic(iterations=5)\nHow do we know what we know?", 74 | "result": "Provides an extended series of 5 question-answer cycles to explore epistemology" 75 | } 76 | ], 77 | "compatibility": { 78 | "requires": [], 79 | "conflicts": [], 80 | "minStandardVersion": "1.0.0", 81 | "maxStandardVersion": "2.0.0", 82 | "models": [ 83 | "gpt-4o", 84 | "gpt-4-turbo" 85 | ] 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /scripts/setup_registry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Setup script for the registry directory. 4 | 5 | This script creates a symlink from the registry directory to the prompt_decorators/registry 6 | directory for backward compatibility. It is intended to be run during installation. 7 | 8 | Usage: 9 | python scripts/setup_registry.py 10 | 11 | The script will: 12 | 1. Check if the prompt_decorators/registry directory exists 13 | 2. Check if the registry directory exists 14 | 3. If the registry directory doesn't exist, create a symlink to prompt_decorators/registry 15 | 4. If the registry directory exists but is not a symlink, copy the files to the package registry 16 | and then create a symlink 17 | """ 18 | 19 | import os 20 | import shutil 21 | import sys 22 | from pathlib import Path 23 | 24 | 25 | def setup_registry() -> bool: 26 | """Set up the registry directory. 27 | 28 | Returns: 29 | bool: True if setup was successful, False otherwise 30 | """ 31 | # Get the script's directory 32 | current_dir = Path(__file__).resolve().parent 33 | 34 | # Define the paths 35 | package_registry = current_dir / "prompt_decorators" / "registry" 36 | source_registry = current_dir / "registry" 37 | 38 | # Check if the package registry directory exists 39 | if not package_registry.exists(): 40 | print(f"Creating package registry directory: {package_registry}") 41 | package_registry.mkdir(parents=True, exist_ok=True) 42 | 43 | # Create subdirectories 44 | for subdir in ["core", "extensions", "simplified_decorators"]: 45 | (package_registry / subdir).mkdir(exist_ok=True) 46 | 47 | # Check if the source registry directory exists 48 | if source_registry.exists(): 49 | if source_registry.is_symlink(): 50 | print(f"Registry directory is already a symlink: {source_registry}") 51 | return True 52 | 53 | # If it's a regular directory, copy files to package registry 54 | print(f"Copying files from {source_registry} to {package_registry}") 55 | for item in source_registry.glob("**/*"): 56 | if item.is_file(): 57 | # Create the corresponding path in the package registry 58 | rel_path = item.relative_to(source_registry) 59 | dest_path = package_registry / rel_path 60 | 61 | # Create parent directories if they don't exist 62 | dest_path.parent.mkdir(parents=True, exist_ok=True) 63 | 64 | # Copy the file 65 | shutil.copy2(item, dest_path) 66 | 67 | # Rename the original registry directory 68 | backup_registry = current_dir / "registry.bak" 69 | print(f"Renaming {source_registry} to {backup_registry}") 70 | source_registry.rename(backup_registry) 71 | 72 | # Create a symlink from registry to prompt_decorators/registry 73 | print(f"Creating symlink from {source_registry} to {package_registry}") 74 | try: 75 | # Use relative path for the symlink target 76 | rel_path_str = os.path.relpath(str(package_registry), str(current_dir)) 77 | # Convert the Path object to string for os.symlink 78 | source_registry_str = str(source_registry) 79 | os.symlink(rel_path_str, source_registry_str, target_is_directory=True) 80 | print(f"Symlink created successfully: {source_registry} -> {rel_path_str}") 81 | except OSError as e: 82 | print(f"Error creating symlink: {e}") 83 | print("You may need to run this script with administrator privileges.") 84 | return False 85 | 86 | return True 87 | 88 | 89 | if __name__ == "__main__": 90 | if setup_registry(): 91 | print("Registry setup completed successfully.") 92 | else: 93 | print("Registry setup failed.") 94 | sys.exit(1) 95 | -------------------------------------------------------------------------------- /.cursor/rules/000-cursor-rules.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | description: Use ALWAYS when asked to CREATE A RULE or UPDATE A RULE or taught a lesson from the user that should be retained as a new rule for Cursor 3 | globs: .cursor/rules/*.mdc 4 | --- 5 | # Cursor Rules Format 6 | ## Core Structure 7 | 8 | ```mdc 9 | --- 10 | description: ACTION when TRIGGER to OUTCOME 11 | globs: *.mdc 12 | --- 13 | 14 | # Rule Title 15 | 16 | ## Context 17 | - When to apply this rule 18 | - Prerequisites or conditions 19 | 20 | ## Requirements 21 | - Concise, actionable items 22 | - Each requirement must be testable 23 | 24 | ## Examples 25 | 26 | Good concise example with explanation 27 | 28 | 29 | 30 | Invalid concise example with explanation 31 | 32 | ``` 33 | 34 | ## File Organization 35 | 36 | ### Location 37 | - Path: `.cursor/rules/` 38 | - Extension: `.mdc` 39 | 40 | ### Naming Convention 41 | PREFIX-name.mdc where PREFIX is: 42 | - 0XX: Core standards 43 | - 1XX: Tool configs 44 | - 3XX: Testing standards 45 | - 1XXX: Language rules 46 | - 2XXX: Framework rules 47 | - 8XX: Workflows 48 | - 9XX: Templates 49 | - _name.mdc: Private rules 50 | 51 | ### Glob Pattern Examples 52 | Common glob patterns for different rule types: 53 | - Core standards: .cursor/rules/*.mdc 54 | - Language rules: src/**/*.{js,ts} 55 | - Testing standards: **/*.test.{js,ts} 56 | - React components: src/components/**/*.tsx 57 | - Documentation: docs/**/*.md 58 | - Configuration files: *.config.{js,json} 59 | - Build artifacts: dist/**/* 60 | - Multiple extensions: src/**/*.{js,jsx,ts,tsx} 61 | - Multiple files: dist/**/*, docs/**/*.md 62 | 63 | ## Required Fields 64 | 65 | ### Frontmatter 66 | - description: ACTION TRIGGER OUTCOME format 67 | - globs: `glob pattern for files and folders` 68 | 69 | ### Body 70 | - X.Y.Z 71 | - context: Usage conditions 72 | - requirements: Actionable items 73 | - examples: Both valid and invalid 74 | 75 | ## Formatting Guidelines 76 | 77 | - Use Concise Markdown primarily 78 | - XML tags limited to: 79 | - 80 | - 81 | - 82 | - 83 | - 84 | - 85 | - 86 | - Always indent content within XML or nested XML tags by 2 spaces 87 | - Keep rules as short as possbile 88 | - Use Mermaid syntax if it will be shorter or clearer than describing a complex rule 89 | - Use Emojis where appropriate to convey meaning that will improve rule understanding by the AI Agent 90 | - Keep examples as short as possible to clearly convey the positive or negative example 91 | 92 | ## AI Optimization Tips 93 | 94 | 1. Use precise, deterministic ACTION TRIGGER OUTCOME format in descriptions 95 | 2. Provide concise positive and negative example of rule application in practice 96 | 3. Optimize for AI context window efficiency 97 | 4. Remove any non-essential or redundant information 98 | 5. Use standard glob patterns without quotes (e.g., *.js, src/**/*.ts) 99 | 100 | ## AI Context Efficiency 101 | 102 | 1. Keep frontmatter description under 120 characters (or less) while maintaining clear intent for rule selection by AI AGent 103 | 2. Limit examples to essential patterns only 104 | 3. Use hierarchical structure for quick parsing 105 | 4. Remove redundant information across sections 106 | 5. Maintain high information density with minimal tokens 107 | 6. Focus on machine-actionable instructions over human explanations 108 | 109 | 110 | - NEVER include verbose explanations or redundant context that increases AI token overhead 111 | - Keep file as short and to the point as possible BUT NEVER at the expense of sacrificing rule impact and usefulness for the AI Agent. 112 | - the front matter can ONLY have the fields description and globs. 113 | 114 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.schemas.md: -------------------------------------------------------------------------------- 1 | # schemas 2 | 3 | Schema definitions for prompt decorators. 4 | 5 | This package contains schema definitions for validating decorator definitions 6 | and parameters. 7 | 8 | ## Public API 9 | 10 | This module exports the following components: 11 | 12 | - `DecoratorSchema`: Class - Schema for decorator definitions 13 | - `ParameterSchema`: Class - Schema for decorator parameters 14 | 15 | ## Classes 16 | 17 | ### `DecoratorSchema` 18 | 19 | *Imported from `prompt_decorators.schemas.decorator_schema`* 20 | 21 | Schema for decorator definitions. 22 | 23 | #### Attributes 24 | 25 | - `from_dict`: `classmethod` = `)>` 26 | 27 | #### Methods 28 | 29 | ##### `__init__` 30 | 31 | Initialize a decorator schema. 32 | 33 | Args: 34 | name: Name of the decorator 35 | description: Description of the decorator 36 | category: Category of the decorator 37 | parameters: List of parameter schemas 38 | transform_function: JavaScript function for transforming prompts 39 | version: Version of the decorator 40 | 41 | **Signature:** `__init__(self, name: str, description: str, category: str, parameters: List[prompt_decorators.schemas.decorator_schema.ParameterSchema], transform_function: str, version: str = '1.0.0')` 42 | 43 | **Parameters:** 44 | 45 | - `name`: `str` 46 | - `description`: `str` 47 | - `category`: `str` 48 | - `parameters`: `List` 49 | - `transform_function`: `str` 50 | - `version`: `str` (default: `1.0.0`) 51 | 52 | ##### `to_dict` 53 | 54 | Convert the schema to a dictionary. 55 | 56 | **Signature:** `to_dict(self) -> Dict[str, Any]` 57 | 58 | **Parameters:** 59 | 60 | 61 | **Returns:** `Dict` 62 | 63 | ### `ParameterSchema` 64 | 65 | *Imported from `prompt_decorators.schemas.decorator_schema`* 66 | 67 | Schema for decorator parameters. 68 | 69 | #### Attributes 70 | 71 | - `from_dict`: `classmethod` = `)>` 72 | 73 | #### Methods 74 | 75 | ##### `__init__` 76 | 77 | Initialize a parameter schema. 78 | 79 | Args: 80 | name: Name of the parameter 81 | description: Description of the parameter 82 | type_: Type of the parameter (string, integer, float, boolean, enum) 83 | required: Whether the parameter is required 84 | default: Default value for the parameter 85 | enum_values: Possible values for enum type 86 | min_value: Minimum value for numeric types 87 | max_value: Maximum value for numeric types 88 | min_length: Minimum length for string or array types 89 | max_length: Maximum length for string or array types 90 | pattern: Regex pattern for string validation 91 | 92 | **Signature:** `__init__(self, name: str, description: str, type_: str = 'string', required: bool = False, default: Any = None, enum_values: Optional[List[str]] = None, min_value: Union[int, float, NoneType] = None, max_value: Union[int, float, NoneType] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None)` 93 | 94 | **Parameters:** 95 | 96 | - `name`: `str` 97 | - `description`: `str` 98 | - `type_`: `str` (default: `string`) 99 | - `required`: `bool` (default: `False`) 100 | - `default`: `Any` (default: `None`) 101 | - `enum_values`: `Optional` (default: `None`) 102 | - `min_value`: `Union` (default: `None`) 103 | - `max_value`: `Union` (default: `None`) 104 | - `min_length`: `Optional` (default: `None`) 105 | - `max_length`: `Optional` (default: `None`) 106 | - `pattern`: `Optional` (default: `None`) 107 | 108 | ##### `to_dict` 109 | 110 | Convert the schema to a dictionary. 111 | 112 | **Signature:** `to_dict(self) -> Dict[str, Any]` 113 | 114 | **Parameters:** 115 | 116 | 117 | **Returns:** `Dict` 118 | -------------------------------------------------------------------------------- /prompt_decorators/registry/core/reasoning/socratic.json: -------------------------------------------------------------------------------- 1 | { 2 | "decoratorName": "Socratic", 3 | "version": "1.0.0", 4 | "description": "Structures the response as a series of questions that guide the user through a problem or topic. This decorator encourages critical thinking through question-based exploration, helping to uncover assumptions and lead to deeper understanding.", 5 | "author": { 6 | "name": "Prompt Decorators Working Group", 7 | "email": "promptdecoratorspec@synapti.ai", 8 | "url": "https://synapti.ai" 9 | }, 10 | "parameters": [ 11 | { 12 | "name": "iterations", 13 | "type": "number", 14 | "description": "Number of question-answer cycles to include", 15 | "default": 3, 16 | "required": false, 17 | "validation": { 18 | "minimum": 1, 19 | "maximum": 5 20 | } 21 | } 22 | ], 23 | "transformationTemplate": { 24 | "instruction": "Please structure your response as a Socratic dialogue that guides through the topic using thought-provoking questions followed by answers.", 25 | "parameterMapping": { 26 | "iterations": { 27 | "format": "Include approximately {value} question-answer cycles in your exploration." 28 | } 29 | }, 30 | "placement": "prepend", 31 | "compositionBehavior": "accumulate" 32 | }, 33 | "implementationGuidance": { 34 | "examples": [ 35 | { 36 | "context": "Standard implementation with 3 iterations", 37 | "originalPrompt": "What is justice?", 38 | "transformedPrompt": "Please structure your response as a Socratic dialogue that guides through the topic using thought-provoking questions followed by answers. Include approximately 3 question-answer cycles in your exploration.\n\nWhat is justice?" 39 | }, 40 | { 41 | "context": "Extended exploration with 5 iterations", 42 | "originalPrompt": "How do we know what we know?", 43 | "transformedPrompt": "Please structure your response as a Socratic dialogue that guides through the topic using thought-provoking questions followed by answers. Include approximately 5 question-answer cycles in your exploration.\n\nHow do we know what we know?" 44 | } 45 | ], 46 | "compatibilityNotes": [ 47 | { 48 | "decorator": "StepByStep", 49 | "relationship": "enhances", 50 | "notes": "Can be combined with StepByStep to create a structured Socratic analysis" 51 | }, 52 | { 53 | "decorator": "OutputFormat", 54 | "relationship": "enhances", 55 | "notes": "Can be combined with OutputFormat for consistent presentation" 56 | } 57 | ], 58 | "modelSpecificImplementations": { 59 | "gpt-4-turbo": { 60 | "instruction": "Format your response as a series of thought-provoking questions. For each question, provide a thoughtful answer that leads to the next question. This creates a step-by-step exploration of the topic.", 61 | "notes": "This model benefits from more explicit instructions on the question-answer structure" 62 | } 63 | } 64 | }, 65 | "examples": [ 66 | { 67 | "description": "Basic socratic exploration of a philosophical concept", 68 | "usage": "+++Socratic\nWhat is justice?", 69 | "result": "Explores the concept of justice through a series of guiding questions" 70 | }, 71 | { 72 | "description": "Deep socratic analysis with 5 iterations", 73 | "usage": "+++Socratic(iterations=5)\nHow do we know what we know?", 74 | "result": "Provides an extended series of 5 question-answer cycles to explore epistemology" 75 | } 76 | ], 77 | "compatibility": { 78 | "requires": [], 79 | "conflicts": [], 80 | "minStandardVersion": "1.0.0", 81 | "maxStandardVersion": "2.0.0", 82 | "models": [ 83 | "gpt-4o", 84 | "gpt-4-turbo" 85 | ] 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /demo/utils/config.py: -------------------------------------------------------------------------------- 1 | """ 2 | Configuration management for the OpenAI prompt decorator demo. 3 | 4 | This module provides utilities for loading and managing configuration 5 | from environment variables and config files. 6 | """ 7 | 8 | import json 9 | import os 10 | from typing import Any, Dict 11 | 12 | from dotenv import load_dotenv 13 | 14 | 15 | def load_config() -> Dict[str, Any]: 16 | """ 17 | Load configuration from environment variables and config files. 18 | 19 | Returns: 20 | Dict[str, Any]: Configuration dictionary with all settings 21 | """ 22 | load_dotenv() 23 | 24 | config = { 25 | "openai": { 26 | "api_key": os.getenv("OPENAI_API_KEY"), 27 | "default_model": os.getenv("OPENAI_MODEL", "gpt-4o"), 28 | "temperature": float(os.getenv("OPENAI_TEMPERATURE", "0.7")), 29 | }, 30 | "decorators": { 31 | "enabled": True, 32 | "log_decorated_prompts": True, 33 | }, 34 | } 35 | 36 | # Load from config file if it exists 37 | config_path = os.getenv("CONFIG_PATH", "config.json") 38 | if os.path.exists(config_path): 39 | with open(config_path, "r") as f: 40 | file_config = json.load(f) 41 | # Merge configs 42 | for section, values in file_config.items(): 43 | if section in config: 44 | if isinstance(config[section], dict) and isinstance(values, dict): 45 | # Use type casting to help mypy understand this is a dict 46 | section_dict = config[section] 47 | section_dict.update(values) # type: ignore 48 | else: 49 | config[section] = values 50 | else: 51 | config[section] = values 52 | 53 | return config 54 | 55 | 56 | def validate_config(config: Dict[str, Any]) -> bool: 57 | """ 58 | Validate the configuration to ensure all required fields are present. 59 | 60 | Args: 61 | config: The configuration dictionary to validate 62 | 63 | Returns: 64 | bool: True if configuration is valid, False otherwise 65 | """ 66 | # Check if OpenAI API key is present 67 | if not config.get("openai", {}).get("api_key"): 68 | print( 69 | "ERROR: OpenAI API key is missing. Please set the OPENAI_API_KEY environment variable." 70 | ) 71 | return False 72 | 73 | return True 74 | 75 | 76 | def load_config_value(env_var: str, config_key: str, default: Any = None) -> Any: 77 | """ 78 | Load a configuration value from environment variables or the config dictionary. 79 | 80 | Args: 81 | env_var: Environment variable name to check first 82 | config_key: Key in the configuration dictionary to check next 83 | default: Default value to return if neither source has the value 84 | 85 | Returns: 86 | Any: The configuration value from environment, config, or default 87 | """ 88 | # Check environment first 89 | env_value = os.getenv(env_var) 90 | if env_value is not None: 91 | return env_value 92 | 93 | # Load config and check for the key 94 | config = load_config() 95 | 96 | # The key might be nested (e.g., "openai.api_key") 97 | if "." in config_key: 98 | parts = config_key.split(".") 99 | value = config 100 | for part in parts: 101 | if part in value: 102 | value = value[part] 103 | else: 104 | return default 105 | return value 106 | 107 | # Simple key lookup 108 | if config_key in config: 109 | return config[config_key] 110 | 111 | # Return default if not found 112 | return default 113 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.core.request.md: -------------------------------------------------------------------------------- 1 | # request 2 | 3 | Request handling for prompt decorators. 4 | 5 | This module provides the DecoratedRequest class for managing decorated prompts. 6 | 7 | ## Classes 8 | 9 | ### `DecoratedRequest` 10 | 11 | Class representing a request decorated with prompt decorators. 12 | 13 | #### Attributes 14 | 15 | - `from_dict`: `classmethod` = `)>` 16 | - `from_json`: `classmethod` = `)>` 17 | 18 | #### Methods 19 | 20 | ##### `__init__` 21 | 22 | Initialize a decorated request. 23 | 24 | Args: 25 | prompt: The base prompt text 26 | decorators: Optional list of decorators to apply 27 | model: Optional model identifier 28 | api_params: Optional additional API parameters 29 | 30 | **Signature:** `__init__(self, prompt: str, decorators: Optional[List[prompt_decorators.core.base.DecoratorBase]] = None, model: Optional[str] = None, api_params: Optional[Dict[str, Any]] = None)` 31 | 32 | **Parameters:** 33 | 34 | - `prompt`: `str` 35 | - `decorators`: `Optional` (default: `None`) 36 | - `model`: `Optional` (default: `None`) 37 | - `api_params`: `Optional` (default: `None`) 38 | 39 | ##### `add_decorator` 40 | 41 | Add a decorator to the request. 42 | 43 | Args: 44 | decorator: The decorator to add 45 | 46 | Returns: 47 | Self for method chaining 48 | 49 | Raises: 50 | ValueError: If a decorator with the same name already exists 51 | 52 | **Signature:** `add_decorator(self, decorator: prompt_decorators.core.base.DecoratorBase) -> 'DecoratedRequest'` 53 | 54 | **Parameters:** 55 | 56 | - `decorator`: `DecoratorBase` 57 | 58 | **Returns:** `DecoratedRequest` 59 | 60 | ##### `apply_decorators` 61 | 62 | Apply all decorators to the prompt. 63 | 64 | Args: 65 | self: The request instance 66 | 67 | Returns: 68 | The decorated prompt text 69 | 70 | Note: 71 | Decorators are applied in the order they were added. 72 | This allows for composing decorators in a specific sequence. 73 | 74 | **Signature:** `apply_decorators(self) -> str` 75 | 76 | **Parameters:** 77 | 78 | 79 | **Returns:** `str` 80 | 81 | ##### `get_decorator` 82 | 83 | Get a decorator by name. 84 | 85 | Args: 86 | decorator_name: Name of the decorator to retrieve 87 | 88 | Returns: 89 | The decorator if found, None otherwise 90 | 91 | **Signature:** `get_decorator(self, decorator_name: str) -> Optional[prompt_decorators.core.base.DecoratorBase]` 92 | 93 | **Parameters:** 94 | 95 | - `decorator_name`: `str` 96 | 97 | **Returns:** `Optional` 98 | 99 | ##### `remove_decorator` 100 | 101 | Remove a decorator by name. 102 | 103 | Args: 104 | decorator_name: Name of the decorator to remove 105 | 106 | Returns: 107 | True if the decorator was removed, False if not found 108 | 109 | **Signature:** `remove_decorator(self, decorator_name: str) -> bool` 110 | 111 | **Parameters:** 112 | 113 | - `decorator_name`: `str` 114 | 115 | **Returns:** `bool` 116 | 117 | ##### `to_dict` 118 | 119 | Convert the request to a dictionary representation. 120 | 121 | Args: 122 | self: The request instance 123 | 124 | Returns: 125 | Dictionary representation of the request 126 | 127 | **Signature:** `to_dict(self) -> Dict[str, Any]` 128 | 129 | **Parameters:** 130 | 131 | 132 | **Returns:** `Dict` 133 | 134 | ##### `to_json` 135 | 136 | Convert the request to a JSON string. 137 | 138 | Args: 139 | indent: Optional indentation for pretty-printing 140 | 141 | Returns: 142 | JSON string representation of the request 143 | 144 | **Signature:** `to_json(self, indent: Optional[int] = None) -> str` 145 | 146 | **Parameters:** 147 | 148 | - `indent`: `Optional` (default: `None`) 149 | 150 | **Returns:** `str` 151 | -------------------------------------------------------------------------------- /.cursor/rules/400-md-docs.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | description: ALWAYS use when writing or updating Markdown files to ensure consistent formatting and readability. This rule enforces standardized Markdown practices across all documentation. 3 | globs: **/*.{md,mdx} 4 | --- 5 | # Markdown Documentation Standards 6 | 7 | ## Requirements 8 | 9 | - Follow the official [Markdown Guide](mdc:https:/www.markdownguide.org) for all basic and extended syntax 10 | - Maintain clear document structure and readability 11 | - Include appropriate metadata when required 12 | - Use Mermaid diagrams for visual documentation where appropriate 13 | - Always Include YAML front matter for metadata but Keep metadata concise 14 | 15 | ## Markdown Reference 16 | 17 | For all basic and extended Markdown syntax, refer to: 18 | - [Basic Syntax Guide](mdc:https:/www.markdownguide.org/basic-syntax) 19 | - [Extended Syntax Guide](mdc:https:/www.markdownguide.org/extended-syntax) 20 | 21 | ## Formatting Rules 22 | 23 | - Use ATX-style headings with space after hash: `# Heading` 24 | - Maintain proper heading hierarchy (don't skip levels) 25 | - Maximum heading depth: 4 levels 26 | - Add blank line before and after headings 27 | - Indent content within XML tags by 2 spaces 28 | - Close XML tags on their own line at the parent indentation level 29 | - Use blockquotes with emoji for different types of callouts: 30 | 31 | 32 | > 🚨 **Warning:** Critical information here. 33 | 34 | > 💡 **Tip:** Helpful suggestion. 35 | 36 | > ℹ️ **Note:** Additional context. 37 | 38 | 39 | ## Code Blocks 40 | 41 | - Use triple backticks with language specification 42 | - Indent code blocks properly 43 | - Add blank line before and after 44 | - Use inline code for short references 45 | 46 | 47 | ```typescript 48 | function example(): void { 49 | console.log('Hello, Universe!'); 50 | } 51 | ``` 52 | 53 | Reference the `example()` function inline. 54 | 55 | 56 | ## Tables 57 | 58 | - Use alignment indicators 59 | - Include header row separator 60 | - Keep tables simple and readable 61 | - Add blank lines before and after 62 | 63 | 64 | | Name | Type | Description | 65 | |:--------|:-------:|---------------:| 66 | | id | number | Primary key | 67 | | name | string | User's name | 68 | 69 | 70 | ## Special Elements 71 | 72 | ### Callouts 73 | 74 | Use blockquotes with emoji for different types of callouts: 75 | 76 | 77 | > 🚨 **Warning:** Critical information here. 78 | 79 | > 💡 **Tip:** Helpful suggestion. 80 | 81 | > ℹ️ **Note:** Additional context. 82 | 83 | 84 | ### Mermaid Diagrams 85 | 86 | Use Mermaid diagrams to visualize: 87 | - Architecture flows 88 | - Process sequences 89 | - Decision trees 90 | - State machines 91 | - Component relationships 92 | - AI agent rule flows 93 | 94 | ### When to Use Mermaid 95 | 96 | - Simple and Complex workflows need visualization 97 | - System architecture needs to be explained 98 | - Process flows have multiple branches 99 | - State transitions need to be clear 100 | - AI decision trees need to be mapped 101 | 102 | ### Diagram Best Practices 103 | 104 | 1. Include clear titles using the `---` syntax 105 | 2. Use descriptive node labels 106 | 3. Add comments for complex flows 107 | 4. Group related components using subgraphs 108 | 5. Use consistent direction (TD/LR/TB) 109 | 6. Keep diagrams focused and specific 110 | 111 | 112 | ```mermaid 113 | --- 114 | title: Example Workflow 115 | --- 116 | graph TD 117 | A[Start] --> B{Decision} 118 | B -->|Yes| C[Process 1] 119 | B -->|No| D[Process 2] 120 | C --> E[End] 121 | D --> E 122 | ``` 123 | 124 | 125 | 126 | ```mermaid 127 | graph TD 128 | A-->B 129 | B-->C 130 | ``` 131 | 132 | No title, unclear labels, no context 133 | 134 | -------------------------------------------------------------------------------- /scripts/debug_transform.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Debug script for testing the transform function in DynamicDecorator. 3 | 4 | This script provides a way to test the transform function in isolation, 5 | which is useful for debugging issues with the transformation logic. 6 | """ 7 | 8 | import logging 9 | import sys 10 | from typing import Any, Callable, Dict, cast 11 | 12 | # Configure logging 13 | logging.basicConfig( 14 | level=logging.DEBUG, 15 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", 16 | handlers=[logging.StreamHandler(sys.stdout)], 17 | ) 18 | 19 | logger = logging.getLogger("debug_transform") 20 | 21 | 22 | def test_decorator_transform(): 23 | """Test decorator with a transform function.""" 24 | return """ 25 | result = "This is a test transformation.\\n" 26 | result += f"Parameter value: {kwargs.get('param1', 'default')}\\n" 27 | return result + text 28 | """ 29 | 30 | 31 | def step_by_step_transform(): 32 | """StepByStep decorator transform function.""" 33 | return """ 34 | result = "Please break down your response into clear, sequential steps.\\n" 35 | if kwargs.get("numbered", True): 36 | result += "Number each step sequentially (Step 1, Step 2, etc.).\\n" 37 | else: 38 | result += "Use bullet points for each step instead of numbers.\\n" 39 | return result + text 40 | """ 41 | 42 | 43 | def debug_transform_function( 44 | transform_function: str, text: str, parameters: Dict[str, Any] 45 | ) -> str: 46 | """Debug the transform function. 47 | 48 | Args: 49 | transform_function: The transform function code 50 | text: The text to transform 51 | parameters: The parameters to use 52 | 53 | Returns: 54 | The transformed text 55 | """ 56 | logger.debug(f"Transform function: {transform_function}") 57 | logger.debug(f"Text: {text}") 58 | logger.debug(f"Parameters: {parameters}") 59 | 60 | try: 61 | # Create a Python function from the transform function 62 | transform_code = f"def transform(text, **kwargs):\n" 63 | for line in transform_function.split("\n"): 64 | transform_code += f" {line}\n" 65 | 66 | logger.debug(f"Transform code:\n{transform_code}") 67 | 68 | # Compile and execute the function 69 | namespace: Dict[str, Any] = {} 70 | exec(transform_code, namespace) 71 | transform = namespace["transform"] 72 | 73 | # Call the function with the text and parameters 74 | # Pass parameters as kwargs, not as a second positional argument 75 | result = transform(text, **parameters) 76 | 77 | # Ensure the result is a string 78 | if not isinstance(result, str): 79 | result = str(result) 80 | 81 | logger.debug(f"Result: {result}") 82 | return cast(str, result) 83 | except Exception as e: 84 | logger.error(f"Error applying transform function: {e}") 85 | import traceback 86 | 87 | traceback.print_exc() 88 | return text 89 | 90 | 91 | def main(): 92 | """Run the debug script.""" 93 | logger.info("=== Testing basic transform function ===") 94 | text = "This is a test prompt." 95 | parameters = {"param1": "test_value"} 96 | transform_function = test_decorator_transform() 97 | 98 | transformed = debug_transform_function(transform_function, text, parameters) 99 | print("\nTransformed text:") 100 | print(transformed) 101 | 102 | logger.info("=== Testing StepByStep transform function ===") 103 | parameters = {"numbered": True} 104 | transform_function = step_by_step_transform() 105 | 106 | transformed = debug_transform_function(transform_function, text, parameters) 107 | print("\nTransformed text (StepByStep):") 108 | print(transformed) 109 | 110 | 111 | if __name__ == "__main__": 112 | main() 113 | -------------------------------------------------------------------------------- /registry/core/minimal/reasoning.json: -------------------------------------------------------------------------------- 1 | { 2 | "decoratorName": "Reasoning", 3 | "version": "1.0.0", 4 | "description": "Modifies the AI's response to provide explicit reasoning paths before reaching conclusions. This decorator encourages the model to show its thought process, making responses more transparent and trustworthy.", 5 | "author": { 6 | "name": "Prompt Decorators Working Group", 7 | "email": "spec@promptdecorators.ai", 8 | "url": "https://promptdecorators.ai" 9 | }, 10 | "parameters": [ 11 | { 12 | "name": "depth", 13 | "type": "enum", 14 | "description": "The level of detail in the reasoning process", 15 | "enum": ["basic", "moderate", "comprehensive"], 16 | "default": "moderate", 17 | "required": false 18 | } 19 | ], 20 | "transformationTemplate": { 21 | "instruction": "Please provide detailed reasoning in your response. Show your thought process before reaching a conclusion.", 22 | "parameterMapping": { 23 | "depth": { 24 | "valueMap": { 25 | "basic": "Focus on the most important logical steps.", 26 | "moderate": "Balance detail with clarity in your reasoning.", 27 | "comprehensive": "Provide a very thorough and detailed analysis with multiple perspectives." 28 | } 29 | } 30 | }, 31 | "placement": "prepend", 32 | "compositionBehavior": "accumulate" 33 | }, 34 | "implementationGuidance": { 35 | "examples": [ 36 | { 37 | "context": "Standard implementation", 38 | "originalPrompt": "What are the implications of artificial intelligence for education?", 39 | "transformedPrompt": "Please provide detailed reasoning in your response. Show your thought process before reaching a conclusion. Provide a very thorough and detailed analysis with multiple perspectives.\n\nWhat are the implications of artificial intelligence for education?" 40 | }, 41 | { 42 | "context": "Basic depth implementation", 43 | "originalPrompt": "How does compound interest work?", 44 | "transformedPrompt": "Please provide detailed reasoning in your response. Show your thought process before reaching a conclusion. Focus on the most important logical steps.\n\nHow does compound interest work?" 45 | } 46 | ], 47 | "compatibilityNotes": [ 48 | { 49 | "decorator": "Concise", 50 | "relationship": "conflicts", 51 | "notes": "The objectives of comprehensive reasoning and concise responses may contradict each other" 52 | }, 53 | { 54 | "decorator": "StepByStep", 55 | "relationship": "enhances", 56 | "notes": "Combining these decorators produces structured reasoning with clear steps" 57 | } 58 | ], 59 | "modelSpecificImplementations": { 60 | "gpt-4-turbo": { 61 | "instruction": "Explain your reasoning step by step before giving your final answer. Show your thought process clearly.", 62 | "notes": "This model may require more explicit instructions to produce detailed reasoning" 63 | } 64 | } 65 | }, 66 | "examples": [ 67 | { 68 | "description": "Basic reasoning for a simple question", 69 | "usage": "+++Reasoning(depth=basic)\nWhat is the best programming language for beginners?", 70 | "result": "Provides a brief explanation of key factors before recommending a language" 71 | }, 72 | { 73 | "description": "Comprehensive analysis of a complex topic", 74 | "usage": "+++Reasoning(depth=comprehensive)\nWhat are the implications of quantum computing for cybersecurity?", 75 | "result": "Delivers an in-depth analysis covering multiple aspects and their interconnections" 76 | } 77 | ], 78 | "compatibility": { 79 | "requires": [], 80 | "conflicts": [], 81 | "minStandardVersion": "1.0.0", 82 | "maxStandardVersion": "2.0.0", 83 | "models": [ 84 | "gpt-4o", 85 | "gpt-4-turbo" 86 | ] 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /prompt_decorators/registry/core/minimal/reasoning.json: -------------------------------------------------------------------------------- 1 | { 2 | "decoratorName": "Reasoning", 3 | "version": "1.0.0", 4 | "description": "Modifies the AI's response to provide explicit reasoning paths before reaching conclusions. This decorator encourages the model to show its thought process, making responses more transparent and trustworthy.", 5 | "author": { 6 | "name": "Prompt Decorators Working Group", 7 | "email": "spec@promptdecorators.ai", 8 | "url": "https://promptdecorators.ai" 9 | }, 10 | "parameters": [ 11 | { 12 | "name": "depth", 13 | "type": "enum", 14 | "description": "The level of detail in the reasoning process", 15 | "enum": ["basic", "moderate", "comprehensive"], 16 | "default": "moderate", 17 | "required": false 18 | } 19 | ], 20 | "transformationTemplate": { 21 | "instruction": "Please provide detailed reasoning in your response. Show your thought process before reaching a conclusion.", 22 | "parameterMapping": { 23 | "depth": { 24 | "valueMap": { 25 | "basic": "Focus on the most important logical steps.", 26 | "moderate": "Balance detail with clarity in your reasoning.", 27 | "comprehensive": "Provide a very thorough and detailed analysis with multiple perspectives." 28 | } 29 | } 30 | }, 31 | "placement": "prepend", 32 | "compositionBehavior": "accumulate" 33 | }, 34 | "implementationGuidance": { 35 | "examples": [ 36 | { 37 | "context": "Standard implementation", 38 | "originalPrompt": "What are the implications of artificial intelligence for education?", 39 | "transformedPrompt": "Please provide detailed reasoning in your response. Show your thought process before reaching a conclusion. Provide a very thorough and detailed analysis with multiple perspectives.\n\nWhat are the implications of artificial intelligence for education?" 40 | }, 41 | { 42 | "context": "Basic depth implementation", 43 | "originalPrompt": "How does compound interest work?", 44 | "transformedPrompt": "Please provide detailed reasoning in your response. Show your thought process before reaching a conclusion. Focus on the most important logical steps.\n\nHow does compound interest work?" 45 | } 46 | ], 47 | "compatibilityNotes": [ 48 | { 49 | "decorator": "Concise", 50 | "relationship": "conflicts", 51 | "notes": "The objectives of comprehensive reasoning and concise responses may contradict each other" 52 | }, 53 | { 54 | "decorator": "StepByStep", 55 | "relationship": "enhances", 56 | "notes": "Combining these decorators produces structured reasoning with clear steps" 57 | } 58 | ], 59 | "modelSpecificImplementations": { 60 | "gpt-4-turbo": { 61 | "instruction": "Explain your reasoning step by step before giving your final answer. Show your thought process clearly.", 62 | "notes": "This model may require more explicit instructions to produce detailed reasoning" 63 | } 64 | } 65 | }, 66 | "examples": [ 67 | { 68 | "description": "Basic reasoning for a simple question", 69 | "usage": "+++Reasoning(depth=basic)\nWhat is the best programming language for beginners?", 70 | "result": "Provides a brief explanation of key factors before recommending a language" 71 | }, 72 | { 73 | "description": "Comprehensive analysis of a complex topic", 74 | "usage": "+++Reasoning(depth=comprehensive)\nWhat are the implications of quantum computing for cybersecurity?", 75 | "result": "Delivers an in-depth analysis covering multiple aspects and their interconnections" 76 | } 77 | ], 78 | "compatibility": { 79 | "requires": [], 80 | "conflicts": [], 81 | "minStandardVersion": "1.0.0", 82 | "maxStandardVersion": "2.0.0", 83 | "models": [ 84 | "gpt-4o", 85 | "gpt-4-turbo" 86 | ] 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /config/model_capabilities.json: -------------------------------------------------------------------------------- 1 | { 2 | "models": [ 3 | { 4 | "model_id": "gpt-4o", 5 | "model_family": "gpt", 6 | "version": "4o", 7 | "capabilities": { 8 | "reasoning": true, 9 | "step_by_step": true, 10 | "code_generation": true, 11 | "json_output": true, 12 | "markdown_output": true, 13 | "max_tokens": 8192, 14 | "streaming": true, 15 | "function_calling": true, 16 | "multi_tool_use": true, 17 | "supported_decorators": [ 18 | "Reasoning", 19 | "StepByStep", 20 | "Socratic", 21 | "Debate", 22 | "TreeOfThought", 23 | "OutputFormat", 24 | "TableFormat", 25 | "Bullet", 26 | "CiteSources", 27 | "FactCheck", 28 | "Confidence", 29 | "Detailed", 30 | "ELI5", 31 | "Professional" 32 | ] 33 | } 34 | }, 35 | { 36 | "model_id": "gpt-4-turbo", 37 | "model_family": "gpt", 38 | "version": "4", 39 | "capabilities": { 40 | "reasoning": true, 41 | "step_by_step": true, 42 | "code_generation": true, 43 | "json_output": true, 44 | "markdown_output": true, 45 | "max_tokens": 4096, 46 | "streaming": true, 47 | "function_calling": true, 48 | "multi_tool_use": false, 49 | "supported_decorators": [ 50 | "Reasoning", 51 | "StepByStep", 52 | "OutputFormat", 53 | "Bullet", 54 | "Detailed", 55 | "ELI5", 56 | "Professional" 57 | ] 58 | } 59 | }, 60 | { 61 | "model_id": "claude-3-7-sonnet-latest", 62 | "model_family": "claude", 63 | "version": "3.7", 64 | "capabilities": { 65 | "reasoning": true, 66 | "step_by_step": true, 67 | "code_generation": true, 68 | "json_output": true, 69 | "markdown_output": true, 70 | "max_tokens": 100000, 71 | "streaming": true, 72 | "function_calling": false, 73 | "multi_tool_use": false, 74 | "supported_decorators": [ 75 | "Reasoning", 76 | "StepByStep", 77 | "Socratic", 78 | "Debate", 79 | "OutputFormat", 80 | "TableFormat", 81 | "Bullet", 82 | "CiteSources", 83 | "Detailed", 84 | "ELI5", 85 | "Professional" 86 | ] 87 | } 88 | }, 89 | { 90 | "model_id": "llama-3.2-70b-chat", 91 | "model_family": "llama", 92 | "version": "3.2", 93 | "capabilities": { 94 | "reasoning": true, 95 | "step_by_step": true, 96 | "code_generation": true, 97 | "json_output": true, 98 | "markdown_output": true, 99 | "max_tokens": 4096, 100 | "streaming": true, 101 | "function_calling": false, 102 | "multi_tool_use": false, 103 | "supported_decorators": [ 104 | "Reasoning", 105 | "StepByStep", 106 | "OutputFormat", 107 | "Bullet", 108 | "ELI5", 109 | "Professional" 110 | ] 111 | } 112 | }, 113 | { 114 | "model_id": "mistral-7b-instruct", 115 | "model_family": "mistral", 116 | "version": "1.0", 117 | "capabilities": { 118 | "reasoning": true, 119 | "step_by_step": true, 120 | "code_generation": true, 121 | "json_output": true, 122 | "markdown_output": true, 123 | "max_tokens": 4096, 124 | "streaming": true, 125 | "function_calling": false, 126 | "multi_tool_use": false, 127 | "supported_decorators": [ 128 | "Reasoning", 129 | "StepByStep", 130 | "OutputFormat", 131 | "ELI5" 132 | ] 133 | } 134 | } 135 | ] 136 | } 137 | -------------------------------------------------------------------------------- /docs/documentation_checklist.md: -------------------------------------------------------------------------------- 1 | # Documentation Verification Checklist 2 | 3 | > **Important Note:** Always use `docs/generate_docs.py` to generate documentation for the prompt-decorators project. Any other documentation generators found in the codebase are deprecated and will be removed in future releases. 4 | 5 | This checklist helps ensure that the documentation for the prompt-decorators project is complete, accurate, and helpful for users. Use this checklist when reviewing documentation changes or conducting regular documentation audits. 6 | 7 | ## Navigation Structure 8 | 9 | - [ ] All important sections are accessible from the navigation 10 | - [ ] The navigation hierarchy makes logical sense 11 | - [ ] Section titles are clear and descriptive 12 | - [ ] Breadcrumbs work correctly 13 | - [ ] Table of contents is accurate and complete 14 | 15 | ## Content Quality 16 | 17 | - [ ] Documentation is clear and well-written 18 | - [ ] Examples are accurate and helpful 19 | - [ ] Terminology is consistent throughout 20 | - [ ] Code examples are up-to-date with the current API 21 | - [ ] All code examples are runnable without modification 22 | - [ ] Complex concepts are explained with appropriate detail 23 | - [ ] No spelling or grammatical errors 24 | 25 | ## Visual Appearance 26 | 27 | - [ ] Documentation renders correctly on desktop browsers 28 | - [ ] Documentation renders correctly on mobile devices 29 | - [ ] Code blocks are properly formatted with syntax highlighting 30 | - [ ] Images and diagrams are clear and relevant 31 | - [ ] Dark/light mode switching works correctly (if applicable) 32 | - [ ] Tables are formatted correctly and readable 33 | 34 | ## User Experience 35 | 36 | - [ ] Search functionality works correctly 37 | - [ ] Documentation is easy to navigate 38 | - [ ] Related content is properly linked 39 | - [ ] External links open in new tabs 40 | - [ ] No broken links or 404 errors 41 | - [ ] Page load times are reasonable 42 | 43 | ## API Documentation 44 | 45 | - [ ] All public classes, methods, and functions are documented 46 | - [ ] Parameter descriptions are clear and accurate 47 | - [ ] Return value descriptions are clear and accurate 48 | - [ ] Exception information is included where relevant 49 | - [ ] Type annotations match the documentation 50 | - [ ] Examples demonstrate common use cases 51 | - [ ] Deprecated features are clearly marked 52 | 53 | ## Registry Documentation 54 | 55 | - [ ] All decorators in the registry have corresponding documentation 56 | - [ ] Decorator parameters are clearly documented 57 | - [ ] Decorator examples show typical usage patterns 58 | - [ ] Compatibility information is included 59 | - [ ] Version information is accurate 60 | 61 | ## Getting Started 62 | 63 | - [ ] Installation instructions are clear and work for all supported platforms 64 | - [ ] Quick start guide provides a simple, working example 65 | - [ ] Prerequisites are clearly stated 66 | - [ ] Common pitfalls are addressed 67 | 68 | ## Tutorials and Guides 69 | 70 | - [ ] Tutorials cover key use cases 71 | - [ ] Step-by-step instructions are clear and accurate 72 | - [ ] Advanced usage scenarios are documented 73 | - [ ] Integration with other tools/libraries is explained where relevant 74 | 75 | ## Feedback and Improvement 76 | 77 | - [ ] Documentation includes a way for users to provide feedback 78 | - [ ] Issues identified in previous reviews have been addressed 79 | - [ ] Recent API changes are reflected in the documentation 80 | - [ ] Documentation is reviewed for accuracy before each release 81 | 82 | ## Accessibility 83 | 84 | - [ ] Documentation meets basic accessibility standards 85 | - [ ] Images have alt text 86 | - [ ] Color contrast is sufficient 87 | - [ ] Navigation is keyboard-accessible 88 | 89 | ## Notes 90 | 91 | Use this section to record any issues found during the review and plans for addressing them: 92 | 93 | 1. 94 | 2. 95 | 3. 96 | 97 | ## Review Information 98 | 99 | - **Reviewer:** 100 | - **Date:** 101 | - **Version Reviewed:** 102 | -------------------------------------------------------------------------------- /docs/api/modules/prompt_decorators.integrations.mcp.server.md: -------------------------------------------------------------------------------- 1 | # server 2 | 3 | MCP Server for Prompt Decorators. 4 | 5 | This module provides integration between Prompt Decorators and the Model Context Protocol (MCP), 6 | exposing prompt decorators as MCP tools that can be used by any MCP client. 7 | 8 | Implementation follows the official MCP SDK patterns and best practices. 9 | 10 | ## Module Variables 11 | 12 | ### `F` 13 | 14 | Type: `TypeVar` 15 | 16 | Value: `~F` 17 | 18 | ### `MCP_AVAILABLE` 19 | 20 | Type: `bool` 21 | 22 | Value: `True` 23 | 24 | ### `logger` 25 | 26 | Type: `Logger` 27 | 28 | Value: `` 29 | 30 | ### `mcp` 31 | 32 | Type: `FastMCP` 33 | 34 | Value: `` 35 | 36 | ## Functions 37 | 38 | ### `apply_decorators` 39 | 40 | Apply decorators to a prompt using the +++ syntax. 41 | 42 | Args: 43 | prompt: The prompt text to decorate. 44 | decorators: List of decorators to apply, each with name and parameters. 45 | 46 | Returns: 47 | The decorated prompt with decorators applied, following MCP tool response format. 48 | 49 | **Signature:** `apply_decorators(prompt: str, decorators: List[Dict[str, Any]]) -> Dict[str, Any]` 50 | 51 | **Parameters:** 52 | 53 | - `prompt`: `str` 54 | - `decorators`: `List` 55 | 56 | **Returns:** `Dict` 57 | 58 | ### `create_decorated_prompt` 59 | 60 | Create a decorated prompt using a predefined template. 61 | 62 | Args: 63 | template_name: The name of the template to use. 64 | content: The content to include in the prompt. 65 | parameters: Optional parameters for customizing the template. 66 | 67 | Returns: 68 | The decorated prompt created from the template, following MCP tool response format. 69 | 70 | **Signature:** `create_decorated_prompt(template_name: str, content: str, parameters: Optional[Dict[str, Any]] = None) -> Dict[str, Any]` 71 | 72 | **Parameters:** 73 | 74 | - `template_name`: `str` 75 | - `content`: `str` 76 | - `parameters`: `Optional` (default: `None`) 77 | 78 | **Returns:** `Dict` 79 | 80 | ### `get_decorator_details` 81 | 82 | Get detailed information about a specific decorator. 83 | 84 | Args: 85 | name: The name of the decorator to get details for. 86 | 87 | Returns: 88 | A dictionary containing detailed information about the decorator. 89 | 90 | **Signature:** `get_decorator_details(name: str) -> Dict[str, Any]` 91 | 92 | **Parameters:** 93 | 94 | - `name`: `str` 95 | 96 | **Returns:** `Dict` 97 | 98 | ### `list_decorators` 99 | 100 | Lists all available prompt decorators. 101 | 102 | Returns: 103 | A dictionary containing information about all available decorators. 104 | 105 | **Signature:** `list_decorators() -> Dict[str, Any]` 106 | 107 | **Returns:** `Dict` 108 | 109 | ### `run_server` 110 | 111 | Run the MCP server. 112 | 113 | Args: 114 | host: The host to listen on. 115 | port: The port to listen on. 116 | 117 | Returns: 118 | None 119 | 120 | **Signature:** `run_server(host: str = '0.0.0.0', port: int = 5000) -> None` 121 | 122 | **Parameters:** 123 | 124 | - `host`: `str` (default: `0.0.0.0`) 125 | - `port`: `int` (default: `5000`) 126 | 127 | ### `transform_prompt` 128 | 129 | Transform a prompt using a list of decorator strings. 130 | 131 | This tool directly transforms a prompt using the raw decorator syntax strings 132 | (e.g., "+++StepByStep(numbered=true)"), which can be useful for clients 133 | that already have decorator strings rather than structured decorator objects. 134 | 135 | Args: 136 | prompt: The prompt text to transform. 137 | decorator_strings: List of decorator syntax strings to apply. 138 | 139 | Returns: 140 | The transformed prompt, following MCP tool response format. 141 | 142 | **Signature:** `transform_prompt(prompt: str, decorator_strings: List[str]) -> Dict[str, Any]` 143 | 144 | **Parameters:** 145 | 146 | - `prompt`: `str` 147 | - `decorator_strings`: `List` 148 | 149 | **Returns:** `Dict` 150 | -------------------------------------------------------------------------------- /xnotes/903-story-template.mdc: -------------------------------------------------------------------------------- 1 | --- 2 | description: ALWAYS use when creating or updating story files to ensure proper tracking and implementation. This rule enforces consistent story structure with tasks, context, and progress tracking. 3 | globs: **/*.story.md 4 | --- 5 | # Story Template Standards 6 | 7 | 1.0.0 8 | 9 | ## Requirements 10 | 11 | - Follow standardized story structure 12 | - Include all required sections 13 | - Track progress accurately 14 | - Maintain implementation history 15 | - Stories must be organized under Epic directories 16 | 17 | ## File Structure 18 | 19 | Stories must be placed in their Epic's directory: 20 | `.ai/epic-{n}/story-{m}.story.md` 21 | 22 | ## Story Structure 23 | 24 | ### Required Sections 25 | 26 | #### 1. Header 27 | 28 | Epic-{N}: {Epic Title} 29 | Story-{M}: {Story Title} 30 | 31 | #### 2. Story Description 32 | 33 | **As a** {role} 34 | **I want** {action} 35 | **so that** {benefit} 36 | 37 | #### 3. Status 38 | 39 | - Draft 40 | - In Progress 41 | - Complete 42 | - Cancelled 43 | 44 | #### 4. Context 45 | 46 | - Background information 47 | - Current state 48 | - Story justification 49 | - Technical context 50 | - Business drivers 51 | - Relevant history from previous stories 52 | 53 | #### 5. Estimation 54 | 55 | Story Points: {Story Points (1 SP = 1 day of Human Development = 10 minutes of AI development)} 56 | 57 | #### 6. Tasks 58 | 59 | ##### Task Groups 60 | 61 | 1. - [ ] {Major Task Group 1} 62 | 1. - [ ] {Test Subtasks (as needed)} 63 | 2. - [ ] {Subtask} 64 | 65 | Note: 66 | - Use - [x] for completed items 67 | - Use ~~skipped/cancelled items~~ 68 | - Follow TDD - Start with Writing Tests Subtask 69 | 70 | ### 7. Additional Sections 71 | 72 | #### Constraints 73 | - List any technical or business constraints 74 | 75 | #### Data Models / Schema 76 | - Database schemas 77 | - API request/response models 78 | - Interfaces/types 79 | 80 | #### Structure 81 | - Module organization 82 | - File structure plan 83 | 84 | #### Diagrams 85 | - Mermaid diagrams as needed 86 | 87 | #### Dev Notes 88 | - Implementation commentary 89 | - Important considerations 90 | - Technical decisions 91 | 92 | #### Chat Command Log 93 | - Commands from User 94 | - Agent Question and Users Response 95 | 96 | ## Examples 97 | 98 | 99 | # Epic-1: Basic Chess Game 100 | # Story-2: Implement Chessboard UI 101 | 102 | ## Story 103 | 104 | **As a** chess player 105 | **I want** to see a clear and interactive chessboard 106 | **so that** I can play chess in the web browser 107 | 108 | ## Status 109 | 110 | In Progress 111 | 112 | ## Context 113 | 114 | Part of Epic-1 which implements the core 2-player chess game. This story focuses on the visual and interactive aspects of the chessboard. The project setup (Story-1) is complete, providing the foundation for UI implementation. 115 | 116 | ## Estimation 117 | 118 | Story Points: 2 119 | 120 | ## Tasks 121 | 122 | 1. - [x] Create Chessboard Grid 123 | 1. - [x] Implement 8x8 board layout 124 | 2. - [x] Add square coloring 125 | 3. - [x] Write grid tests 126 | 2. - [ ] Add Chess Pieces 127 | 1. - [ ] Create piece components 128 | 2. - [ ] Add piece images 129 | 3. - [ ] Write piece tests 130 | 3. - [ ] Implement Basic Interaction 131 | 1. - [ ] Add click handlers 132 | 2. - [ ] Highlight selected square 133 | 3. - [ ] Write interaction tests 134 | 135 | ## Dev Notes 136 | 137 | - Using React for UI components 138 | - Chess piece SVGs from open-source library 139 | - Implementing responsive design for various screen sizes 140 | 141 | ## Chat Command Log 142 | 143 | - BMad: Let's implement the chessboard UI 144 | - AiAgent: Reviewing the design requirements. Should we use SVG or PNG for pieces? 145 | - BMad: Let's use SVG for better scaling 146 | - AiAgent: Grid implementation complete, proceeding with piece placement 147 | 148 | 149 | 150 | Chess UI Story 151 | 152 | todo: 153 | - make board 154 | - add pieces 155 | - make it work 156 | 157 | -------------------------------------------------------------------------------- /prompt_decorators/integrations/mcp/install_claude_desktop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Installation helper for Claude Desktop integration. 3 | 4 | This script generates a configuration file for Claude Desktop that sets up 5 | the Prompt Decorators MCP integration. 6 | """ 7 | 8 | import argparse 9 | import json 10 | import os 11 | import subprocess 12 | import sys 13 | from pathlib import Path 14 | from typing import Optional 15 | 16 | 17 | def find_python_executable() -> str: 18 | """Find the path to the current Python executable.""" 19 | return sys.executable 20 | 21 | 22 | def find_package_path() -> str: 23 | """Find the path to the prompt-decorators package.""" 24 | try: 25 | import prompt_decorators 26 | 27 | return os.path.dirname( 28 | os.path.dirname(os.path.dirname(prompt_decorators.__file__)) 29 | ) 30 | except ImportError: 31 | print("Error: prompt-decorators package not found.") 32 | print("Please install it with: pip install prompt-decorators") 33 | sys.exit(1) 34 | 35 | 36 | def create_config_file( 37 | output_path: Optional[str] = None, server_name: Optional[str] = None 38 | ) -> None: 39 | """Create a Claude Desktop configuration file.""" 40 | python_exec = find_python_executable() 41 | package_path = find_package_path() 42 | 43 | if not server_name: 44 | server_name = "Prompt Decorators" 45 | 46 | config = { 47 | "name": server_name, 48 | "command": python_exec, 49 | "args": ["-m", "prompt_decorators.integrations.mcp.claude_desktop"], 50 | "cwd": package_path, 51 | "env": { 52 | "PYTHONPATH": package_path, 53 | "PYTHONUNBUFFERED": "1", 54 | "PYTHONDONTWRITEBYTECODE": "1", 55 | }, 56 | } 57 | 58 | if not output_path: 59 | output_path = "claude_desktop_config.json" 60 | 61 | with open(output_path, "w") as f: 62 | json.dump(config, f, indent=2) 63 | 64 | print(f"Claude Desktop configuration file created at: {output_path}") 65 | print("\nTo use this configuration with Claude Desktop:") 66 | print("1. Open Claude Desktop") 67 | print("2. Go to Settings (gear icon) > Advanced > Context Sources") 68 | print("3. Click 'Add Context Source'") 69 | print("4. Click 'Import from File' and select the generated configuration file") 70 | print("5. Click 'Save'") 71 | 72 | 73 | def check_mcp_sdk() -> bool: 74 | """Check if the MCP SDK is installed.""" 75 | try: 76 | import mcp 77 | 78 | return True 79 | except ImportError: 80 | return False 81 | 82 | 83 | def main() -> None: 84 | """Main function to parse arguments and create the configuration file.""" 85 | parser = argparse.ArgumentParser( 86 | description="Generate a Claude Desktop configuration file for Prompt Decorators." 87 | ) 88 | parser.add_argument( 89 | "-o", 90 | "--output", 91 | help="Path to save the configuration file (default: claude_desktop_config.json)", 92 | ) 93 | parser.add_argument( 94 | "-n", "--name", help="Custom name for the server (default: Prompt Decorators)" 95 | ) 96 | args = parser.parse_args() 97 | 98 | # Check if MCP SDK is installed 99 | if not check_mcp_sdk(): 100 | print( 101 | "Warning: MCP SDK not found. This is required for Claude Desktop integration." 102 | ) 103 | print("Install it with: pip install mcp") 104 | install = input("Would you like to install it now? (y/n): ") 105 | if install.lower() == "y": 106 | subprocess.check_call([sys.executable, "-m", "pip", "install", "mcp"]) 107 | print("MCP SDK installed successfully.") 108 | else: 109 | print( 110 | "Please install MCP SDK manually before using the Claude Desktop integration." 111 | ) 112 | 113 | create_config_file(args.output, args.name) 114 | 115 | 116 | if __name__ == "__main__": 117 | main() 118 | -------------------------------------------------------------------------------- /docs/api/decorators/Iterate.md: -------------------------------------------------------------------------------- 1 | # Iterate Decorator 2 | 3 | Indicates this is an iteration on previously generated code, with specific improvements needed. 4 | 5 | **Category**: Implementation-Focused 6 | 7 | ## Parameters 8 | 9 | | Parameter | Type | Description | Default | 10 | |-----------|------|-------------|--------| 11 | | `version` | `number` | Iteration number | `2` | 12 | | `feedback` | `enum` | Type of feedback addressed | `review-comments` | 13 | | `priority` | `enum` | Implementation priority | `correctness` | 14 | 15 | ## Feedback Options 16 | 17 | - `review-comments`: code review comments 18 | - `bug-fixes`: bug fixes 19 | - `performance-issues`: performance issues 20 | - `feature-requests`: feature requests 21 | 22 | ## Priority Options 23 | 24 | - `correctness`: ensuring code correctness 25 | - `completeness`: ensuring feature completeness 26 | - `performance`: optimizing performance 27 | - `readability`: improving code readability 28 | 29 | ## Examples 30 | 31 | ### Basic iteration on authentication middleware 32 | 33 | ``` 34 | +++Iterate(version=2, feedback=review-comments, priority=correctness) 35 | Update the authentication middleware based on these code review comments: 1) Token expiration is not properly checked, 2) Error messages are not consistent. 36 | ``` 37 | 38 | The model will understand this is the second iteration of code, focusing on fixing specific review comments with correctness as the priority. 39 | 40 | ### Performance improvement iteration 41 | 42 | ``` 43 | +++Iterate(feedback=performance-issues, priority=performance) 44 | The database query in the user service is taking too long. Please optimize it. 45 | ``` 46 | 47 | The model will understand this is an iteration focused on performance issues, with performance optimization as the priority. 48 | 49 | ## Model-Specific Implementations 50 | 51 | ### gpt-4-turbo 52 | 53 | **Instruction:** This is iteration {version}. I need you to improve the previously generated code based on {feedback} feedback. Focus primarily on {priority}. 54 | 55 | **Notes:** Simpler phrasing works better with this model. 56 | 57 | 58 | ## Implementation Guidance 59 | 60 | ### Web development 61 | 62 | **Original Prompt:** 63 | ``` 64 | Create an authentication middleware for Express.js 65 | ``` 66 | 67 | **Transformed Prompt:** 68 | ``` 69 | This is iteration 2 of the code implementation. Please focus on addressing the following feedback: code review comments, with priority on ensuring code correctness. 70 | 71 | Create an authentication middleware for Express.js 72 | ``` 73 | 74 | **Notes:** The decorator indicates this is a follow-up request to improve previously generated code. 75 | 76 | ## Transformation Details 77 | 78 | **Base Instruction:** This is iteration {version} of the code implementation. Please focus on addressing the following feedback: {feedback}, with priority on {priority}. 79 | 80 | **Placement:** prepend 81 | 82 | **Composition Behavior:** accumulate 83 | 84 | **Parameter Effects:** 85 | 86 | - `version`: 87 | - Format: {value} 88 | 89 | - `feedback`: 90 | - When set to `review-comments`: code review comments 91 | - When set to `bug-fixes`: bug fixes 92 | - When set to `performance-issues`: performance issues 93 | - When set to `feature-requests`: feature requests 94 | 95 | - `priority`: 96 | - When set to `correctness`: ensuring code correctness 97 | - When set to `completeness`: ensuring feature completeness 98 | - When set to `performance`: optimizing performance 99 | - When set to `readability`: improving code readability 100 | 101 | ## Compatibility 102 | 103 | - **Requires**: None 104 | - **Conflicts**: FromScratch 105 | - **Compatible Models**: gpt-4-turbo, gpt-4o, claude-3-7-sonnet-latest, llama-3.2 106 | - **Standard Version**: 1.0.0 - 2.0.0 107 | 108 | ## Related Decorators 109 | 110 | - **CodeReview**: Enhances Iterate Iterate works well after CodeReview to implement suggested changes. 111 | - **FromScratch**: Conflicts with Iterate Iterate assumes existing code to improve upon, which conflicts with FromScratch's purpose. 112 | --------------------------------------------------------------------------------