Assembles the final prompt within a hard token budget. Reservation order (priority, highest first): 1. System prompt — fixed overhead, always fits 2. Constraints — hard requirements, always fits 3. Mutation hint — retry correction 4. Context — truncated
| 352 | # ============================================================================= |
| 353 | |
| 354 | class PromptBuilder: |
| 355 | """ |
| 356 | Assembles the final prompt within a hard token budget. |
| 357 | |
| 358 | Reservation order (priority, highest first): |
| 359 | 1. System prompt — fixed overhead, always fits |
| 360 | 2. Constraints — hard requirements, always fits |
| 361 | 3. Mutation hint — retry correction |
| 362 | 4. Context — truncated if budget is tight |
| 363 | 5. User input — what the user actually asked |
| 364 | """ |
| 365 | |
| 366 | def __init__( |
| 367 | self, |
| 368 | system_prompt: str, |
| 369 | config: ControlLayerConfig, |
| 370 | ): |
| 371 | self.system_prompt = system_prompt |
| 372 | self.config = config |
| 373 | |
| 374 | def build( |
| 375 | self, |
| 376 | user_input: str, |
| 377 | constraints: List[str], |
| 378 | context: str = "", |
| 379 | mutation_hint: str = "", |
| 380 | ) -> Tuple[str, TokenBudget]: |
| 381 | budget = TokenBudget(self.config.total_tokens, self.config.model_name) |
| 382 | |
| 383 | budget.reserve("system_prompt", self.system_prompt) |
| 384 | |
| 385 | constraint_block = self._format_constraints(constraints) |
| 386 | if constraint_block: |
| 387 | budget.reserve("constraints", constraint_block) |
| 388 | |
| 389 | if mutation_hint: |
| 390 | budget.reserve("mutation_hint", mutation_hint) |
| 391 | |
| 392 | if context: |
| 393 | if not budget.reserve("context", context): |
| 394 | # Truncate context to fit remaining budget |
| 395 | max_chars = budget.remaining_chars() |
| 396 | context = context[:max_chars] |
| 397 | budget.reserve("context_truncated", context) |
| 398 | |
| 399 | budget.reserve("user_input", user_input) |
| 400 | |
| 401 | parts = [self.system_prompt] |
| 402 | if constraint_block: |
| 403 | parts.append(constraint_block) |
| 404 | if mutation_hint: |
| 405 | parts.append(f"Correction note: {mutation_hint}") |
| 406 | if context: |
| 407 | parts.append(f"Context:\n{context}") |
| 408 | parts.append(f"User: {user_input}") |
| 409 | |
| 410 | return "\n\n".join(parts), budget |
| 411 |
no outgoing calls