Spaces:
Sleeping
Sleeping
File size: 8,220 Bytes
e2b8b61 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | import json
import re
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
ROLE_HEADERS = {"# system", "# user", "# assistant"}
JSON_SCHEMA_HEADER = "# JSON schema"
def fill_template_file(template_path: str, data: Dict[str, Any]) -> Tuple[List[Dict[str, str]], Optional[Dict[str, Any]]]:
"""
Reads a DAS-style prompt template and returns:
1. chat messages: [{"role": "...", "content": "..."}]
2. response_format: dict | None
Supported template features:
- role headers:
# system
# user
# assistant
- placeholders:
[key]
{{key}}
- loop sections:
# start field_name
...
# end field_name
where data[field_name] is a list[dict]
- nested loops inside loops
- optional JSON schema block:
# JSON schema
{ ... valid JSON ... }
"""
raw_text = Path(template_path).read_text(encoding="utf-8")
prompt_text, schema_text = _split_prompt_and_schema(raw_text)
expanded_prompt = _expand_template(prompt_text, data)
messages = _parse_role_markdown(expanded_prompt)
response_format = None
if schema_text:
schema_payload = json.loads(schema_text)
response_format = _schema_to_response_format(schema_payload)
return messages, response_format
def _split_prompt_and_schema(text: str) -> Tuple[str, Optional[str]]:
if JSON_SCHEMA_HEADER not in text:
return text, None
prompt_part, schema_part = text.split(JSON_SCHEMA_HEADER, 1)
schema_text = schema_part.strip()
if not schema_text:
return prompt_part, None
return prompt_part.rstrip(), schema_text
def _schema_to_response_format(schema_payload: Dict[str, Any]) -> Dict[str, Any]:
"""
Expects DAS-style schema payload, e.g.
{
"name": "decoded_das",
"schema": {...},
"strict": true
}
"""
if "name" not in schema_payload or "schema" not in schema_payload:
raise ValueError("JSON schema block must contain at least 'name' and 'schema' keys.")
return {
"type": "json_schema",
"json_schema": {
"name": schema_payload["name"],
"schema": schema_payload["schema"],
"strict": schema_payload.get("strict", True),
},
}
def _expand_template(text: str, data: Dict[str, Any]) -> str:
lines = text.splitlines()
expanded_lines, _ = _process_block(lines, 0, data)
expanded_text = "\n".join(expanded_lines)
expanded_text = _replace_placeholders(expanded_text, data)
return expanded_text.strip()
def _process_block(lines: List[str], start_idx: int, context: Dict[str, Any]) -> Tuple[List[str], int]:
"""
Recursively processes lines until the end of the block or a matching # end ...
"""
output: List[str] = []
i = start_idx
while i < len(lines):
stripped = lines[i].strip()
if stripped.startswith("# end "):
return output, i
if stripped.startswith("# start "):
field_name = stripped.replace("# start ", "", 1).strip()
block_lines, end_idx = _collect_loop_block(lines, i + 1, field_name)
loop_value = _resolve_key(field_name, context)
if loop_value is None:
loop_value = []
if not isinstance(loop_value, list):
raise ValueError(f"Loop field '{field_name}' must be a list, got {type(loop_value).__name__}.")
for idx, item in enumerate(loop_value, start=1):
child_context = dict(context)
if isinstance(item, dict):
child_context.update(item)
else:
child_context[field_name] = item
child_context["$index"] = idx
child_context[field_name] = item
expanded_child, _ = _process_block(block_lines, 0, child_context)
output.extend(expanded_child)
i = end_idx + 1
continue
output.append(_replace_placeholders(lines[i], context))
i += 1
return output, i
def _collect_loop_block(lines: List[str], start_idx: int, field_name: str) -> Tuple[List[str], int]:
"""
Collects lines until the matching # end field_name, respecting nested loops.
Returns (block_lines, end_index).
"""
block: List[str] = []
depth = 1
i = start_idx
while i < len(lines):
stripped = lines[i].strip()
if stripped.startswith("# start "):
nested_name = stripped.replace("# start ", "", 1).strip()
if nested_name == field_name:
depth += 1
block.append(lines[i])
i += 1
continue
if stripped.startswith("# end "):
end_name = stripped.replace("# end ", "", 1).strip()
if end_name == field_name:
depth -= 1
if depth == 0:
return block, i
block.append(lines[i])
i += 1
continue
block.append(lines[i])
i += 1
raise ValueError(f"Missing matching '# end {field_name}' in template.")
def _parse_role_markdown(text: str) -> List[Dict[str, str]]:
messages: List[Dict[str, str]] = []
current_role: Optional[str] = None
buffer: List[str] = []
for line in text.splitlines():
stripped = line.strip()
if stripped in ROLE_HEADERS:
if current_role is not None:
content = _clean_content("\n".join(buffer))
messages.append({"role": current_role, "content": content})
current_role = stripped.replace("# ", "")
buffer = []
continue
buffer.append(line)
if current_role is not None:
content = _clean_content("\n".join(buffer))
messages.append({"role": current_role, "content": content})
if not messages:
raise ValueError(
"Template must contain at least one role header: '# system', '# user', or '# assistant'."
)
return messages
def _clean_content(text: str) -> str:
lines = text.splitlines()
while lines and not lines[0].strip():
lines.pop(0)
while lines and not lines[-1].strip():
lines.pop()
if not lines:
return ""
min_indent = None
for line in lines:
if not line.strip():
continue
indent = len(line) - len(line.lstrip(" "))
if min_indent is None or indent < min_indent:
min_indent = indent
min_indent = min_indent or 0
cleaned = "\n".join(line[min_indent:] if len(line) >= min_indent else line for line in lines)
return cleaned.strip()
def _replace_placeholders(text: str, context: Dict[str, Any]) -> str:
"""
Supports both:
[key]
{{key}}
including dotted keys:
[speaker.name]
{{speaker.name}}
and special loop index:
[$index]
{{$index}}
"""
def square_repl(match: re.Match) -> str:
key = match.group(1).strip()
value = _resolve_key(key, context)
return _stringify(value)
def brace_repl(match: re.Match) -> str:
key = match.group(1).strip()
value = _resolve_key(key, context)
return _stringify(value)
text = re.sub(r"\[([^\[\]]+)\]", square_repl, text)
text = re.sub(r"\{\{([^{}]+)\}\}", brace_repl, text)
return text
def _resolve_key(key: str, context: Dict[str, Any]) -> Any:
if key in context:
return context[key]
if "." not in key:
return ""
current: Any = context
for part in key.split("."):
part = part.strip()
if isinstance(current, dict) and part in current:
current = current[part]
else:
return ""
return current
def _stringify(value: Any) -> str:
if value is None:
return ""
if isinstance(value, str):
return value
if isinstance(value, (int, float, bool)):
return str(value)
if isinstance(value, list):
return ", ".join(_stringify(v) for v in value)
if isinstance(value, dict):
return json.dumps(value, ensure_ascii=False)
return str(value) |