1"""Core type definitions for the prompt library system.

2

3 This module defines:

4- Validation levels and configuration

5- Prompt template structures

6- RAG configuration types

7- Message index types

8- Render result types

9"""

10

11 from enum import Enum

12 from typing import Any, Dict, List, TypedDict

13 from dataclasses import dataclass, field

14

15

16 class ValidationLevel(Enum):

17 """Validation strictness levels for template rendering.

18

19 Attributes:

20 ERROR: Raise exception for missing required parameters

21 WARN: Log warning for missing required parameters (default)

22 IGNORE: Silently ignore missing required parameters

23 """

24 ERROR = "error"

25 WARN = "warn"

26 IGNORE = "ignore"

27

28

29 class TemplateMode(Enum):

30 """Template rendering mode.

31

32 Attributes:

33 MIXED: Pre-process (( )) conditionals then render with Jinja2 (default)

34 JINJA2: Pure Jinja2 rendering, skip (( )) preprocessing

35 """

36 MIXED = "mixed"

37 JINJA2 = "jinja2"

38

39 @classmethod

40 def from_string(cls, value: str) -> "TemplateMode":

41 """Parse mode from string.

42

43 Args:

44 value: Mode string ("mixed" or "jinja2")

45

46 Returns:

47 TemplateMode enum value

48

49 Raises:

50 ValueError: If value is not a valid mode

51 """

52 try:

53 return cls(value.lower())

54 except ValueError as e:

55 raise ValueError(

56 f"Invalid template mode: {value}. "

57 f"Valid modes: {', '.join(m.value for m in cls)}"

58 ) from e

59

60

61@dataclass

62 class ValidationConfig:

63 """Configuration for template parameter validation.

64

65 Attributes:

66 level: Validation strictness level (None to inherit from context)

67 required_params: Set of parameter names that must be provided

68 optional_params: Set of parameter names that are optional

69 """

70 level: ValidationLevel | None = None

71 required_params: set[str] = field(default_factory=set)

72 optional_params: set[str] = field(default_factory=set)

73

74 def __init__(

75 self,

76 level: ValidationLevel | None = None,

77 required_params: List[str] | None = None,

78 optional_params: List[str] | None = None

79 ):

80 """Initialize validation configuration.

81

82 Args:

83 level: Validation strictness level (None to inherit from context)

84 required_params: List of required parameter names

85 optional_params: List of optional parameter names

86 """

87 self.level = level

88 self.required_params = set(required_params or [])

89 self.optional_params = set(optional_params or [])

90

91

92 class PromptTemplateDict(TypedDict, total=False):

93 """TypedDict structure for prompt template configuration.

94

95 This defines the schema for prompt template definitions used throughout

96 the prompt library system. It supports template inheritance, validation,

97 RAG configuration, and flexible template composition.

98

99 Attributes:

100 template: The template string with {{variables}} and ((conditionals))

101 defaults: Default values for template parameters

102 validation: Validation configuration for this template

103 metadata: Additional metadata (author, version, etc.)

104 sections: Section definitions for template composition

105 extends: Name of base template to inherit from

106 rag_config_refs: References to standalone RAG configurations

107 rag_configs: Inline RAG configurations

108 template_mode: Template rendering mode ("mixed" or "jinja2")

109 """

110 template: str

111 defaults: Dict[str, Any]

112 validation: ValidationConfig

113 metadata: Dict[str, Any]

114 sections: Dict[str, str]

115 extends: str

116 rag_config_refs: List[str]

117 rag_configs: List['RAGConfig']

118 template_mode: str

119

120

121 class RAGConfig(TypedDict, total=False):

122 """Configuration for RAG (Retrieval-Augmented Generation) searches.

123

124 Attributes:

125 adapter_name: Name of the adapter to use for RAG search

126 query: RAG search query (may contain {{variables}})

127 k: Number of results to retrieve

128 filters: Additional filters for the search

129 placeholder: Placeholder name in template (e.g., "RAG_CONTENT")

130 header: Header text to prepend to RAG results

131 item_template: Template for formatting individual RAG items

132 """

133 adapter_name: str

134 query: str

135 k: int

136 filters: Dict[str, Any]

137 placeholder: str

138 header: str

139 item_template: str

140

141

142 class MessageIndex(TypedDict, total=False):

143 """Structure for a message index definition.

144

145 Message indexes define sequences of messages with roles and content,

146 including support for RAG content injection.

147

148 Attributes:

149 messages: List of message dictionaries with 'role' and 'content'

150 rag_configs: RAG configurations for this message sequence

151 metadata: Additional metadata for this message index

152 """

153 messages: List[Dict[str, str]]

154 rag_configs: List[RAGConfig]

155 metadata: Dict[str, Any]

156

157

158@dataclass

159 class RenderResult:

160 """Result of rendering a prompt template.

161

162 Attributes:

163 content: The final rendered content

164 params_used: Parameters that were actually used in rendering

165 params_missing: Required parameters that were missing

166 validation_warnings: List of validation warnings (if level=WARN)

167 metadata: Additional metadata about the rendering

168 rag_metadata: Optional RAG metadata (if return_rag_metadata=True)

169 Contains details about RAG searches executed during rendering

170 """

171 content: str

172 params_used: Dict[str, Any] = field(default_factory=dict)

173 params_missing: List[str] = field(default_factory=list)

174 validation_warnings: List[str] = field(default_factory=list)

175 metadata: Dict[str, Any] = field(default_factory=dict)

176 rag_metadata: Dict[str, Any] | None = None

177

178

179# Type aliases for convenience

180 TemplateDict = Dict[str, PromptTemplateDict]

181 MessageIndexDict = Dict[str, MessageIndex]

182 ParameterDict = Dict[str, Any]

183 AdapterDict = Dict[str, Any] # Will be refined in adapter modules