""" Template management with type support """ import json from pathlib import Path from typing import Optional, Tuple class TemplateManager: def __init__(self, templates_dir: Path): self.templates_dir = templates_dir def load_template(self, name: str) -> dict: """Load template by name and parse field types""" template_path = self.templates_dir / f'{name}.json' if not template_path.exists(): # Fallback to default template_path = self.templates_dir / 'default.json' with open(template_path, 'r', encoding='utf-8') as f: raw_template = json.load(f) # Parse template to separate strategies and types template = {} for field, value in raw_template.items(): template[field] = value return template def parse_field(self, field_value: str) -> Tuple[str, str]: """ Parse field value to extract strategy and type Format: "strategy|strategy:type" or just "strategy|strategy" Returns: (strategy, field_type) """ # Check if type is specified with colon if ':' in field_value: parts = field_value.rsplit(':', 1) strategy = parts[0] field_type = parts[1].strip() else: strategy = field_value field_type = 'text' # Default type return strategy, field_type def get_structured_output_schema(self, template: dict) -> dict: """Generate JSON schema for structured output based on field types""" properties = {} required = [] for field, field_value in template.items(): strategy, field_type = self.parse_field(str(field_value)) # Map field type to JSON schema type if field_type == 'list': properties[field] = { "type": "array", "items": {"type": "string"}, "description": f"Field: {field} (list of text)" } elif field_type == 'number': properties[field] = { "type": "number", "description": f"Field: {field} (number)" } elif field_type == 'checkbox': properties[field] = { "type": "boolean", "description": f"Field: {field} (true/false)" } elif field_type in ('date', 'datetime'): properties[field] = { "type": "string", "format": "date-time" if field_type == 'datetime' else "date", "description": f"Field: {field} ({field_type})" } else: # text or unspecified properties[field] = { "type": "string", "description": f"Field: {field} (text)" } required.append(field) return { "type": "object", "properties": properties, "required": required, "additionalProperties": False }