commit 8198164d09be35b68cc738fef368a67fc9891c66 Author: Michael Date: Fri Apr 24 09:16:29 2026 +0200 feat: Initiales Projekt-Setup für Prompt-Templates - Verzeichnisstruktur: templates/{system,user,custom}, categories, scripts - Beispiel-Templates: Code Reviewer, Summarizer (JSON), Email Draft, Brainstorming (MD) - Validierungsskript: validate.py für JSON/MD Templates - Dokumentation: README.md mit Workflow und Beispielen Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7aaa193 --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + +# Python +__pycache__/ +*.py[cod] + +# Logs +*.log + +# Local overrides +!.gitignore diff --git a/README.md b/README.md new file mode 100644 index 0000000..5c8871c --- /dev/null +++ b/README.md @@ -0,0 +1,126 @@ +# Prompt Templates + +> Eine Sammlung von strukturierten Prompt-Templates für KI-Assistenten. Verwaltet über Git für Versionierung und Kollaboration. + +--- + +## Struktur + +``` +prompt_template/ +├── templates/ # Haupt-Templates +│ ├── system/ # System-Prompts (Code, Analyse, etc.) +│ ├── user/ # Benutzer-Prompts (Emails, Texte, etc.) +│ └── custom/ # Benutzerdefinierte Templates +│ +├── categories/ # Optional: Kategorisierte Templates +│ ├── marketing/ +│ ├── technical/ +│ └── creative/ +│ +├── scripts/ # Hilfsskripte +│ └── validate.py # Template-Validierung +│ +├── README.md +└── .gitignore +``` + +--- + +## Dateiformate + +### JSON (empfohlen für strukturierte Templates) +```json +{ + "name": "Template Name", + "version": "1.0", + "description": "Beschreibung...", + "role": "Rolle der KI", + "template": "Der eigentliche Prompt mit {variables}", + "variables": { + "var1": {"type": "string", "required": true, "description": "..."} + }, + "tags": ["tag1", "tag2"], + "language": "de" +} +``` + +### Markdown (für einfache Templates mit Dokumentation) +```markdown +# Template Name + +**Rolle**: Beschreibung + +**Template**: +``` +Prompt-Text mit {variables} +``` + +**Variablen**: +| Variable | Typ | Required | Beschreibung | +``` + +--- + +## erweitert verwenden + +### Neues Template hinzufügen +1. Template in passendem Verzeichnis erstellen (`.json` oder `.md`) +2. Validieren: + ```bash + python scripts/validate.py templates/system/mein_template.json + ``` +3. Commiten: + ```bash + git add templates/system/mein_template.json + git commit -m "feat: neues Template XY hinzugefügt" + ``` + +### Template validieren +```bash +# Einzelnes Template +python scripts/validate.py pfad/zum/template.json + +# Alle Templates +python scripts/validate.py --all + +# Nur JSON-Templates +python scripts/validate.py --json +``` + +--- + +## Git Workflow + +### Branches +- `master` / `main`: Stabile Templates +- `feature/*`: Neue Templates in Entwicklung +- `fix/*`: Korrekturen an bestehenden Templates + +### Commit Messages +- `feat: neues Template hinzugefügt` +- `fix: Variable in Template XY korrigiert` +- `docs: Beschreibung aktualisiert` +- `refactor: Template-Struktur verbessert` + +--- + +## Tags + +| Tag | Beschreibung | +|-----|--------------| +| `#code` | Code-bezogene Templates | +| `#text` | Textgenerierung/Verarbeitung | +| `#creative` | Kreatives Schreiben | +| `#analysis` | Analyse-Tasks | +| `#communication` | Emails, Chat, etc. | + +--- + +## Beispiele + +Siehe: +- [Code Reviewer](templates/system/code_reviewer.json) - Code-Analyse +- [Text Summarizer](templates/system/summarizer.json) - Textzusammenfassung +- [Email Draft](templates/user/email_draft.md) - Email-Generierung +- [Brainstorming](templates/custom/brainstorming.md) - Ideenfindung diff --git a/categories/.gitkeep b/categories/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/scripts/validate.py b/scripts/validate.py new file mode 100755 index 0000000..c73d748 --- /dev/null +++ b/scripts/validate.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +""" +Prompt Template Validator + +Validiert JSON- und Markdown-Templates gegen definierte Schemas. +""" + +import argparse +import json +import os +import re +import sys +from pathlib import Path +from typing import Dict, List, Optional, Tuple + + +# JSON Schema für JSON-Templates +JSON_SCHEMA = { + "required": ["name", "template", "variables"], + "properties": { + "name": {"type": "string", "minLength": 1}, + "version": {"type": "string", "pattern": r"^\d+\.\d+$"}, + "description": {"type": "string"}, + "role": {"type": "string"}, + "template": {"type": "string", "minLength": 1}, + "variables": { + "type": "object", + "patternProperties": { + r"^.+$": { + "type": "object", + "properties": { + "type": {"type": "string", "enum": ["string", "number", "enum", "boolean"]}, + "required": {"type": "boolean"}, + "default": {}, + "description": {"type": "string"}, + "values": {"type": "array"}, + }, + "required": ["type"], + } + }, + }, + "tags": {"type": "array", "items": {"type": "string"}}, + "language": {"type": "string", "enum": ["de", "en", "fr", "es", "any"]}, + }, +} + +# Muster für Markdown-Templates +MD_REQUIRED_SECTIONS = ["Template", "Variablen"] +MD_VARIABLE_PATTERN = re.compile(r"\|\s*(\w+)\s*\|\s*(\w+)\s*\|") + + +def validate_json_template(filepath: Path) -> Tuple[bool, List[str]]: + """Validiert ein JSON-Template.""" + errors = [] + + try: + with open(filepath, 'r', encoding='utf-8') as f: + data = json.load(f) + except json.JSONDecodeError as e: + return False, [f"❌ JSON Syntax Error: {e}"] + except Exception as e: + return False, [f"❌ Datei kann nicht gelesen werden: {e}"] + + # Schemas validieren + if not isinstance(data, dict): + return False, ["❌ Root muss ein Object sein"] + + # Required Felder + for field in JSON_SCHEMA.get("required", []): + if field not in data: + errors.append(f"❌ Fehlendes Pflichtfeld: '{field}'") + + # Feld-Typen validieren + for field, schema in JSON_SCHEMA.get("properties", {}).items(): + if field in data: + field_type = schema.get("type") + if field_type == "string" and not isinstance(data[field], str): + errors.append(f"❌ Feld '{field}' muss ein String sein") + elif field_type == "object" and not isinstance(data[field], dict): + errors.append(f"❌ Feld '{field}' muss ein Object sein") + elif field_type == "array" and not isinstance(data[field], list): + errors.append(f"❌ Feld '{field}' muss ein Array sein") + + # Pattern validieren + if "pattern" in schema and isinstance(data[field], str): + if not re.match(schema["pattern"], data[field]): + errors.append(f"❌ Feld '{field}' entspricht nicht dem Pattern: {schema['pattern']}") + + # Template prüfen + if "template" in data: + template = data["template"] + if not isinstance(template, str): + errors.append("❌ Template muss ein String sein") + else: + # Variablen im Template prüfen + if "variables" in data: + template_vars = set(re.findall(r"\{(\w+)\}", template)) + defined_vars = set(data["variables"].keys()) + undefined_vars = template_vars - defined_vars + if undefined_vars: + errors.append(f"❌ Undefinierte Variablen im Template: {', '.join(undefined_vars)}") + + # Variablen validieren + if "variables" in data: + variables = data["variables"] + if not isinstance(variables, dict): + errors.append("❌ Variables muss ein Object sein") + else: + for var_name, var_schema in variables.items(): + if not isinstance(var_schema, dict): + errors.append(f"❌ Variable '{var_name}' muss ein Object sein") + continue + if "type" not in var_schema: + errors.append(f"❌ Variable '{var_name}' benötigt ein 'type' Feld") + if var_schema.get("type") == "enum" and "values" not in var_schema: + errors.append(f"❌ Enum Variable '{var_name}' benötigt 'values' Array") + + return len(errors) == 0, errors + + +def validate_md_template(filepath: Path) -> Tuple[bool, List[str]]: + """Validiert ein Markdown-Template.""" + errors = [] + + try: + with open(filepath, 'r', encoding='utf-8') as f: + content = f.read() + except Exception as e: + return False, [f"❌ Datei kann nicht gelesen werden: {e}"] + + # Mindestlänge + if len(content.strip()) < 50: + errors.append("❌ Template zu kurz (mind. 50 Zeichen)") + + # Titel prüfen + if not content.startswith("# "): + errors.append("❌ Fehlender Titel (erwartet: # Titel)") + + # Pflichtabschnitte prüfen + for section in MD_REQUIRED_SECTIONS: + if f"## {section}" not in content and f"# {section}" not in content: + errors.append(f"❌ Fehlender Abschnitt: {section}") + + # Variablen-Tabelle prüfen + if "Variablen" in content: + var_section_start = content.find("## Variablen") + if var_section_start == -1: + var_section_start = content.find("# Variablen") + + if var_section_start != -1: + var_section = content[var_section_start:var_section_start + 500] + if "| Variable |" not in var_section: + errors.append("❌ Variablen-Tabelle nicht im korrekten Format") + + # Template-Block prüfen + if "Template" in content: + template_start = content.find("```") + if template_start == -1: + errors.append("❌ Kein Code-Block für Template gefunden") + else: + # Prüfe ob Variablen im Template sind + template_content = content[template_start:] + if "{" not in template_content or "}" not in template_content: + errors.append("⚠️ Warnung: Keine Variablen (z.B. {var}) im Template gefunden") + + return len(errors) == 0, errors + + +def validate_template(filepath: Path) -> Tuple[bool, List[str]]: + """Validiert ein Template basierend auf der Dateiendung.""" + if filepath.suffix.lower() == ".json": + return validate_json_template(filepath) + elif filepath.suffix.lower() == ".md": + return validate_md_template(filepath) + else: + return False, [f"❌ Unsupported file type: {filepath.suffix}"] + + +def find_templates(directory: Path) -> List[Path]: + """Findet alle Template-Dateien in einem Verzeichnis Baum.""" + templates = [] + for root, _, files in os.walk(directory): + for file in files: + if file.endswith((".json", ".md")): + templates.append(Path(root) / file) + return templates + + +def main(): + parser = argparse.ArgumentParser( + description="Validiert Prompt-Templates", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Beispiele: + python validate.py templates/system/code_reviewer.json + python validate.py --all + python validate.py --json templates/ + """ + ) + parser.add_argument("path", nargs="?", help="Pfad zum Template oder Verzeichnis") + parser.add_argument("--all", action="store_true", help="Alle Templates validieren") + parser.add_argument("--json", action="store_true", help="Nur JSON-Templates validieren") + parser.add_argument("--md", action="store_true", help="Nur Markdown-Templates validieren") + + args = parser.parse_args() + + base_dir = Path(__file__).parent.parent + + if args.all: + # Alle Templates finden + templates = find_templates(base_dir / "templates") + if not args.json: + templates += find_templates(base_dir / "categories") + + if args.json: + templates = [t for t in templates if t.suffix == ".json"] + if args.md: + templates = [t for t in templates if t.suffix == ".md"] + + elif args.path: + path = Path(args.path) + if path.is_dir(): + templates = find_templates(path) + if args.json: + templates = [t for t in templates if t.suffix == ".json"] + if args.md: + templates = [t for t in templates if t.suffix == ".md"] + else: + templates = [path] + else: + print("❌ Bitte Pfad angeben oder --all verwenden") + print("Beispiel: python validate.py --all") + sys.exit(1) + + if not templates: + print("❌ Keine Templates gefunden") + sys.exit(1) + + # Validierung + total = len(templates) + valid = 0 + invalid = 0 + + print(f"\n{'='*60}") + print(f"Validiere {total} Template(s)...\n") + + for template_path in sorted(templates): + is_valid, errors = validate_template(template_path) + rel_path = str(template_path.relative_to(base_dir)) + + if is_valid: + print(f"✅ {rel_path}") + valid += 1 + else: + print(f"❌ {rel_path}") + for error in errors: + print(f" {error}") + invalid += 1 + + print(f"\n{'='*60}") + print(f"Ergebnis: {valid} ✅ | {invalid} ❌ | {total} Total") + + sys.exit(0 if invalid == 0 else 1) + + +if __name__ == "__main__": + main() diff --git a/templates/custom/brainstorming.md b/templates/custom/brainstorming.md new file mode 100644 index 0000000..f252752 --- /dev/null +++ b/templates/custom/brainstorming.md @@ -0,0 +1,51 @@ +# Brainstorming Assistent + +**Rolle**: Kreativer Innovationscoach + +**Beschreibung**: Generiert Ideen und Lösungsansätze für gegebene Probleme oder Ziele. + +--- + +## Template + +``` +Führe eine Brainstorming-Session zu folgendem Thema durch: + +**Ziel**: {goal} +**Kontext**: {context} +**Zielgruppe**: {target_audience} +**Rahmenbedingungen**: {constraints} + +Erstelle {idea_count} verschiedene Ideen/Lösungsansätze. + +Für jede Idee gib an: +1. **Kurzbeschreibung** (1 Satz) +2. **Vorteile** (2-3 Bullet Points) +3. **Nachteile/Risiken** (2-3 Bullet Points) +4. **Umsetzbarkeit** (1-5 Sternen: ⭐) + +--- + +Format: Markdown Tabelle + +| # | Idee | Vorteile | Nachteile | Umsetzbarkeit | +|---|------|----------|-----------|---------------| +``` + +--- + +## Variablen + +| Variable | Typ | Required | Default | Beschreibung | +|----------|-----|----------|---------|---------------| +| `goal` | string | ✅ | - | Das zu erreichende Ziel | +| `context` | string | ❌ | - | Hintergrundinformationen | +| `target_audience` | string | ❌ | "alle" | Zielgruppe | +| `constraints` | string | ❌ | "keine" | Einschränkungen | +| `idea_count` | number | ❌ | 5 | Anzahl Ideen (5-15) | +| `format` | enum | ❌ | "table" | Format: table, list, detailed | + +--- + +## Tags +#brainstorming #innovation #ideation #creative #problemlösung diff --git a/templates/system/code_reviewer.json b/templates/system/code_reviewer.json new file mode 100644 index 0000000..afa30c1 --- /dev/null +++ b/templates/system/code_reviewer.json @@ -0,0 +1,16 @@ +{ + "name": "Code Reviewer", + "version": "1.0", + "description": "Analysiert Code auf Qualität, Best Practices und potenzielle Bugs", + "role": "Senior Software Engineer", + "template": "Du bist ein erfahrener Senior-Entwickler mit 10+ Jahren Erfahrung. Analysiere den folgenden Code besonders auf:\n\n1. **Code-Qualität**: Lesbarkeit, Wartbarkeit, Struktur\n2. **Best Practices**: Idiomatische Nutzung der Sprache/Framework\n3. **Potenzielle Bugs**: Edge Cases, Race Conditions, Sicherheitslücken\n4. **Performance**: Ineffizienzen, unnötige Berechnungen\n5. **Tests**: Fehlende Testabdeckung\n\nCode:\n```\n{code}\n```\n\nGib dein Feedback in diesem Format:\n\n### ✅ Was gut ist\n- [Punkt 1]\n- [Punkt 2]\n\n### ⚠️ Verbesserungsvorschläge\n- [Punkt 1 mit Begründung]\n- [Punkt 2 mit Beispiel]\n\n### 🐛 Kritische Issues\n- [Issue mit Priorität und Fix-Vorschlag]", + "variables": { + "code": { + "type": "string", + "required": true, + "description": "Der zu analysierende Source Code" + } + }, + "tags": ["code", "review", "quality", "best-practices", "security"], + "language": "de" +} diff --git a/templates/system/summarizer.json b/templates/system/summarizer.json new file mode 100644 index 0000000..4a43156 --- /dev/null +++ b/templates/system/summarizer.json @@ -0,0 +1,32 @@ +{ + "name": "Text Summarizer", + "version": "1.0", + "description": "Erstellt präzise Zusammenfassungen von Texten mit konfigurierbarer Länge", + "role": "Erfahrener Redakteur", + "template": "Fasse den folgenden Text zusammen. Halte dich an diese Regeln:\n\n- **Stil**: Sachlich, präzise, neutral\n- **Länge**: ca. {length} der Original-Länge\n- **Fokus**: {focus_area}\n- **Struktur**: bullet points oder Fließtext (wie angefordert)\n- **Wichtigste Punkte zuerst**\n\nText:\n\n{text}\n", + "variables": { + "text": { + "type": "string", + "required": true, + "description": "Der zu Zusammenfassende Text" + }, + "length": { + "type": "enum", + "values": ["10%", "25%", "50%", "75%"], + "default": "25%", + "description": "Ziel-Länge der Zusammenfassung" + }, + "focus_area": { + "type": "string", + "default": "Haupteaussagen", + "description": "Thematischer Fokus" + }, + "format": { + "type": "enum", + "values": [" bullets", "paragraph"], + "default": "bullets" + } + }, + "tags": ["summary", "text", "condense", "abstract"], + "language": "de" +} diff --git a/templates/user/email_draft.md b/templates/user/email_draft.md new file mode 100644 index 0000000..d385b1f --- /dev/null +++ b/templates/user/email_draft.md @@ -0,0 +1,61 @@ +# Email Entwurf Assistent + +**Rolle**: Professioneller Kommunikationsberater + +**Beschreibung**: Erstellt formelle oder informelle Email-Entwürfe basierend auf den gegebenen Parametern. + +--- + +## Template + +``` +Schreibe eine Email mit folgenden Spearman: + +**Betreff**: {subject} +**Empfänger**: {recipient} (Ton: {tone}) +**Inhalt**: +{content} + +**Anforderungen**: +- Sprache: {language} +- Länge: {length} +- Signatur: {signature} + +--- +Email: +``` + +--- + +## Variablen + +| Variable | Typ | Required | Default | Beschreibung | +|----------|-----|----------|---------|---------------| +| `subject` | string | ✅ | - | Email Betreffzeile | +| `recipient` | string | ✅ | - | Empfänger (Name oder Rolle) | +| `content` | string | ✅ | - | Hauptinhalt der Email | +| `tone` | enum | ❌ | "formell" | Tonfall: formell,neutral,freundlich | +| `language` | enum | ❌ | "de" | Sprache: de, en, fr | +| `length` | enum | ❌ | "mittel" | Länge: kurz, mittel, lang | +| `signature` | string | ❌ | - | Absendersignatur | + +--- + +## Beispiele + +### Beispiel 1: Formelle Einladung +``` +subject: "Terminbestätigung: Projektreview am 15.05." +recipient: "Herrn Müller (Projektleitung)" +tone: "formell" +content: "Bestätigung des Termins für das Projektreview incl. Agenda" +``` + +### Beispiel 2: Kurze interne Nachricht +``` +subject: "Quick Update: Server Status" +recipient: "Team IT" +tone: "neutral" +length: "kurz" +content: "Der Server ist wieder online. Ursache war ein Speicherleck." +```