codekingpro/portable-devtools
114k
1"""Utilities for formatting strings."""2 3from collections.abc import Mapping, Sequence4from string import Formatter5from typing import Any6 7 8class StrictFormatter(Formatter):9 """A string formatter that enforces keyword-only argument substitution.10 11 This formatter extends Python's built-in `string.Formatter` to provide stricter12 validation for prompt template formatting. It ensures that all variable13 substitutions use keyword arguments rather than positional arguments, which improves14 clarity and reduces errors when formatting prompt templates.15 16 Example:17 >>> fmt = StrictFormatter()18 >>> fmt.format("Hello, {name}!", name="World")19 'Hello, World!'20 >>> fmt.format("Hello, {}!", "World") # Raises ValueError21 """22 23 def vformat(24 self, format_string: str, args: Sequence, kwargs: Mapping[str, Any]25 ) -> str:26 """Format a string using only keyword arguments.27 28 Overrides the base `vformat` to reject positional arguments, ensuring all29 substitutions are explicit and named.30 31 Args:32 format_string: A string containing replacement fields (e.g., `'{name}'`).33 args: Positional arguments (must be empty).34 kwargs: Keyword arguments for substitution into the format string.35 36 Returns:37 The formatted string with all replacement fields substituted.38 39 Raises:40 ValueError: If any positional arguments are provided.41 """42 if len(args) > 0:43 msg = (44 "No arguments should be provided, "45 "everything should be passed as keyword arguments."46 )47 raise ValueError(msg)48 return super().vformat(format_string, args, kwargs)49 50 def validate_input_variables(51 self, format_string: str, input_variables: list[str]52 ) -> None:53 """Validate that input variables match the placeholders in a format string.54 55 Checks that the provided input variables can be used to format the given string56 without missing or extra keys. This is useful for validating prompt templates57 before runtime.58 59 Args:60 format_string: A string containing replacement fields to validate61 against (e.g., `'Hello, {name}!'`).62 input_variables: List of variable names expected to fill the63 replacement fields.64 65 Raises:66 KeyError: If the format string contains placeholders not present67 in input_variables.68 69 Example:70 >>> fmt = StrictFormatter()71 >>> fmt.validate_input_variables("Hello, {name}!", ["name"]) # OK72 >>> fmt.validate_input_variables("Hello, {name}!", ["other"]) # Raises73 """74 dummy_inputs = dict.fromkeys(input_variables, "foo")75 super().format(format_string, **dummy_inputs)76 77 78#: Default StrictFormatter instance for use throughout LangChain.79#: Used internally for formatting prompt templates with named variables.80formatter = StrictFormatter()81 