Skip to content

Commit

Permalink
core: Add ruff rules for error messages (EM) (#26965)
Browse files Browse the repository at this point in the history
All auto-fixes

Co-authored-by: Erick Friis <[email protected]>
  • Loading branch information
cbornet and efriis authored Oct 7, 2024
1 parent 37ca468 commit d31ec88
Show file tree
Hide file tree
Showing 94 changed files with 777 additions and 523 deletions.
23 changes: 14 additions & 9 deletions libs/core/langchain_core/_api/deprecation.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,18 @@ def _validate_deprecation_params(
) -> None:
"""Validate the deprecation parameters."""
if pending and removal:
raise ValueError("A pending deprecation cannot have a scheduled removal")
msg = "A pending deprecation cannot have a scheduled removal"
raise ValueError(msg)
if alternative and alternative_import:
raise ValueError("Cannot specify both alternative and alternative_import")
msg = "Cannot specify both alternative and alternative_import"
raise ValueError(msg)

if alternative_import and "." not in alternative_import:
raise ValueError(
msg = (
"alternative_import must be a fully qualified module path. Got "
f" {alternative_import}"
)
raise ValueError(msg)


def deprecated(
Expand Down Expand Up @@ -222,7 +225,8 @@ def warn_if_direct_instance(
if not _obj_type:
_obj_type = "attribute"
if not _name:
raise ValueError(f"Field {obj} must have a name to be deprecated.")
msg = f"Field {obj} must have a name to be deprecated."
raise ValueError(msg)
old_doc = obj.description

def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
Expand All @@ -241,7 +245,8 @@ def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
if not _obj_type:
_obj_type = "attribute"
if not _name:
raise ValueError(f"Field {obj} must have a name to be deprecated.")
msg = f"Field {obj} must have a name to be deprecated."
raise ValueError(msg)
old_doc = obj.description

def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
Expand Down Expand Up @@ -428,10 +433,11 @@ def warn_deprecated(
if not pending:
if not removal:
removal = f"in {removal}" if removal else "within ?? minor releases"
raise NotImplementedError(
msg = (
f"Need to determine which default deprecation schedule to use. "
f"{removal}"
)
raise NotImplementedError(msg)
else:
removal = f"in {removal}"

Expand Down Expand Up @@ -523,9 +529,8 @@ def decorator(f: Callable[_P, _R]) -> Callable[_P, _R]:
@functools.wraps(f)
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
if new in kwargs and old in kwargs:
raise TypeError(
f"{f.__name__}() got multiple values for argument {new!r}"
)
msg = f"{f.__name__}() got multiple values for argument {new!r}"
raise TypeError(msg)
if old in kwargs:
warn_deprecated(
since,
Expand Down
21 changes: 10 additions & 11 deletions libs/core/langchain_core/beta/runnables/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ def _key_from_id(id_: str) -> str:
elif wout_prefix.endswith(CONTEXT_CONFIG_SUFFIX_SET):
return wout_prefix[: -len(CONTEXT_CONFIG_SUFFIX_SET)]
else:
raise ValueError(f"Invalid context config id {id_}")
msg = f"Invalid context config id {id_}"
raise ValueError(msg)


def _config_with_context(
Expand Down Expand Up @@ -103,16 +104,15 @@ def _config_with_context(

for dep in deps_by_key[key]:
if key in deps_by_key[dep]:
raise ValueError(
f"Deadlock detected between context keys {key} and {dep}"
)
msg = f"Deadlock detected between context keys {key} and {dep}"
raise ValueError(msg)
if len(setters) != 1:
raise ValueError(f"Expected exactly one setter for context key {key}")
msg = f"Expected exactly one setter for context key {key}"
raise ValueError(msg)
setter_idx = setters[0][1]
if any(getter_idx < setter_idx for _, getter_idx in getters):
raise ValueError(
f"Context setter for key {key} must be defined after all getters."
)
msg = f"Context setter for key {key} must be defined after all getters."
raise ValueError(msg)

if getters:
context_funcs[getters[0][0].id] = partial(getter, events[key], values)
Expand Down Expand Up @@ -271,9 +271,8 @@ def config_specs(self) -> list[ConfigurableFieldSpec]:
if spec.id.endswith(CONTEXT_CONFIG_SUFFIX_GET):
getter_key = spec.id.split("/")[1]
if getter_key in self.keys:
raise ValueError(
f"Circular reference in context setter for key {getter_key}"
)
msg = f"Circular reference in context setter for key {getter_key}"
raise ValueError(msg)
return super().config_specs + [
ConfigurableFieldSpec(
id=id_,
Expand Down
3 changes: 2 additions & 1 deletion libs/core/langchain_core/caches.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,8 @@ def __init__(self, *, maxsize: Optional[int] = None) -> None:
"""
self._cache: dict[tuple[str, str], RETURN_VAL_TYPE] = {}
if maxsize is not None and maxsize <= 0:
raise ValueError("maxsize must be greater than 0")
msg = "maxsize must be greater than 0"
raise ValueError(msg)
self._maxsize = maxsize

def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:
Expand Down
10 changes: 4 additions & 6 deletions libs/core/langchain_core/callbacks/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,9 +275,8 @@ def on_chat_model_start(
"""
# NotImplementedError is thrown intentionally
# Callback handler will fall back to on_llm_start if this is exception is thrown
raise NotImplementedError(
f"{self.__class__.__name__} does not implement `on_chat_model_start`"
)
msg = f"{self.__class__.__name__} does not implement `on_chat_model_start`"
raise NotImplementedError(msg)

def on_retriever_start(
self,
Expand Down Expand Up @@ -523,9 +522,8 @@ async def on_chat_model_start(
"""
# NotImplementedError is thrown intentionally
# Callback handler will fall back to on_llm_start if this is exception is thrown
raise NotImplementedError(
f"{self.__class__.__name__} does not implement `on_chat_model_start`"
)
msg = f"{self.__class__.__name__} does not implement `on_chat_model_start`"
raise NotImplementedError(msg)

async def on_llm_new_token(
self,
Expand Down
15 changes: 10 additions & 5 deletions libs/core/langchain_core/callbacks/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -1510,11 +1510,12 @@ def on_custom_event(
.. versionadded:: 0.2.14
"""
if kwargs:
raise ValueError(
msg = (
"The dispatcher API does not accept additional keyword arguments."
"Please do not pass any additional keyword arguments, instead "
"include them in the data field."
)
raise ValueError(msg)
if run_id is None:
run_id = uuid.uuid4()

Expand Down Expand Up @@ -1989,11 +1990,12 @@ async def on_custom_event(
run_id = uuid.uuid4()

if kwargs:
raise ValueError(
msg = (
"The dispatcher API does not accept additional keyword arguments."
"Please do not pass any additional keyword arguments, instead "
"include them in the data field."
)
raise ValueError(msg)
await ahandle_event(
self.handlers,
"on_custom_event",
Expand Down Expand Up @@ -2336,11 +2338,12 @@ def _configure(

if v1_tracing_enabled_ and not tracing_v2_enabled_:
# if both are enabled, can silently ignore the v1 tracer
raise RuntimeError(
msg = (
"Tracing using LangChainTracerV1 is no longer supported. "
"Please set the LANGCHAIN_TRACING_V2 environment variable to enable "
"tracing instead."
)
raise RuntimeError(msg)

tracer_project = _get_tracer_project()
debug = _get_debug()
Expand Down Expand Up @@ -2519,13 +2522,14 @@ async def foo(inputs):
# within a tool or a lambda and have the metadata events associated
# with the parent run rather than have a new run id generated for each.
if callback_manager.parent_run_id is None:
raise RuntimeError(
msg = (
"Unable to dispatch an adhoc event without a parent run id."
"This function can only be called from within an existing run (e.g.,"
"inside a tool or a RunnableLambda or a RunnableGenerator.)"
"If you are doing that and still seeing this error, try explicitly"
"passing the config parameter to this function."
)
raise RuntimeError(msg)

await callback_manager.on_custom_event(
name,
Expand Down Expand Up @@ -2588,13 +2592,14 @@ def foo(inputs):
# within a tool or a lambda and have the metadata events associated
# with the parent run rather than have a new run id generated for each.
if callback_manager.parent_run_id is None:
raise RuntimeError(
msg = (
"Unable to dispatch an adhoc event without a parent run id."
"This function can only be called from within an existing run (e.g.,"
"inside a tool or a RunnableLambda or a RunnableGenerator.)"
"If you are doing that and still seeing this error, try explicitly"
"passing the config parameter to this function."
)
raise RuntimeError(msg)
callback_manager.on_custom_event(
name,
data,
Expand Down
3 changes: 2 additions & 1 deletion libs/core/langchain_core/chat_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,11 @@ def add_message(self, message: BaseMessage) -> None:
# method, so we should use it.
self.add_messages([message])
else:
raise NotImplementedError(
msg = (
"add_message is not implemented for this class. "
"Please implement add_message or add_messages."
)
raise NotImplementedError(msg)

def add_messages(self, messages: Sequence[BaseMessage]) -> None:
"""Add a list of messages.
Expand Down
10 changes: 5 additions & 5 deletions libs/core/langchain_core/document_loaders/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,12 @@ def load_and_split(
try:
from langchain_text_splitters import RecursiveCharacterTextSplitter
except ImportError as e:
raise ImportError(
msg = (
"Unable to import from langchain_text_splitters. Please specify "
"text_splitter or install langchain_text_splitters with "
"`pip install -U langchain-text-splitters`."
) from e
)
raise ImportError(msg) from e

_text_splitter: TextSplitter = RecursiveCharacterTextSplitter()
else:
Expand All @@ -71,9 +72,8 @@ def lazy_load(self) -> Iterator[Document]:
"""A lazy loader for Documents."""
if type(self).load != BaseLoader.load:
return iter(self.load())
raise NotImplementedError(
f"{self.__class__.__name__} does not implement lazy_load()"
)
msg = f"{self.__class__.__name__} does not implement lazy_load()"
raise NotImplementedError(msg)

async def alazy_load(self) -> AsyncIterator[Document]:
"""A lazy loader for Documents."""
Expand Down
12 changes: 8 additions & 4 deletions libs/core/langchain_core/documents/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ def source(self) -> Optional[str]:
def check_blob_is_valid(cls, values: dict[str, Any]) -> Any:
"""Verify that either data or path is provided."""
if "data" not in values and "path" not in values:
raise ValueError("Either data or path must be provided")
msg = "Either data or path must be provided"
raise ValueError(msg)
return values

def as_string(self) -> str:
Expand All @@ -155,7 +156,8 @@ def as_string(self) -> str:
elif isinstance(self.data, str):
return self.data
else:
raise ValueError(f"Unable to get string for blob {self}")
msg = f"Unable to get string for blob {self}"
raise ValueError(msg)

def as_bytes(self) -> bytes:
"""Read data as bytes."""
Expand All @@ -167,7 +169,8 @@ def as_bytes(self) -> bytes:
with open(str(self.path), "rb") as f:
return f.read()
else:
raise ValueError(f"Unable to get bytes for blob {self}")
msg = f"Unable to get bytes for blob {self}"
raise ValueError(msg)

@contextlib.contextmanager
def as_bytes_io(self) -> Generator[Union[BytesIO, BufferedReader], None, None]:
Expand All @@ -178,7 +181,8 @@ def as_bytes_io(self) -> Generator[Union[BytesIO, BufferedReader], None, None]:
with open(str(self.path), "rb") as f:
yield f
else:
raise NotImplementedError(f"Unable to convert blob {self}")
msg = f"Unable to convert blob {self}"
raise NotImplementedError(msg)

@classmethod
def from_path(
Expand Down
3 changes: 2 additions & 1 deletion libs/core/langchain_core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,11 @@ def __init__(
):
super().__init__(error)
if send_to_llm and (observation is None or llm_output is None):
raise ValueError(
msg = (
"Arguments 'observation' & 'llm_output'"
" are required if 'send_to_llm' is True"
)
raise ValueError(msg)
self.observation = observation
self.llm_output = llm_output
self.send_to_llm = send_to_llm
Loading

0 comments on commit d31ec88

Please sign in to comment.