|
| 1 | +""" |
| 2 | +Input validation and sanitization utilities for LLM chat drivers. |
| 3 | +
|
| 4 | +This module provides functions to validate and sanitize user input before |
| 5 | +it is sent to LLM provider APIs. It guards against: |
| 6 | +
|
| 7 | +- Control characters that cause API errors or undefined behavior |
| 8 | +- Prompts that exceed provider context windows |
| 9 | +- Empty or whitespace-only prompts |
| 10 | +- Model name strings that contain unexpected characters |
| 11 | +- Output token values that exceed known safe maximums |
| 12 | +""" |
| 13 | + |
| 14 | +import re |
| 15 | +from typing import Optional |
| 16 | + |
| 17 | +from rocketlib import debug |
| 18 | + |
| 19 | +# Matches C0/C1 control characters EXCEPT common whitespace (\t \n \r) |
| 20 | +_CONTROL_CHAR_RE = re.compile(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]') |
| 21 | + |
| 22 | +# Model names should be alphanumeric with hyphens, dots, slashes, colons, at-signs, and underscores |
| 23 | +# e.g. "gpt-4", "claude-3-opus-20240229", "us.anthropic.claude-3", "meta-llama/Llama-3", "org@model" |
| 24 | +_MODEL_NAME_RE = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9._:/@-]*$') |
| 25 | + |
| 26 | +# Absolute upper bound for output tokens across all known providers (as of 2026) |
| 27 | +MAX_OUTPUT_TOKENS = 1_000_000 |
| 28 | + |
| 29 | + |
| 30 | +def sanitize_prompt(prompt: str) -> str: |
| 31 | + """Strip control characters from a prompt string. |
| 32 | +
|
| 33 | + Removes C0/C1 control characters that are known to cause errors or |
| 34 | + undefined behavior in LLM APIs while preserving normal whitespace |
| 35 | + (tabs, newlines, carriage returns). |
| 36 | +
|
| 37 | + Args: |
| 38 | + prompt: The raw prompt string. |
| 39 | +
|
| 40 | + Returns: |
| 41 | + The sanitized prompt with control characters removed. |
| 42 | + """ |
| 43 | + sanitized = _CONTROL_CHAR_RE.sub('', prompt) |
| 44 | + if sanitized != prompt: |
| 45 | + removed_count = len(prompt) - len(sanitized) |
| 46 | + debug(f'Sanitized {removed_count} control character(s) from prompt') |
| 47 | + return sanitized |
| 48 | + |
| 49 | + |
| 50 | +def validate_prompt(prompt: str, max_tokens: int, token_counter) -> str: |
| 51 | + """Validate and sanitize a prompt before sending to an LLM API. |
| 52 | +
|
| 53 | + Performs the following checks in order: |
| 54 | + 1. Rejects empty / whitespace-only prompts |
| 55 | + 2. Strips dangerous control characters |
| 56 | + 3. Warns if the prompt likely exceeds the model's context window |
| 57 | +
|
| 58 | + Args: |
| 59 | + prompt: The raw prompt string. |
| 60 | + max_tokens: The model's total token limit (context window). |
| 61 | + token_counter: A callable that estimates token count for a string. |
| 62 | +
|
| 63 | + Returns: |
| 64 | + The sanitized prompt string, ready for the API call. |
| 65 | +
|
| 66 | + Raises: |
| 67 | + ValueError: If the prompt is empty or whitespace-only. |
| 68 | + """ |
| 69 | + if not prompt or not prompt.strip(): |
| 70 | + raise ValueError('Prompt is empty or contains only whitespace.') |
| 71 | + |
| 72 | + # Sanitize control characters |
| 73 | + prompt = sanitize_prompt(prompt) |
| 74 | + |
| 75 | + # Re-check after sanitization to catch control-only prompts |
| 76 | + if not prompt.strip(): |
| 77 | + raise ValueError('Prompt is empty after sanitization.') |
| 78 | + |
| 79 | + # Check token count - warn but don't block (ChatBase.chat_string already |
| 80 | + # has a softer check; this catches the truly egregious cases early) |
| 81 | + try: |
| 82 | + token_count = token_counter(prompt) |
| 83 | + if token_count > max_tokens: |
| 84 | + debug(f'Warning: Prompt ({token_count} tokens) exceeds model context window ({max_tokens} tokens). The request will likely be rejected by the provider.') |
| 85 | + except Exception: |
| 86 | + # Token counting failures should not block the request |
| 87 | + pass |
| 88 | + |
| 89 | + return prompt |
| 90 | + |
| 91 | + |
| 92 | +def validate_model_name(model: Optional[str]) -> Optional[str]: |
| 93 | + """Validate that a model name is well-formed. |
| 94 | +
|
| 95 | + Args: |
| 96 | + model: The model identifier string, or None if not yet configured. |
| 97 | +
|
| 98 | + Returns: |
| 99 | + The validated model name (stripped of leading/trailing whitespace), |
| 100 | + or None if model was None (not yet configured). |
| 101 | +
|
| 102 | + Raises: |
| 103 | + ValueError: If the model name is non-None but empty or contains |
| 104 | + invalid characters. |
| 105 | + """ |
| 106 | + if model is None: |
| 107 | + return None |
| 108 | + |
| 109 | + if not isinstance(model, str): |
| 110 | + raise ValueError(f'Model name must be a string, got {type(model).__name__}.') |
| 111 | + |
| 112 | + if not model.strip(): |
| 113 | + raise ValueError('Model name was provided but is empty.') |
| 114 | + |
| 115 | + model = model.strip() |
| 116 | + |
| 117 | + if not _MODEL_NAME_RE.match(model): |
| 118 | + raise ValueError(f'Invalid model name: {model!r}. Model names must start with an alphanumeric character and contain only letters, digits, hyphens, dots, underscores, colons, at-signs, or slashes.') |
| 119 | + |
| 120 | + return model |
| 121 | + |
| 122 | + |
| 123 | +def validate_max_tokens(output_tokens: int, total_tokens: int) -> int: |
| 124 | + """Validate that the output token limit is within reasonable bounds. |
| 125 | +
|
| 126 | + Args: |
| 127 | + output_tokens: The configured max output tokens. |
| 128 | + total_tokens: The model's total context window. |
| 129 | +
|
| 130 | + Returns: |
| 131 | + The validated output token value (clamped if necessary). |
| 132 | +
|
| 133 | + Raises: |
| 134 | + ValueError: If output_tokens is not a positive integer. |
| 135 | + """ |
| 136 | + if not isinstance(output_tokens, int) or isinstance(output_tokens, bool) or output_tokens < 1: |
| 137 | + raise ValueError(f'Output tokens must be a positive integer, got {output_tokens!r}.') |
| 138 | + |
| 139 | + if not isinstance(total_tokens, int) or isinstance(total_tokens, bool) or total_tokens < 1: |
| 140 | + raise ValueError(f'Total tokens must be a positive integer, got {total_tokens!r}.') |
| 141 | + |
| 142 | + if output_tokens > MAX_OUTPUT_TOKENS: |
| 143 | + debug(f'Warning: Output tokens ({output_tokens}) exceeds maximum known limit ({MAX_OUTPUT_TOKENS}). Clamping to {MAX_OUTPUT_TOKENS}.') |
| 144 | + output_tokens = MAX_OUTPUT_TOKENS |
| 145 | + |
| 146 | + if output_tokens > total_tokens: |
| 147 | + debug(f'Warning: Output tokens ({output_tokens}) exceeds total tokens ({total_tokens}). Clamping to total tokens.') |
| 148 | + output_tokens = total_tokens |
| 149 | + |
| 150 | + return output_tokens |
0 commit comments