Home / File/ formatting.py — langchain Source File

formatting.py — langchain Source File

Architecture documentation for formatting.py, a python file in the langchain codebase. 3 imports, 0 dependents.

Entity Profile

Dependency Diagram

graph LR
  a6cb80fd_c1ac_c959_2d3d_637ca2511f97["formatting.py"]
  cfe2bde5_180e_e3b0_df2b_55b3ebaca8e7["collections.abc"]
  a6cb80fd_c1ac_c959_2d3d_637ca2511f97 --> cfe2bde5_180e_e3b0_df2b_55b3ebaca8e7
  06ab3965_70ce_6e2c_feb9_564d849aa5f4["string"]
  a6cb80fd_c1ac_c959_2d3d_637ca2511f97 --> 06ab3965_70ce_6e2c_feb9_564d849aa5f4
  8e2034b7_ceb8_963f_29fc_2ea6b50ef9b3["typing"]
  a6cb80fd_c1ac_c959_2d3d_637ca2511f97 --> 8e2034b7_ceb8_963f_29fc_2ea6b50ef9b3
  style a6cb80fd_c1ac_c959_2d3d_637ca2511f97 fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

"""Utilities for formatting strings."""

from collections.abc import Mapping, Sequence
from string import Formatter
from typing import Any


class StrictFormatter(Formatter):
    """A string formatter that enforces keyword-only argument substitution.

    This formatter extends Python's built-in `string.Formatter` to provide stricter
    validation for prompt template formatting. It ensures that all variable
    substitutions use keyword arguments rather than positional arguments, which improves
    clarity and reduces errors when formatting prompt templates.

    Example:
        >>> fmt = StrictFormatter()
        >>> fmt.format("Hello, {name}!", name="World")
        'Hello, World!'
        >>> fmt.format("Hello, {}!", "World")  # Raises ValueError
    """

    def vformat(
        self, format_string: str, args: Sequence, kwargs: Mapping[str, Any]
    ) -> str:
        """Format a string using only keyword arguments.

        Overrides the base `vformat` to reject positional arguments, ensuring all
        substitutions are explicit and named.

        Args:
            format_string: A string containing replacement fields (e.g., `'{name}'`).
            args: Positional arguments (must be empty).
            kwargs: Keyword arguments for substitution into the format string.

        Returns:
            The formatted string with all replacement fields substituted.

        Raises:
            ValueError: If any positional arguments are provided.
        """
        if len(args) > 0:
            msg = (
                "No arguments should be provided, "
                "everything should be passed as keyword arguments."
            )
            raise ValueError(msg)
        return super().vformat(format_string, args, kwargs)

    def validate_input_variables(
        self, format_string: str, input_variables: list[str]
    ) -> None:
        """Validate that input variables match the placeholders in a format string.

        Checks that the provided input variables can be used to format the given string
        without missing or extra keys. This is useful for validating prompt templates
        before runtime.

        Args:
            format_string: A string containing replacement fields to validate
                against (e.g., `'Hello, {name}!'`).
            input_variables: List of variable names expected to fill the
                replacement fields.

        Raises:
            KeyError: If the format string contains placeholders not present
                in input_variables.

        Example:
            >>> fmt = StrictFormatter()
            >>> fmt.validate_input_variables("Hello, {name}!", ["name"])  # OK
            >>> fmt.validate_input_variables("Hello, {name}!", ["other"])  # Raises
        """
        dummy_inputs = dict.fromkeys(input_variables, "foo")
        super().format(format_string, **dummy_inputs)


#: Default StrictFormatter instance for use throughout LangChain.
#: Used internally for formatting prompt templates with named variables.
formatter = StrictFormatter()

Subdomains

Classes

Dependencies

  • collections.abc
  • string
  • typing

Frequently Asked Questions

What does formatting.py do?
formatting.py is a source file in the langchain codebase, written in python. It belongs to the CoreAbstractions domain, RunnableInterface subdomain.
What does formatting.py depend on?
formatting.py imports 3 module(s): collections.abc, string, typing.
Where is formatting.py in the architecture?
formatting.py is located at libs/core/langchain_core/utils/formatting.py (domain: CoreAbstractions, subdomain: RunnableInterface, directory: libs/core/langchain_core/utils).

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free