Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
exceptions.py112 linesDownload Raw Back to langchain_core
1"""Custom **exceptions** for LangChain."""2 3from enum import Enum4from typing import Any5 6 7class LangChainException(Exception):  # noqa: N8188    """General LangChain exception."""9 10 11class TracerException(LangChainException):12    """Base class for exceptions in tracers module."""13 14 15class OutputParserException(ValueError, LangChainException):  # noqa: N81816    """Exception that output parsers should raise to signify a parsing error.17 18    This exists to differentiate parsing errors from other code or execution errors19    that also may arise inside the output parser.20 21    `OutputParserException` will be available to catch and handle in ways to fix the22    parsing error, while other errors will be raised.23    """24 25    def __init__(26        self,27        error: Any,28        observation: str | None = None,29        llm_output: str | None = None,30        send_to_llm: bool = False,  # noqa: FBT001,FBT00231    ):32        """Create an `OutputParserException`.33 34        Args:35            error: The error that's being re-raised or an error message.36            observation: String explanation of error which can be passed to a model to37                try and remediate the issue.38            llm_output: String model output which is error-ing.39 40            send_to_llm: Whether to send the observation and llm_output back to an Agent41                after an `OutputParserException` has been raised.42 43                This gives the underlying model driving the agent the context that the44                previous output was improperly structured, in the hopes that it will45                update the output to the correct format.46 47        Raises:48            ValueError: If `send_to_llm` is `True` but either observation or49                `llm_output` are not provided.50        """51        if isinstance(error, str):52            error = create_message(53                message=error, error_code=ErrorCode.OUTPUT_PARSING_FAILURE54            )55 56        super().__init__(error)57        if send_to_llm and (observation is None or llm_output is None):58            msg = (59                "Arguments 'observation' & 'llm_output'"60                " are required if 'send_to_llm' is True"61            )62            raise ValueError(msg)63        self.observation = observation64        self.llm_output = llm_output65        self.send_to_llm = send_to_llm66 67 68class ContextOverflowError(LangChainException):69    """Exception raised when input exceeds the model's context limit.70 71    This exception is raised by chat models when the input tokens exceed72    the maximum context window supported by the model.73    """74 75 76class ErrorCode(Enum):77    """Error codes."""78 79    INVALID_PROMPT_INPUT = "INVALID_PROMPT_INPUT"80    INVALID_TOOL_RESULTS = "INVALID_TOOL_RESULTS"  # Used in JS; not Py (yet)81    MESSAGE_COERCION_FAILURE = "MESSAGE_COERCION_FAILURE"82    MODEL_AUTHENTICATION = "MODEL_AUTHENTICATION"  # Used in JS; not Py (yet)83    MODEL_NOT_FOUND = "MODEL_NOT_FOUND"  # Used in JS; not Py (yet)84    MODEL_RATE_LIMIT = "MODEL_RATE_LIMIT"  # Used in JS; not Py (yet)85    OUTPUT_PARSING_FAILURE = "OUTPUT_PARSING_FAILURE"86 87 88def create_message(*, message: str, error_code: ErrorCode) -> str:89    """Create a message with a link to the LangChain troubleshooting guide.90 91    Args:92        message: The message to display.93        error_code: The error code to display.94 95    Returns:96        The full message with the troubleshooting link.97 98    Example:99        ```python100        create_message(101            message="Failed to parse output",102            error_code=ErrorCode.OUTPUT_PARSING_FAILURE,103        )104        "Failed to parse output. For troubleshooting, visit: ..."105        ```106    """107    return (108        f"{message}\n"109        "For troubleshooting, visit: https://docs.langchain.com/oss/python/langchain"110        f"/errors/{error_code.value} "111    )112 
codekingpro/portable-devtools · Team Ai