Skip to content

The agent engineering platform.

langchain: Add ruff rules EM (#31873)

Christophe Bornet49c316667def
diff --git a/libs/langchain/langchain/__init__.py b/libs/langchain/langchain/__init__.py
index 528f773db0..f4e9e521d3 100644
--- a/libs/langchain/langchain/__init__.py
+++ b/libs/langchain/langchain/__init__.py
@@ -67,7 +67,7 @@ def __getattr__(name: str) -> Any:
return ConversationChain
elif name == "LLMBashChain":
- raise ImportError(
+ msg = (
"This module has been moved to langchain-experimental. "
"For more details: "
"https://github.com/langchain-ai/langchain/discussions/11352."
@@ -75,6 +75,7 @@ def __getattr__(name: str) -> Any:
"`from langchain_experimental.llm_bash.base "
"import LLMBashChain`"
)
+ raise ImportError(msg)
elif name == "LLMChain":
from langchain.chains import LLMChain
@@ -386,7 +387,8 @@ def __getattr__(name: str) -> Any:
return _llm_cache
else:
- raise AttributeError(f"Could not find: {name}")
+ msg = f"Could not find: {name}"
+ raise AttributeError(msg)
__all__ = [
diff --git a/libs/langchain/langchain/_api/module_import.py b/libs/langchain/langchain/_api/module_import.py
index 83fa148352..fdfc1cee08 100644
--- a/libs/langchain/langchain/_api/module_import.py
+++ b/libs/langchain/langchain/_api/module_import.py
@@ -60,20 +60,22 @@ def create_importer(
if all_module_lookup and name in all_module_lookup:
new_module = all_module_lookup[name]
if new_module.split(".")[0] not in ALLOWED_TOP_LEVEL_PKGS:
- raise AssertionError(
+ msg = (
f"Importing from {new_module} is not allowed. "
f"Allowed top-level packages are: {ALLOWED_TOP_LEVEL_PKGS}"
)
+ raise AssertionError(msg)
try:
module = importlib.import_module(new_module)
except ModuleNotFoundError as e:
if new_module.startswith("langchain_community"):
- raise ModuleNotFoundError(
+ msg = (
f"Module {new_module} not found. "
"Please install langchain-community to access this module. "
"You can install it using `pip install -U langchain-community`"
- ) from e
+ )
+ raise ModuleNotFoundError(msg) from e
raise
try:
@@ -106,9 +108,8 @@ def create_importer(
)
return result
except Exception as e:
- raise AttributeError(
- f"module {new_module} has no attribute {name}"
- ) from e
+ msg = f"module {new_module} has no attribute {name}"
+ raise AttributeError(msg) from e
if fallback_module:
try:
@@ -139,10 +140,10 @@ def create_importer(
return result
except Exception as e:
- raise AttributeError(
- f"module {fallback_module} has no attribute {name}"
- ) from e
+ msg = f"module {fallback_module} has no attribute {name}"
+ raise AttributeError(msg) from e
- raise AttributeError(f"module {package} has no attribute {name}")
+ msg = f"module {package} has no attribute {name}"
+ raise AttributeError(msg)
return import_by_name
diff --git a/libs/langchain/langchain/agents/__init__.py b/libs/langchain/langchain/agents/__init__.py
index e0250585fe..7e99899d38 100644
--- a/libs/langchain/langchain/agents/__init__.py
+++ b/libs/langchain/langchain/agents/__init__.py
@@ -126,12 +126,13 @@ def __getattr__(name: str) -> Any:
)
old_path = "langchain." + relative_path
new_path = "langchain_experimental." + relative_path
- raise ImportError(
+ msg = (
f"{name} has been moved to langchain experimental. "
"See https://github.com/langchain-ai/langchain/discussions/11680"
"for more information.\n"
f"Please update your import statement from: `{old_path}` to `{new_path}`."
)
+ raise ImportError(msg)
return _import_attribute(name)
diff --git a/libs/langchain/langchain/agents/agent.py b/libs/langchain/langchain/agents/agent.py
index 129e443c4d..c783aa9d70 100644
--- a/libs/langchain/langchain/agents/agent.py
+++ b/libs/langchain/langchain/agents/agent.py
@@ -137,9 +137,8 @@ class BaseSingleActionAgent(BaseModel):
{"output": "Agent stopped due to iteration limit or time limit."}, ""
)
else:
- raise ValueError(
- f"Got unsupported early_stopping_method `{early_stopping_method}`"
- )
+ msg = f"Got unsupported early_stopping_method `{early_stopping_method}`"
+ raise ValueError(msg)
@classmethod
def from_llm_and_tools(
@@ -208,7 +207,8 @@ class BaseSingleActionAgent(BaseModel):
# Fetch dictionary to save
agent_dict = self.dict()
if "_type" not in agent_dict:
- raise NotImplementedError(f"Agent {self} does not support saving")
+ msg = f"Agent {self} does not support saving"
+ raise NotImplementedError(msg)
if save_path.suffix == ".json":
with open(file_path, "w") as f:
@@ -217,7 +217,8 @@ class BaseSingleActionAgent(BaseModel):
with open(file_path, "w") as f:
yaml.dump(agent_dict, f, default_flow_style=False)
else:
- raise ValueError(f"{save_path} must be json or yaml")
+ msg = f"{save_path} must be json or yaml"
+ raise ValueError(msg)
def tool_run_logging_kwargs(self) -> builtins.dict:
"""Return logging kwargs for tool run."""
@@ -310,9 +311,8 @@ class BaseMultiActionAgent(BaseModel):
# `force` just returns a constant string
return AgentFinish({"output": "Agent stopped due to max iterations."}, "")
else:
- raise ValueError(
- f"Got unsupported early_stopping_method `{early_stopping_method}`"
- )
+ msg = f"Got unsupported early_stopping_method `{early_stopping_method}`"
+ raise ValueError(msg)
@property
def _agent_type(self) -> str:
@@ -353,7 +353,8 @@ class BaseMultiActionAgent(BaseModel):
# Fetch dictionary to save
agent_dict = self.dict()
if "_type" not in agent_dict:
- raise NotImplementedError(f"Agent {self} does not support saving.")
+ msg = f"Agent {self} does not support saving."
+ raise NotImplementedError(msg)
directory_path = save_path.parent
directory_path.mkdir(parents=True, exist_ok=True)
@@ -365,7 +366,8 @@ class BaseMultiActionAgent(BaseModel):
with open(file_path, "w") as f:
yaml.dump(agent_dict, f, default_flow_style=False)
else:
- raise ValueError(f"{save_path} must be json or yaml")
+ msg = f"{save_path} must be json or yaml"
+ raise ValueError(msg)
def tool_run_logging_kwargs(self) -> builtins.dict:
"""Return logging kwargs for tool run."""
@@ -760,7 +762,8 @@ class Agent(BaseSingleActionAgent):
Returns:
str: Fixed text.
"""
- raise ValueError("fix_text not implemented for this agent.")
+ msg = "fix_text not implemented for this agent."
+ raise ValueError(msg)
@property
def _stop(self) -> list[str]:
@@ -874,7 +877,8 @@ class Agent(BaseSingleActionAgent):
elif isinstance(prompt, FewShotPromptTemplate):
prompt.suffix += "\n{agent_scratchpad}"
else:
- raise ValueError(f"Got unexpected prompt type {type(prompt)}")
+ msg = f"Got unexpected prompt type {type(prompt)}"
+ raise ValueError(msg)
return self
@property
@@ -998,10 +1002,11 @@ class Agent(BaseSingleActionAgent):
# we just return the full output
return AgentFinish({"output": full_output}, full_output)
else:
- raise ValueError(
+ msg = (
"early_stopping_method should be one of `force` or `generate`, "
f"got {early_stopping_method}"
)
+ raise ValueError(msg)
def tool_run_logging_kwargs(self) -> builtins.dict:
"""Return logging kwargs for tool run."""
@@ -1130,10 +1135,11 @@ class AgentExecutor(Chain):
allowed_tools = agent.get_allowed_tools() # type: ignore[union-attr]
if allowed_tools is not None:
if set(allowed_tools) != set([tool.name for tool in tools]):
- raise ValueError(
+ msg = (
f"Allowed tools ({allowed_tools}) different than "
f"provided tools ({[tool.name for tool in tools]})"
)
+ raise ValueError(msg)
return self
@model_validator(mode="before")
@@ -1191,11 +1197,12 @@ class AgentExecutor(Chain):
Raises:
ValueError: Saving not supported for agent executors.
"""
- raise ValueError(
+ msg = (
"Saving not supported for agent executors. "
"If you are trying to save the agent, please use the "
"`.save_agent(...)`"
)
+ raise ValueError(msg)
def save_agent(self, file_path: Union[Path, str]) -> None:
"""Save the underlying agent.
@@ -1306,9 +1313,8 @@ class AgentExecutor(Chain):
) -> Union[AgentFinish, list[tuple[AgentAction, str]]]:
if isinstance(values[-1], AgentFinish):
if len(values) != 1:
- raise ValueError(
- "Expected a single AgentFinish output, but got multiple values."
- )
+ msg = "Expected a single AgentFinish output, but got multiple values."
+ raise ValueError(msg)
return values[-1]
else:
return [
@@ -1363,12 +1369,13 @@ class AgentExecutor(Chain):
else:
raise_error = False
if raise_error:
- raise ValueError(
+ msg = (
"An output parsing error occurred. "
"In order to pass this error back to the agent and have it try "
"again, pass `handle_parsing_errors=True` to the AgentExecutor. "
f"This is the error: {str(e)}"
)
+ raise ValueError(msg)
text = str(e)
if isinstance(self.handle_parsing_errors, bool):
if e.send_to_llm:
@@ -1381,7 +1388,8 @@ class AgentExecutor(Chain):
elif callable(self.handle_parsing_errors):
observation = self.handle_parsing_errors(e)
else:
- raise ValueError("Got unexpected type of `handle_parsing_errors`")
+ msg = "Got unexpected type of `handle_parsing_errors`"
+ raise ValueError(msg)
output = AgentAction("_Exception", observation, text)
if run_manager:
run_manager.on_agent_action(output, color="green")
@@ -1500,12 +1508,13 @@ class AgentExecutor(Chain):
else:
raise_error = False
if raise_error:
- raise ValueError(
+ msg = (
"An output parsing error occurred. "
"In order to pass this error back to the agent and have it try "
"again, pass `handle_parsing_errors=True` to the AgentExecutor. "
f"This is the error: {str(e)}"
)
+ raise ValueError(msg)
text = str(e)
if isinstance(self.handle_parsing_errors, bool):
if e.send_to_llm:
@@ -1518,7 +1527,8 @@ class AgentExecutor(Chain):
elif callable(self.handle_parsing_errors):
observation = self.handle_parsing_errors(e)
else:
- raise ValueError("Got unexpected type of `handle_parsing_errors`")
+ msg = "Got unexpected type of `handle_parsing_errors`"
+ raise ValueError(msg)
output = AgentAction("_Exception", observation, text)
tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()
observation = await ExceptionTool().arun(
diff --git a/libs/langchain/langchain/agents/agent_toolkits/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/__init__.py
index 6e5c299380..3c8d3062ac 100644
--- a/libs/langchain/langchain/agents/agent_toolkits/__init__.py
+++ b/libs/langchain/langchain/agents/agent_toolkits/__init__.py
@@ -121,12 +121,13 @@ def __getattr__(name: str) -> Any:
relative_path = as_import_path(Path(__file__).parent, suffix=name)
old_path = "langchain." + relative_path
new_path = "langchain_experimental." + relative_path
- raise ImportError(
+ msg = (
f"{name} has been moved to langchain experimental. "
"See https://github.com/langchain-ai/langchain/discussions/11680"
"for more information.\n"
f"Please update your import statement from: `{old_path}` to `{new_path}`."
)
+ raise ImportError(msg)
return _import_attribute(name)
diff --git a/libs/langchain/langchain/agents/agent_toolkits/csv/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/csv/__init__.py
index 4b04980288..82c49e246a 100644
--- a/libs/langchain/langchain/agents/agent_toolkits/csv/__init__.py
+++ b/libs/langchain/langchain/agents/agent_toolkits/csv/__init__.py
@@ -14,7 +14,7 @@ def __getattr__(name: str) -> Any:
old_path = "langchain." + here + "." + name
new_path = "langchain_experimental." + here + "." + name
- raise ImportError(
+ msg = (
"This agent has been moved to langchain experiment. "
"This agent relies on python REPL tool under the hood, so to use it "
"safely please sandbox the python REPL. "
@@ -23,4 +23,6 @@ def __getattr__(name: str) -> Any:
"To keep using this code as is, install langchain experimental and "
f"update your import statement from:\n `{old_path}` to `{new_path}`."
)
- raise AttributeError(f"{name} does not exist")
+ raise ImportError(msg)
+ msg = f"{name} does not exist"
+ raise AttributeError(msg)
diff --git a/libs/langchain/langchain/agents/agent_toolkits/pandas/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/pandas/__init__.py
index a5cc6fc666..edb90f5a7c 100644
--- a/libs/langchain/langchain/agents/agent_toolkits/pandas/__init__.py
+++ b/libs/langchain/langchain/agents/agent_toolkits/pandas/__init__.py
@@ -14,7 +14,7 @@ def __getattr__(name: str) -> Any:
old_path = "langchain." + here + "." + name
new_path = "langchain_experimental." + here + "." + name
- raise ImportError(
+ msg = (
"This agent has been moved to langchain experiment. "
"This agent relies on python REPL tool under the hood, so to use it "
"safely please sandbox the python REPL. "
@@ -23,4 +23,6 @@ def __getattr__(name: str) -> Any:
"To keep using this code as is, install langchain experimental and "
f"update your import statement from:\n `{old_path}` to `{new_path}`."
)
- raise AttributeError(f"{name} does not exist")
+ raise ImportError(msg)
+ msg = f"{name} does not exist"
+ raise AttributeError(msg)
diff --git a/libs/langchain/langchain/agents/agent_toolkits/python/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/python/__init__.py
index 85d36eeb49..0ce36303ed 100644
--- a/libs/langchain/langchain/agents/agent_toolkits/python/__init__.py
+++ b/libs/langchain/langchain/agents/agent_toolkits/python/__init__.py
@@ -14,7 +14,7 @@ def __getattr__(name: str) -> Any:
old_path = "langchain." + here + "." + name
new_path = "langchain_experimental." + here + "." + name
- raise ImportError(
+ msg = (
"This agent has been moved to langchain experiment. "
"This agent relies on python REPL tool under the hood, so to use it "
"safely please sandbox the python REPL. "
@@ -23,4 +23,6 @@ def __getattr__(name: str) -> Any:
"To keep using this code as is, install langchain experimental and "
f"update your import statement from:\n `{old_path}` to `{new_path}`."
)
- raise AttributeError(f"{name} does not exist")
+ raise ImportError(msg)
+ msg = f"{name} does not exist"
+ raise AttributeError(msg)
diff --git a/libs/langchain/langchain/agents/agent_toolkits/spark/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/spark/__init__.py
index 73ec5b97de..76f96cc335 100644
--- a/libs/langchain/langchain/agents/agent_toolkits/spark/__init__.py
+++ b/libs/langchain/langchain/agents/agent_toolkits/spark/__init__.py
@@ -14,7 +14,7 @@ def __getattr__(name: str) -> Any:
old_path = "langchain." + here + "." + name
new_path = "langchain_experimental." + here + "." + name
- raise ImportError(
+ msg = (
"This agent has been moved to langchain experiment. "
"This agent relies on python REPL tool under the hood, so to use it "
"safely please sandbox the python REPL. "
@@ -23,4 +23,6 @@ def __getattr__(name: str) -> Any:
"To keep using this code as is, install langchain experimental and "
f"update your import statement from:\n `{old_path}` to `{new_path}`."
)
- raise AttributeError(f"{name} does not exist")
+ raise ImportError(msg)
+ msg = f"{name} does not exist"
+ raise AttributeError(msg)
diff --git a/libs/langchain/langchain/agents/agent_toolkits/vectorstore/toolkit.py b/libs/langchain/langchain/agents/agent_toolkits/vectorstore/toolkit.py
index 08c2c1a697..bcd9bdf31d 100644
--- a/libs/langchain/langchain/agents/agent_toolkits/vectorstore/toolkit.py
+++ b/libs/langchain/langchain/agents/agent_toolkits/vectorstore/toolkit.py
@@ -37,9 +37,8 @@ class VectorStoreToolkit(BaseToolkit):
VectorStoreQAWithSourcesTool,
)
except ImportError:
- raise ImportError(
- "You need to install langchain-community to use this toolkit."
- )
+ msg = "You need to install langchain-community to use this toolkit."
+ raise ImportError(msg)
description = VectorStoreQATool.get_description(
self.vectorstore_info.name, self.vectorstore_info.description
)
@@ -79,9 +78,8 @@ class VectorStoreRouterToolkit(BaseToolkit):
VectorStoreQATool,
)
except ImportError:
- raise ImportError(
- "You need to install langchain-community to use this toolkit."
- )
+ msg = "You need to install langchain-community to use this toolkit."
+ raise ImportError(msg)
for vectorstore_info in self.vectorstores:
description = VectorStoreQATool.get_description(
vectorstore_info.name, vectorstore_info.description
diff --git a/libs/langchain/langchain/agents/agent_toolkits/xorbits/__init__.py b/libs/langchain/langchain/agents/agent_toolkits/xorbits/__init__.py
index fd8fc13ba0..7f23f48262 100644
--- a/libs/langchain/langchain/agents/agent_toolkits/xorbits/__init__.py
+++ b/libs/langchain/langchain/agents/agent_toolkits/xorbits/__init__.py
@@ -14,7 +14,7 @@ def __getattr__(name: str) -> Any:
old_path = "langchain." + here + "." + name
new_path = "langchain_experimental." + here + "." + name
- raise ImportError(
+ msg = (
"This agent has been moved to langchain experiment. "
"This agent relies on python REPL tool under the hood, so to use it "
"safely please sandbox the python REPL. "
@@ -23,4 +23,6 @@ def __getattr__(name: str) -> Any:
"To keep using this code as is, install langchain experimental and "
f"update your import statement from:\n `{old_path}` to `{new_path}`."
)
- raise AttributeError(f"{name} does not exist")
+ raise ImportError(msg)
+ msg = f"{name} does not exist"
+ raise AttributeError(msg)
diff --git a/libs/langchain/langchain/agents/chat/base.py b/libs/langchain/langchain/agents/chat/base.py
index 19488b3b55..718b97603b 100644
--- a/libs/langchain/langchain/agents/chat/base.py
+++ b/libs/langchain/langchain/agents/chat/base.py
@@ -53,7 +53,8 @@ class ChatAgent(Agent):
) -> str:
agent_scratchpad = super()._construct_scratchpad(intermediate_steps)
if not isinstance(agent_scratchpad, str):
- raise ValueError("agent_scratchpad should be of type string.")
+ msg = "agent_scratchpad should be of type string."
+ raise ValueError(msg)
if agent_scratchpad:
return (
f"This was your previous work "
diff --git a/libs/langchain/langchain/agents/chat/output_parser.py b/libs/langchain/langchain/agents/chat/output_parser.py
index fd15a4aa2e..21066c6627 100644
--- a/libs/langchain/langchain/agents/chat/output_parser.py
+++ b/libs/langchain/langchain/agents/chat/output_parser.py
@@ -45,24 +45,25 @@ class ChatOutputParser(AgentOutputParser):
found = self.pattern.search(text)
if not found:
# Fast fail to parse Final Answer.
- raise ValueError("action not found")
+ msg = "action not found"
+ raise ValueError(msg)
action = found.group(1)
response = json.loads(action.strip())
includes_action = "action" in response
if includes_answer and includes_action:
- raise OutputParserException(
+ msg = (
"Parsing LLM output produced a final answer "
f"and a parse-able action: {text}"
)
+ raise OutputParserException(msg)
return AgentAction(
response["action"], response.get("action_input", {}), text
)
except Exception as exc:
if not includes_answer:
- raise OutputParserException(
- f"Could not parse LLM output: {text}"
- ) from exc
+ msg = f"Could not parse LLM output: {text}"
+ raise OutputParserException(msg) from exc
output = text.split(FINAL_ANSWER_ACTION)[-1].strip()
return AgentFinish({"output": output}, text)
diff --git a/libs/langchain/langchain/agents/conversational/output_parser.py b/libs/langchain/langchain/agents/conversational/output_parser.py
index dadcfabb16..82f098162a 100644
--- a/libs/langchain/langchain/agents/conversational/output_parser.py
+++ b/libs/langchain/langchain/agents/conversational/output_parser.py
@@ -39,7 +39,8 @@ class ConvoOutputParser(AgentOutputParser):
regex = r"Action: (.*?)[\n]*Action Input: ([\s\S]*)"
match = re.search(regex, text, re.DOTALL)
if not match:
- raise OutputParserException(f"Could not parse LLM output: `{text}`")
+ msg = f"Could not parse LLM output: `{text}`"
+ raise OutputParserException(msg)
action = match.group(1)
action_input = match.group(2)
return AgentAction(action.strip(), action_input.strip(" ").strip('"'), text)
diff --git a/libs/langchain/langchain/agents/conversational_chat/output_parser.py b/libs/langchain/langchain/agents/conversational_chat/output_parser.py
index daf317f2bb..d8192f7bed 100644
--- a/libs/langchain/langchain/agents/conversational_chat/output_parser.py
+++ b/libs/langchain/langchain/agents/conversational_chat/output_parser.py
@@ -46,13 +46,13 @@ class ConvoOutputParser(AgentOutputParser):
else:
# If the necessary keys aren't present in the response, raise an
# exception
- raise OutputParserException(
- f"Missing 'action' or 'action_input' in LLM output: {text}"
- )
+ msg = f"Missing 'action' or 'action_input' in LLM output: {text}"
+ raise OutputParserException(msg)
except Exception as e:
# If any other exception is raised during parsing, also raise an
# OutputParserException
- raise OutputParserException(f"Could not parse LLM output: {text}") from e
+ msg = f"Could not parse LLM output: {text}"
+ raise OutputParserException(msg) from e
@property
def _type(self) -> str:
diff --git a/libs/langchain/langchain/agents/initialize.py b/libs/langchain/langchain/agents/initialize.py
index 5816de5653..9490d7c9c3 100644
--- a/libs/langchain/langchain/agents/initialize.py
+++ b/libs/langchain/langchain/agents/initialize.py
@@ -59,16 +59,18 @@ def initialize_agent(
if agent is None and agent_path is None:
agent = AgentType.ZERO_SHOT_REACT_DESCRIPTION
if agent is not None and agent_path is not None:
- raise ValueError(
+ msg = (
"Both `agent` and `agent_path` are specified, "
"but at most only one should be."
)
+ raise ValueError(msg)
if agent is not None:
if agent not in AGENT_TO_CLASS:
- raise ValueError(
+ msg = (
f"Got unknown agent type: {agent}. "
f"Valid types are: {AGENT_TO_CLASS.keys()}."
)
+ raise ValueError(msg)
tags_.append(agent.value if isinstance(agent, AgentType) else agent)
agent_cls = AGENT_TO_CLASS[agent]
agent_kwargs = agent_kwargs or {}
@@ -85,9 +87,10 @@ def initialize_agent(
except NotImplementedError:
pass
else:
- raise ValueError(
+ msg = (
"Somehow both `agent` and `agent_path` are None, this should never happen."
)
+ raise ValueError(msg)
return AgentExecutor.from_agent_and_tools(
agent=agent_obj,
tools=tools,
diff --git a/libs/langchain/langchain/agents/json_chat/base.py b/libs/langchain/langchain/agents/json_chat/base.py
index cc56676b44..6c61f13357 100644
--- a/libs/langchain/langchain/agents/json_chat/base.py
+++ b/libs/langchain/langchain/agents/json_chat/base.py
@@ -165,12 +165,12 @@ def create_json_chat_agent(
prompt.input_variables + list(prompt.partial_variables)
)
if missing_vars:
- raise ValueError(f"Prompt missing required variables: {missing_vars}")
+ msg = f"Prompt missing required variables: {missing_vars}"
+ raise ValueError(msg)
if "{observation}" not in template_tool_response:
- raise ValueError(
- "Template tool response missing required variable 'observation'"
- )
+ msg = "Template tool response missing required variable 'observation'"
+ raise ValueError(msg)
prompt = prompt.partial(
tools=tools_renderer(list(tools)),
diff --git a/libs/langchain/langchain/agents/loading.py b/libs/langchain/langchain/agents/loading.py
index 08fc6fa878..34369cc0fb 100644
--- a/libs/langchain/langchain/agents/loading.py
+++ b/libs/langchain/langchain/agents/loading.py
@@ -24,7 +24,8 @@ def _load_agent_from_tools(
) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]:
config_type = config.pop("_type")
if config_type not in AGENT_TO_CLASS:
- raise ValueError(f"Loading {config_type} agent not supported")
+ msg = f"Loading {config_type} agent not supported"
+ raise ValueError(msg)
agent_cls = AGENT_TO_CLASS[config_type]
combined_config = {**config, **kwargs}
@@ -53,23 +54,27 @@ def load_agent_from_config(
ValueError: If agent type is not specified in the config.
"""
if "_type" not in config:
- raise ValueError("Must specify an agent Type in config")
+ msg = "Must specify an agent Type in config"
+ raise ValueError(msg)
load_from_tools = config.pop("load_from_llm_and_tools", False)
if load_from_tools:
if llm is None:
- raise ValueError(
+ msg = (
"If `load_from_llm_and_tools` is set to True, then LLM must be provided"
)
+ raise ValueError(msg)
if tools is None:
- raise ValueError(
+ msg = (
"If `load_from_llm_and_tools` is set to True, "
"then tools must be provided"
)
+ raise ValueError(msg)
return _load_agent_from_tools(config, llm, tools, **kwargs)
config_type = config.pop("_type")
if config_type not in AGENT_TO_CLASS:
- raise ValueError(f"Loading {config_type} agent not supported")
+ msg = f"Loading {config_type} agent not supported"
+ raise ValueError(msg)
agent_cls = AGENT_TO_CLASS[config_type]
if "llm_chain" in config:
@@ -77,7 +82,8 @@ def load_agent_from_config(
elif "llm_chain_path" in config:
config["llm_chain"] = load_chain(config.pop("llm_chain_path"))
else:
- raise ValueError("One of `llm_chain` and `llm_chain_path` should be specified.")
+ msg = "One of `llm_chain` and `llm_chain_path` should be specified."
+ raise ValueError(msg)
if "output_parser" in config:
logger.warning(
"Currently loading output parsers on agent is not supported, "
@@ -107,11 +113,12 @@ def load_agent(
Hub is attempted.
"""
if isinstance(path, str) and path.startswith("lc://"):
- raise RuntimeError(
+ msg = (
"Loading from the deprecated github-based Hub is no longer supported. "
"Please use the new LangChain Hub at https://smith.langchain.com/hub "
"instead."
)
+ raise RuntimeError(msg)
return _load_agent_from_file(path, **kwargs)
@@ -133,6 +140,7 @@ def _load_agent_from_file(
with open(file_path) as f:
config = yaml.safe_load(f)
else:
- raise ValueError(f"Unsupported file type, must be one of {valid_suffixes}.")
+ msg = f"Unsupported file type, must be one of {valid_suffixes}."
+ raise ValueError(msg)
# Load the agent from the config now.
return load_agent_from_config(config, **kwargs)
diff --git a/libs/langchain/langchain/agents/mrkl/base.py b/libs/langchain/langchain/agents/mrkl/base.py
index 727ca66b39..7e76b4caf5 100644
--- a/libs/langchain/langchain/agents/mrkl/base.py
+++ b/libs/langchain/langchain/agents/mrkl/base.py
@@ -162,15 +162,17 @@ class ZeroShotAgent(Agent):
def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
validate_tools_single_input(cls.__name__, tools)
if len(tools) == 0:
- raise ValueError(
+ msg = (
f"Got no tools for {cls.__name__}. At least one tool must be provided."
)
+ raise ValueError(msg)
for tool in tools:
if tool.description is None:
- raise ValueError(
+ msg = (
f"Got a tool {tool.name} without a description. For this agent, "
f"a description must always be provided."
)
+ raise ValueError(msg)
super()._validate_tools(tools)
diff --git a/libs/langchain/langchain/agents/mrkl/output_parser.py b/libs/langchain/langchain/agents/mrkl/output_parser.py
index 54d04817ae..d9390c698d 100644
--- a/libs/langchain/langchain/agents/mrkl/output_parser.py
+++ b/libs/langchain/langchain/agents/mrkl/output_parser.py
@@ -56,9 +56,8 @@ class MRKLOutputParser(AgentOutputParser):
{"output": text[start_index:end_index].strip()}, text[:end_index]
)
else:
- raise OutputParserException(
- f"{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: {text}"
- )
+ msg = f"{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: {text}"
+ raise OutputParserException(msg)
if action_match:
action = action_match.group(1).strip()
@@ -76,8 +75,9 @@ class MRKLOutputParser(AgentOutputParser):
)
if not re.search(r"Action\s*\d*\s*:[\s]*(.*?)", text, re.DOTALL):
+ msg = f"Could not parse LLM output: `{text}`"
raise OutputParserException(
- f"Could not parse LLM output: `{text}`",
+ msg,
observation=MISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE,
llm_output=text,
send_to_llm=True,
@@ -85,14 +85,16 @@ class MRKLOutputParser(AgentOutputParser):
elif not re.search(
r"[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)", text, re.DOTALL
):
+ msg = f"Could not parse LLM output: `{text}`"
raise OutputParserException(
- f"Could not parse LLM output: `{text}`",
+ msg,
observation=MISSING_ACTION_INPUT_AFTER_ACTION_ERROR_MESSAGE,
llm_output=text,
send_to_llm=True,
)
else:
- raise OutputParserException(f"Could not parse LLM output: `{text}`")
+ msg = f"Could not parse LLM output: `{text}`"
+ raise OutputParserException(msg)
@property
def _type(self) -> str:
diff --git a/libs/langchain/langchain/agents/openai_assistant/base.py b/libs/langchain/langchain/agents/openai_assistant/base.py
index 5ca00c3c68..44550912dd 100644
--- a/libs/langchain/langchain/agents/openai_assistant/base.py
+++ b/libs/langchain/langchain/agents/openai_assistant/base.py
@@ -80,14 +80,14 @@ def _get_openai_client() -> openai.OpenAI:
return openai.OpenAI()
except ImportError as e:
- raise ImportError(
- "Unable to import openai, please install with `pip install openai`."
- ) from e
+ msg = "Unable to import openai, please install with `pip install openai`."
+ raise ImportError(msg) from e
except AttributeError as e:
- raise AttributeError(
+ msg = (
"Please make sure you are using a v1.1-compatible version of openai. You "
'can install with `pip install "openai>=1.1"`.'
- ) from e
+ )
+ raise AttributeError(msg) from e
def _get_openai_async_client() -> openai.AsyncOpenAI:
@@ -96,14 +96,14 @@ def _get_openai_async_client() -> openai.AsyncOpenAI:
return openai.AsyncOpenAI()
except ImportError as e:
- raise ImportError(
- "Unable to import openai, please install with `pip install openai`."
- ) from e
+ msg = "Unable to import openai, please install with `pip install openai`."
+ raise ImportError(msg) from e
except AttributeError as e:
- raise AttributeError(
+ msg = (
"Please make sure you are using a v1.1-compatible version of openai. You "
'can install with `pip install "openai>=1.1"`.'
- ) from e
+ )
+ raise AttributeError(msg) from e
def _is_assistants_builtin_tool(
@@ -619,10 +619,11 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
try:
args = json.loads(function.arguments, strict=False)
except JSONDecodeError as e:
- raise ValueError(
+ msg = (
f"Received invalid JSON function arguments: "
f"{function.arguments} for function {function.name}"
- ) from e
+ )
+ raise ValueError(msg) from e
if len(args) == 1 and "__arg1" in args:
args = args["__arg1"]
actions.append(
@@ -638,9 +639,8 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
return actions
else:
run_info = json.dumps(run.dict(), indent=2)
- raise ValueError(
- f"Unexpected run status: {run.status}. Full run info:\n\n{run_info})"
- )
+ msg = f"Unexpected run status: {run.status}. Full run info:\n\n{run_info})"
+ raise ValueError(msg)
def _wait_for_run(self, run_id: str, thread_id: str) -> Any:
in_progress = True
@@ -773,10 +773,11 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
try:
args = json.loads(function.arguments, strict=False)
except JSONDecodeError as e:
- raise ValueError(
+ msg = (
f"Received invalid JSON function arguments: "
f"{function.arguments} for function {function.name}"
- ) from e
+ )
+ raise ValueError(msg) from e
if len(args) == 1 and "__arg1" in args:
args = args["__arg1"]
actions.append(
@@ -792,9 +793,8 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
return actions
else:
run_info = json.dumps(run.dict(), indent=2)
- raise ValueError(
- f"Unexpected run status: {run.status}. Full run info:\n\n{run_info})"
- )
+ msg = f"Unexpected run status: {run.status}. Full run info:\n\n{run_info})"
+ raise ValueError(msg)
async def _await_for_run(self, run_id: str, thread_id: str) -> Any:
in_progress = True
diff --git a/libs/langchain/langchain/agents/openai_functions_agent/base.py b/libs/langchain/langchain/agents/openai_functions_agent/base.py
index 10111aa3a4..f277bd9337 100644
--- a/libs/langchain/langchain/agents/openai_functions_agent/base.py
+++ b/libs/langchain/langchain/agents/openai_functions_agent/base.py
@@ -75,10 +75,11 @@ class OpenAIFunctionsAgent(BaseSingleActionAgent):
"""
prompt: BasePromptTemplate = self.prompt
if "agent_scratchpad" not in prompt.input_variables:
- raise ValueError(
+ msg = (
"`agent_scratchpad` should be one of the variables in the prompt, "
f"got {prompt.input_variables}"
)
+ raise ValueError(msg)
return self
@property
@@ -199,14 +200,14 @@ class OpenAIFunctionsAgent(BaseSingleActionAgent):
if isinstance(agent_decision, AgentFinish):
return agent_decision
else:
- raise ValueError(
- f"got AgentAction with no functions provided: {agent_decision}"
- )
+ msg = f"got AgentAction with no functions provided: {agent_decision}"
+ raise ValueError(msg)
else:
- raise ValueError(
+ msg = (
"early_stopping_method should be one of `force` or `generate`, "
f"got {early_stopping_method}"
)
+ raise ValueError(msg)
@classmethod
def create_prompt(
@@ -354,10 +355,11 @@ def create_openai_functions_agent(
if "agent_scratchpad" not in (
prompt.input_variables + list(prompt.partial_variables)
):
- raise ValueError(
+ msg = (
"Prompt must have input variable `agent_scratchpad`, but wasn't found. "
f"Found {prompt.input_variables} instead."
)
+ raise ValueError(msg)
llm_with_tools = llm.bind(functions=[convert_to_openai_function(t) for t in tools])
agent = (
RunnablePassthrough.assign(
diff --git a/libs/langchain/langchain/agents/openai_functions_multi_agent/base.py b/libs/langchain/langchain/agents/openai_functions_multi_agent/base.py
index 5f243a094b..cc26a25f07 100644
--- a/libs/langchain/langchain/agents/openai_functions_multi_agent/base.py
+++ b/libs/langchain/langchain/agents/openai_functions_multi_agent/base.py
@@ -38,7 +38,8 @@ _FunctionsAgentAction = AgentActionMessageLog
def _parse_ai_message(message: BaseMessage) -> Union[list[AgentAction], AgentFinish]:
"""Parse an AI message."""
if not isinstance(message, AIMessage):
- raise TypeError(f"Expected an AI message got {type(message)}")
+ msg = f"Expected an AI message got {type(message)}"
+ raise TypeError(msg)
function_call = message.additional_kwargs.get("function_call", {})
@@ -46,18 +47,20 @@ def _parse_ai_message(message: BaseMessage) -> Union[list[AgentAction], AgentFin
try:
arguments = json.loads(function_call["arguments"], strict=False)
except JSONDecodeError:
- raise OutputParserException(
+ msg = (
f"Could not parse tool input: {function_call} because "
f"the `arguments` is not valid JSON."
)
+ raise OutputParserException(msg)
try:
tools = arguments["actions"]
except (TypeError, KeyError):
- raise OutputParserException(
+ msg = (
f"Could not parse tool input: {function_call} because "
f"the `arguments` JSON does not contain `actions` key."
)
+ raise OutputParserException(msg)
final_tools: list[AgentAction] = []
for tool_schema in tools:
@@ -121,10 +124,11 @@ class OpenAIMultiFunctionsAgent(BaseMultiActionAgent):
def validate_prompt(self) -> Self:
prompt: BasePromptTemplate = self.prompt
if "agent_scratchpad" not in prompt.input_variables:
- raise ValueError(
+ msg = (
"`agent_scratchpad` should be one of the variables in the prompt, "
f"got {prompt.input_variables}"
)
+ raise ValueError(msg)
return self
@property
diff --git a/libs/langchain/langchain/agents/openai_tools/base.py b/libs/langchain/langchain/agents/openai_tools/base.py
index fda07b33cb..6e53662aec 100644
--- a/libs/langchain/langchain/agents/openai_tools/base.py
+++ b/libs/langchain/langchain/agents/openai_tools/base.py
@@ -89,7 +89,8 @@ def create_openai_tools_agent(
prompt.input_variables + list(prompt.partial_variables)
)
if missing_vars:
- raise ValueError(f"Prompt missing required variables: {missing_vars}")
+ msg = f"Prompt missing required variables: {missing_vars}"
+ raise ValueError(msg)
llm_with_tools = llm.bind(
tools=[convert_to_openai_tool(tool, strict=strict) for tool in tools]
diff --git a/libs/langchain/langchain/agents/output_parsers/json.py b/libs/langchain/langchain/agents/output_parsers/json.py
index 9ef067d0d4..cca8f1c505 100644
--- a/libs/langchain/langchain/agents/output_parsers/json.py
+++ b/libs/langchain/langchain/agents/output_parsers/json.py
@@ -55,7 +55,8 @@ class JSONAgentOutputParser(AgentOutputParser):
action_input = {}
return AgentAction(response["action"], action_input, text)
except Exception as e:
- raise OutputParserException(f"Could not parse LLM output: {text}") from e
+ msg = f"Could not parse LLM output: {text}"
+ raise OutputParserException(msg) from e
@property
def _type(self) -> str:
diff --git a/libs/langchain/langchain/agents/output_parsers/openai_functions.py b/libs/langchain/langchain/agents/output_parsers/openai_functions.py
index 67a6423db9..26af5ddd96 100644
--- a/libs/langchain/langchain/agents/output_parsers/openai_functions.py
+++ b/libs/langchain/langchain/agents/output_parsers/openai_functions.py
@@ -33,7 +33,8 @@ class OpenAIFunctionsAgentOutputParser(AgentOutputParser):
def _parse_ai_message(message: BaseMessage) -> Union[AgentAction, AgentFinish]:
"""Parse an AI message."""
if not isinstance(message, AIMessage):
- raise TypeError(f"Expected an AI message got {type(message)}")
+ msg = f"Expected an AI message got {type(message)}"
+ raise TypeError(msg)
function_call = message.additional_kwargs.get("function_call", {})
@@ -47,10 +48,11 @@ class OpenAIFunctionsAgentOutputParser(AgentOutputParser):
# otherwise it returns a json object
_tool_input = json.loads(function_call["arguments"], strict=False)
except JSONDecodeError:
- raise OutputParserException(
+ msg = (
f"Could not parse tool input: {function_call} because "
f"the `arguments` is not valid JSON."
)
+ raise OutputParserException(msg)
# HACK HACK HACK:
# The code that encodes tool input into Open AI uses a special variable
@@ -80,9 +82,11 @@ class OpenAIFunctionsAgentOutputParser(AgentOutputParser):
self, result: list[Generation], *, partial: bool = False
) -> Union[AgentAction, AgentFinish]:
if not isinstance(result[0], ChatGeneration):
- raise ValueError("This output parser only works on ChatGeneration output")
+ msg = "This output parser only works on ChatGeneration output"
+ raise ValueError(msg)
message = result[0].message
return self._parse_ai_message(message)
def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
- raise ValueError("Can only parse messages")
+ msg = "Can only parse messages"
+ raise ValueError(msg)
diff --git a/libs/langchain/langchain/agents/output_parsers/openai_tools.py b/libs/langchain/langchain/agents/output_parsers/openai_tools.py
index 2c58084276..42899aca57 100644
--- a/libs/langchain/langchain/agents/output_parsers/openai_tools.py
+++ b/libs/langchain/langchain/agents/output_parsers/openai_tools.py
@@ -57,9 +57,11 @@ class OpenAIToolsAgentOutputParser(MultiActionAgentOutputParser):
self, result: list[Generation], *, partial: bool = False
) -> Union[list[AgentAction], AgentFinish]:
if not isinstance(result[0], ChatGeneration):
- raise ValueError("This output parser only works on ChatGeneration output")
+ msg = "This output parser only works on ChatGeneration output"
+ raise ValueError(msg)
message = result[0].message
return parse_ai_message_to_openai_tool_action(message)
def parse(self, text: str) -> Union[list[AgentAction], AgentFinish]:
- raise ValueError("Can only parse messages")
+ msg = "Can only parse messages"
+ raise ValueError(msg)
diff --git a/libs/langchain/langchain/agents/output_parsers/react_json_single_input.py b/libs/langchain/langchain/agents/output_parsers/react_json_single_input.py
index 75a473c66d..248852cebc 100644
--- a/libs/langchain/langchain/agents/output_parsers/react_json_single_input.py
+++ b/libs/langchain/langchain/agents/output_parsers/react_json_single_input.py
@@ -55,22 +55,25 @@ class ReActJsonSingleInputOutputParser(AgentOutputParser):
found = self.pattern.search(text)
if not found:
# Fast fail to parse Final Answer.
- raise ValueError("action not found")
+ msg = "action not found"
+ raise ValueError(msg)
action = found.group(1)
response = json.loads(action.strip())
includes_action = "action" in response
if includes_answer and includes_action:
- raise OutputParserException(
+ msg = (
"Parsing LLM output produced a final answer "
f"and a parse-able action: {text}"
)
+ raise OutputParserException(msg)
return AgentAction(
response["action"], response.get("action_input", {}), text
)
except Exception:
if not includes_answer:
- raise OutputParserException(f"Could not parse LLM output: {text}")
+ msg = f"Could not parse LLM output: {text}"
+ raise OutputParserException(msg)
output = text.split(FINAL_ANSWER_ACTION)[-1].strip()
return AgentFinish({"output": output}, text)
diff --git a/libs/langchain/langchain/agents/output_parsers/react_single_input.py b/libs/langchain/langchain/agents/output_parsers/react_single_input.py
index b853cb04aa..d87aedfa11 100644
--- a/libs/langchain/langchain/agents/output_parsers/react_single_input.py
+++ b/libs/langchain/langchain/agents/output_parsers/react_single_input.py
@@ -56,9 +56,8 @@ class ReActSingleInputOutputParser(AgentOutputParser):
action_match = re.search(regex, text, re.DOTALL)
if action_match:
if includes_answer:
- raise OutputParserException(
- f"{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: {text}"
- )
+ msg = f"{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: {text}"
+ raise OutputParserException(msg)
action = action_match.group(1).strip()
action_input = action_match.group(2)
tool_input = action_input.strip(" ")
@@ -72,8 +71,9 @@ class ReActSingleInputOutputParser(AgentOutputParser):
)
if not re.search(r"Action\s*\d*\s*:[\s]*(.*?)", text, re.DOTALL):
+ msg = f"Could not parse LLM output: `{text}`"
raise OutputParserException(
- f"Could not parse LLM output: `{text}`",
+ msg,
observation=MISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE,
llm_output=text,
send_to_llm=True,
@@ -81,14 +81,16 @@ class ReActSingleInputOutputParser(AgentOutputParser):
elif not re.search(
r"[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)", text, re.DOTALL
):
+ msg = f"Could not parse LLM output: `{text}`"
raise OutputParserException(
- f"Could not parse LLM output: `{text}`",
+ msg,
observation=MISSING_ACTION_INPUT_AFTER_ACTION_ERROR_MESSAGE,
llm_output=text,
send_to_llm=True,
)
else:
- raise OutputParserException(f"Could not parse LLM output: `{text}`")
+ msg = f"Could not parse LLM output: `{text}`"
+ raise OutputParserException(msg)
@property
def _type(self) -> str:
diff --git a/libs/langchain/langchain/agents/output_parsers/self_ask.py b/libs/langchain/langchain/agents/output_parsers/self_ask.py
index 05ecafe80d..a6fa69fb75 100644
--- a/libs/langchain/langchain/agents/output_parsers/self_ask.py
+++ b/libs/langchain/langchain/agents/output_parsers/self_ask.py
@@ -39,7 +39,8 @@ class SelfAskOutputParser(AgentOutputParser):
last_line = text.split("\n")[-1]
if not any([follow in last_line for follow in self.followups]):
if self.finish_string not in last_line:
- raise OutputParserException(f"Could not parse output: {text}")
+ msg = f"Could not parse output: {text}"
+ raise OutputParserException(msg)
return AgentFinish({"output": last_line[len(self.finish_string) :]}, text)
after_colon = text.split(":")[-1].strip()
diff --git a/libs/langchain/langchain/agents/output_parsers/tools.py b/libs/langchain/langchain/agents/output_parsers/tools.py
index b7d28e69bd..ecf912e838 100644
--- a/libs/langchain/langchain/agents/output_parsers/tools.py
+++ b/libs/langchain/langchain/agents/output_parsers/tools.py
@@ -24,7 +24,8 @@ def parse_ai_message_to_tool_action(
) -> Union[list[AgentAction], AgentFinish]:
"""Parse an AI message potentially containing tool_calls."""
if not isinstance(message, AIMessage):
- raise TypeError(f"Expected an AI message got {type(message)}")
+ msg = f"Expected an AI message got {type(message)}"
+ raise TypeError(msg)
actions: list = []
if message.tool_calls:
@@ -45,10 +46,11 @@ def parse_ai_message_to_tool_action(
ToolCall(name=function_name, args=args, id=tool_call["id"])
)
except JSONDecodeError:
- raise OutputParserException(
+ msg = (
f"Could not parse tool input: {function} because "
f"the `arguments` is not valid JSON."
)
+ raise OutputParserException(msg)
for tool_call in tool_calls:
# HACK HACK HACK:
# The code that encodes tool input into Open AI uses a special variable
@@ -94,9 +96,11 @@ class ToolsAgentOutputParser(MultiActionAgentOutputParser):
self, result: list[Generation], *, partial: bool = False
) -> Union[list[AgentAction], AgentFinish]:
if not isinstance(result[0], ChatGeneration):
- raise ValueError("This output parser only works on ChatGeneration output")
+ msg = "This output parser only works on ChatGeneration output"
+ raise ValueError(msg)
message = result[0].message
return parse_ai_message_to_tool_action(message)
def parse(self, text: str) -> Union[list[AgentAction], AgentFinish]:
- raise ValueError("Can only parse messages")
+ msg = "Can only parse messages"
+ raise ValueError(msg)
diff --git a/libs/langchain/langchain/agents/react/agent.py b/libs/langchain/langchain/agents/react/agent.py
index 4c4e775919..a19b821fda 100644
--- a/libs/langchain/langchain/agents/react/agent.py
+++ b/libs/langchain/langchain/agents/react/agent.py
@@ -121,7 +121,8 @@ def create_react_agent(
prompt.input_variables + list(prompt.partial_variables)
)
if missing_vars:
- raise ValueError(f"Prompt missing required variables: {missing_vars}")
+ msg = f"Prompt missing required variables: {missing_vars}"
+ raise ValueError(msg)
prompt = prompt.partial(
tools=tools_renderer(list(tools)),
diff --git a/libs/langchain/langchain/agents/react/base.py b/libs/langchain/langchain/agents/react/base.py
index 8b0d191d6e..c3c55206f6 100644
--- a/libs/langchain/langchain/agents/react/base.py
+++ b/libs/langchain/langchain/agents/react/base.py
@@ -53,12 +53,12 @@ class ReActDocstoreAgent(Agent):
validate_tools_single_input(cls.__name__, tools)
super()._validate_tools(tools)
if len(tools) != 2:
- raise ValueError(f"Exactly two tools must be specified, but got {tools}")
+ msg = f"Exactly two tools must be specified, but got {tools}"
+ raise ValueError(msg)
tool_names = {tool.name for tool in tools}
if tool_names != {"Lookup", "Search"}:
- raise ValueError(
- f"Tool names should be Lookup and Search, got {tool_names}"
- )
+ msg = f"Tool names should be Lookup and Search, got {tool_names}"
+ raise ValueError(msg)
@property
def observation_prefix(self) -> str:
@@ -103,7 +103,8 @@ class DocstoreExplorer:
def lookup(self, term: str) -> str:
"""Lookup a term in document (if saved)."""
if self.document is None:
- raise ValueError("Cannot lookup without a successful search first")
+ msg = "Cannot lookup without a successful search first"
+ raise ValueError(msg)
if term.lower() != self.lookup_str:
self.lookup_str = term.lower()
self.lookup_index = 0
@@ -125,7 +126,8 @@ class DocstoreExplorer:
@property
def _paragraphs(self) -> list[str]:
if self.document is None:
- raise ValueError("Cannot get paragraphs without a document")
+ msg = "Cannot get paragraphs without a document"
+ raise ValueError(msg)
return self.document.page_content.split("\n\n")
@@ -147,10 +149,12 @@ class ReActTextWorldAgent(ReActDocstoreAgent):
validate_tools_single_input(cls.__name__, tools)
super()._validate_tools(tools)
if len(tools) != 1:
- raise ValueError(f"Exactly one tool must be specified, but got {tools}")
+ msg = f"Exactly one tool must be specified, but got {tools}"
+ raise ValueError(msg)
tool_names = {tool.name for tool in tools}
if tool_names != {"Play"}:
- raise ValueError(f"Tool name should be Play, got {tool_names}")
+ msg = f"Tool name should be Play, got {tool_names}"
+ raise ValueError(msg)
@deprecated(
diff --git a/libs/langchain/langchain/agents/react/output_parser.py b/libs/langchain/langchain/agents/react/output_parser.py
index ce3161d630..a632f22527 100644
--- a/libs/langchain/langchain/agents/react/output_parser.py
+++ b/libs/langchain/langchain/agents/react/output_parser.py
@@ -13,16 +13,16 @@ class ReActOutputParser(AgentOutputParser):
def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
action_prefix = "Action: "
if not text.strip().split("\n")[-1].startswith(action_prefix):
- raise OutputParserException(f"Could not parse LLM Output: {text}")
+ msg = f"Could not parse LLM Output: {text}"
+ raise OutputParserException(msg)
action_block = text.strip().split("\n")[-1]
action_str = action_block[len(action_prefix) :]
# Parse out the action and the directive.
re_matches = re.search(r"(.*?)\[(.*?)\]", action_str)
if re_matches is None:
- raise OutputParserException(
- f"Could not parse action directive: {action_str}"
- )
+ msg = f"Could not parse action directive: {action_str}"
+ raise OutputParserException(msg)
action, action_input = re_matches.group(1), re_matches.group(2)
if action == "Finish":
return AgentFinish({"output": action_input}, text)
diff --git a/libs/langchain/langchain/agents/self_ask_with_search/base.py b/libs/langchain/langchain/agents/self_ask_with_search/base.py
index 36d859f34f..a04414fb0e 100644
--- a/libs/langchain/langchain/agents/self_ask_with_search/base.py
+++ b/libs/langchain/langchain/agents/self_ask_with_search/base.py
@@ -50,12 +50,12 @@ class SelfAskWithSearchAgent(Agent):
validate_tools_single_input(cls.__name__, tools)
super()._validate_tools(tools)
if len(tools) != 1:
- raise ValueError(f"Exactly one tool must be specified, but got {tools}")
+ msg = f"Exactly one tool must be specified, but got {tools}"
+ raise ValueError(msg)
tool_names = {tool.name for tool in tools}
if tool_names != {"Intermediate Answer"}:
- raise ValueError(
- f"Tool name should be Intermediate Answer, got {tool_names}"
- )
+ msg = f"Tool name should be Intermediate Answer, got {tool_names}"
+ raise ValueError(msg)
@property
def observation_prefix(self) -> str:
@@ -183,15 +183,16 @@ def create_self_ask_with_search_agent(
prompt.input_variables + list(prompt.partial_variables)
)
if missing_vars:
- raise ValueError(f"Prompt missing required variables: {missing_vars}")
+ msg = f"Prompt missing required variables: {missing_vars}"
+ raise ValueError(msg)
if len(tools) != 1:
- raise ValueError("This agent expects exactly one tool")
+ msg = "This agent expects exactly one tool"
+ raise ValueError(msg)
tool = list(tools)[0]
if tool.name != "Intermediate Answer":
- raise ValueError(
- "This agent expects the tool to be named `Intermediate Answer`"
- )
+ msg = "This agent expects the tool to be named `Intermediate Answer`"
+ raise ValueError(msg)
llm_with_stop = llm.bind(stop=["\nIntermediate answer:"])
agent = (
diff --git a/libs/langchain/langchain/agents/structured_chat/base.py b/libs/langchain/langchain/agents/structured_chat/base.py
index 051cd6e04b..f333955338 100644
--- a/libs/langchain/langchain/agents/structured_chat/base.py
+++ b/libs/langchain/langchain/agents/structured_chat/base.py
@@ -54,7 +54,8 @@ class StructuredChatAgent(Agent):
) -> str:
agent_scratchpad = super()._construct_scratchpad(intermediate_steps)
if not isinstance(agent_scratchpad, str):
- raise ValueError("agent_scratchpad should be of type string.")
+ msg = "agent_scratchpad should be of type string."
+ raise ValueError(msg)
if agent_scratchpad:
return (
f"This was your previous work "
@@ -278,7 +279,8 @@ def create_structured_chat_agent(
prompt.input_variables + list(prompt.partial_variables)
)
if missing_vars:
- raise ValueError(f"Prompt missing required variables: {missing_vars}")
+ msg = f"Prompt missing required variables: {missing_vars}"
+ raise ValueError(msg)
prompt = prompt.partial(
tools=tools_renderer(list(tools)),
diff --git a/libs/langchain/langchain/agents/structured_chat/output_parser.py b/libs/langchain/langchain/agents/structured_chat/output_parser.py
index 9fc85fbc43..985ca6156e 100644
--- a/libs/langchain/langchain/agents/structured_chat/output_parser.py
+++ b/libs/langchain/langchain/agents/structured_chat/output_parser.py
@@ -49,7 +49,8 @@ class StructuredChatOutputParser(AgentOutputParser):
else:
return AgentFinish({"output": text}, text)
except Exception as e:
- raise OutputParserException(f"Could not parse LLM output: {text}") from e
+ msg = f"Could not parse LLM output: {text}"
+ raise OutputParserException(msg) from e
@property
def _type(self) -> str:
@@ -77,7 +78,8 @@ class StructuredChatOutputParserWithRetries(AgentOutputParser):
parsed_obj = self.base_parser.parse(text)
return parsed_obj
except Exception as e:
- raise OutputParserException(f"Could not parse LLM output: {text}") from e
+ msg = f"Could not parse LLM output: {text}"
+ raise OutputParserException(msg) from e
@classmethod
def from_llm(
diff --git a/libs/langchain/langchain/agents/tool_calling_agent/base.py b/libs/langchain/langchain/agents/tool_calling_agent/base.py
index 324ea84569..a7624f582a 100644
--- a/libs/langchain/langchain/agents/tool_calling_agent/base.py
+++ b/libs/langchain/langchain/agents/tool_calling_agent/base.py
@@ -90,11 +90,13 @@ def create_tool_calling_agent(
prompt.input_variables + list(prompt.partial_variables)
)
if missing_vars:
- raise ValueError(f"Prompt missing required variables: {missing_vars}")
+ msg = f"Prompt missing required variables: {missing_vars}"
+ raise ValueError(msg)
if not hasattr(llm, "bind_tools"):
+ msg = "This function requires a bind_tools() method be implemented on the LLM."
raise ValueError(
- "This function requires a .bind_tools method be implemented on the LLM.",
+ msg,
)
llm_with_tools = llm.bind_tools(tools)
diff --git a/libs/langchain/langchain/agents/utils.py b/libs/langchain/langchain/agents/utils.py
index f8db41b535..45544153ad 100644
--- a/libs/langchain/langchain/agents/utils.py
+++ b/libs/langchain/langchain/agents/utils.py
@@ -15,6 +15,5 @@ def validate_tools_single_input(class_name: str, tools: Sequence[BaseTool]) -> N
"""
for tool in tools:
if not tool.is_single_input:
- raise ValueError(
- f"{class_name} does not support multi-input tool {tool.name}."
- )
+ msg = f"{class_name} does not support multi-input tool {tool.name}."
+ raise ValueError(msg)
diff --git a/libs/langchain/langchain/agents/xml/base.py b/libs/langchain/langchain/agents/xml/base.py
index e91e99120f..e1658ba680 100644
--- a/libs/langchain/langchain/agents/xml/base.py
+++ b/libs/langchain/langchain/agents/xml/base.py
@@ -208,7 +208,8 @@ def create_xml_agent(
prompt.input_variables + list(prompt.partial_variables)
)
if missing_vars:
- raise ValueError(f"Prompt missing required variables: {missing_vars}")
+ msg = f"Prompt missing required variables: {missing_vars}"
+ raise ValueError(msg)
prompt = prompt.partial(
tools=tools_renderer(list(tools)),
diff --git a/libs/langchain/langchain/callbacks/streamlit/__init__.py b/libs/langchain/langchain/callbacks/streamlit/__init__.py
index 446ab9a27e..9f75611977 100644
--- a/libs/langchain/langchain/callbacks/streamlit/__init__.py
+++ b/libs/langchain/langchain/callbacks/streamlit/__init__.py
@@ -71,10 +71,11 @@ def StreamlitCallbackHandler(
StreamlitCallbackHandler as _InternalStreamlitCallbackHandler,
)
except ImportError:
- raise ImportError(
+ msg = (
"To use the StreamlitCallbackHandler, please install "
"langchain-community with `pip install langchain-community`."
)
+ raise ImportError(msg)
return _InternalStreamlitCallbackHandler(
parent_container,
diff --git a/libs/langchain/langchain/chains/api/base.py b/libs/langchain/langchain/chains/api/base.py
index 36d18b9ddc..8322cc6499 100644
--- a/libs/langchain/langchain/chains/api/base.py
+++ b/libs/langchain/langchain/chains/api/base.py
@@ -235,9 +235,8 @@ try:
input_vars = self.api_request_chain.prompt.input_variables
expected_vars = {"question", "api_docs"}
if set(input_vars) != expected_vars:
- raise ValueError(
- f"Input variables should be {expected_vars}, got {input_vars}"
- )
+ msg = f"Input variables should be {expected_vars}, got {input_vars}"
+ raise ValueError(msg)
return self
@model_validator(mode="before")
@@ -247,18 +246,20 @@ try:
# This check must be a pre=True check, so that a default of None
# won't be set to limit_to_domains if it's not provided.
if "limit_to_domains" not in values:
- raise ValueError(
+ msg = (
"You must specify a list of domains to limit access using "
"`limit_to_domains`"
)
+ raise ValueError(msg)
if (
not values["limit_to_domains"]
and values["limit_to_domains"] is not None
):
- raise ValueError(
+ msg = (
"Please provide a list of domains to limit access using "
"`limit_to_domains`."
)
+ raise ValueError(msg)
return values
@model_validator(mode="after")
@@ -267,9 +268,8 @@ try:
input_vars = self.api_answer_chain.prompt.input_variables
expected_vars = {"question", "api_docs", "api_url", "api_response"}
if set(input_vars) != expected_vars:
- raise ValueError(
- f"Input variables should be {expected_vars}, got {input_vars}"
- )
+ msg = f"Input variables should be {expected_vars}, got {input_vars}"
+ raise ValueError(msg)
return self
def _call(
@@ -289,9 +289,10 @@ try:
if self.limit_to_domains and not _check_in_allowed_domain(
api_url, self.limit_to_domains
):
- raise ValueError(
+ msg = (
f"{api_url} is not in the allowed domains: {self.limit_to_domains}"
)
+ raise ValueError(msg)
api_response = self.requests_wrapper.get(api_url)
_run_manager.on_text(
str(api_response), color="yellow", end="\n", verbose=self.verbose
@@ -326,9 +327,10 @@ try:
if self.limit_to_domains and not _check_in_allowed_domain(
api_url, self.limit_to_domains
):
- raise ValueError(
+ msg = (
f"{api_url} is not in the allowed domains: {self.limit_to_domains}"
)
+ raise ValueError(msg)
api_response = await self.requests_wrapper.aget(api_url)
await _run_manager.on_text(
str(api_response), color="yellow", end="\n", verbose=self.verbose
@@ -374,7 +376,8 @@ except ImportError:
class APIChain: # type: ignore[no-redef]
def __init__(self, *args: Any, **kwargs: Any) -> None:
- raise ImportError(
+ msg = (
"To use the APIChain, you must install the langchain_community package."
"pip install langchain_community"
)
+ raise ImportError(msg)
diff --git a/libs/langchain/langchain/chains/base.py b/libs/langchain/langchain/chains/base.py
index 8007587919..92a738bc45 100644
--- a/libs/langchain/langchain/chains/base.py
+++ b/libs/langchain/langchain/chains/base.py
@@ -224,7 +224,8 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
@property
def _chain_type(self) -> str:
- raise NotImplementedError("Saving not supported for this chain type.")
+ msg = "Saving not supported for this chain type."
+ raise NotImplementedError(msg)
@model_validator(mode="before")
@classmethod
@@ -232,11 +233,12 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
"""Raise deprecation warning if callback_manager is used."""
if values.get("callback_manager") is not None:
if values.get("callbacks") is not None:
- raise ValueError(
+ msg = (
"Cannot specify both callback_manager and callbacks. "
"callback_manager is deprecated, callbacks is the preferred "
"parameter to pass in."
)
+ raise ValueError(msg)
warnings.warn(
"callback_manager is deprecated. Please use callbacks instead.",
DeprecationWarning,
@@ -275,21 +277,24 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
# only one is not set, we can still figure out which key it is.
_input_keys = _input_keys.difference(self.memory.memory_variables)
if len(_input_keys) != 1:
- raise ValueError(
+ msg = (
f"A single string input was passed in, but this chain expects "
f"multiple inputs ({_input_keys}). When a chain expects "
f"multiple inputs, please call it by passing in a dictionary, "
"eg `chain({'foo': 1, 'bar': 2})`"
)
+ raise ValueError(msg)
missing_keys = set(self.input_keys).difference(inputs)
if missing_keys:
- raise ValueError(f"Missing some input keys: {missing_keys}")
+ msg = f"Missing some input keys: {missing_keys}"
+ raise ValueError(msg)
def _validate_outputs(self, outputs: dict[str, Any]) -> None:
missing_keys = set(self.output_keys).difference(outputs)
if missing_keys:
- raise ValueError(f"Missing some output keys: {missing_keys}")
+ msg = f"Missing some output keys: {missing_keys}"
+ raise ValueError(msg)
@abstractmethod
def _call(
@@ -543,10 +548,11 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
@property
def _run_output_key(self) -> str:
if len(self.output_keys) != 1:
- raise ValueError(
+ msg = (
f"`run` not supported when there is not exactly "
f"one output key. Got {self.output_keys}."
)
+ raise ValueError(msg)
return self.output_keys[0]
@deprecated("0.1.0", alternative="invoke", removal="1.0")
@@ -599,7 +605,8 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
if args and not kwargs:
if len(args) != 1:
- raise ValueError("`run` supports only one positional argument.")
+ msg = "`run` supports only one positional argument."
+ raise ValueError(msg)
return self(args[0], callbacks=callbacks, tags=tags, metadata=metadata)[
_output_key
]
@@ -610,15 +617,17 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
]
if not kwargs and not args:
- raise ValueError(
+ msg = (
"`run` supported with either positional arguments or keyword arguments,"
" but none were provided."
)
+ raise ValueError(msg)
else:
- raise ValueError(
+ msg = (
f"`run` supported with either positional arguments or keyword arguments"
f" but not both. Got args: {args} and kwargs: {kwargs}."
)
+ raise ValueError(msg)
@deprecated("0.1.0", alternative="ainvoke", removal="1.0")
async def arun(
@@ -667,13 +676,15 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
# -> "The temperature in Boise is..."
"""
if len(self.output_keys) != 1:
- raise ValueError(
+ msg = (
f"`run` not supported when there is not exactly "
f"one output key. Got {self.output_keys}."
)
+ raise ValueError(msg)
elif args and not kwargs:
if len(args) != 1:
- raise ValueError("`run` supports only one positional argument.")
+ msg = "`run` supports only one positional argument."
+ raise ValueError(msg)
return (
await self.acall(
args[0], callbacks=callbacks, tags=tags, metadata=metadata
@@ -687,10 +698,11 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
)
)[self.output_keys[0]]
- raise ValueError(
+ msg = (
f"`run` supported with either positional arguments or keyword arguments"
f" but not both. Got args: {args} and kwargs: {kwargs}."
)
+ raise ValueError(msg)
def dict(self, **kwargs: Any) -> dict:
"""Dictionary representation of chain.
@@ -733,12 +745,14 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
chain.save(file_path="path/chain.yaml")
"""
if self.memory is not None:
- raise ValueError("Saving of memory is not yet supported.")
+ msg = "Saving of memory is not yet supported."
+ raise ValueError(msg)
# Fetch dictionary to save
chain_dict = self.dict()
if "_type" not in chain_dict:
- raise NotImplementedError(f"Chain {self} does not support saving.")
+ msg = f"Chain {self} does not support saving."
+ raise NotImplementedError(msg)
# Convert file to Path object.
if isinstance(file_path, str):
@@ -756,7 +770,8 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
with open(file_path, "w") as f:
yaml.dump(chain_dict, f, default_flow_style=False)
else:
- raise ValueError(f"{save_path} must be json or yaml")
+ msg = f"{save_path} must be json or yaml"
+ raise ValueError(msg)
@deprecated("0.1.0", alternative="batch", removal="1.0")
def apply(
diff --git a/libs/langchain/langchain/chains/combine_documents/base.py b/libs/langchain/langchain/chains/combine_documents/base.py
index 5d7b68e763..76f1290a86 100644
--- a/libs/langchain/langchain/chains/combine_documents/base.py
+++ b/libs/langchain/langchain/chains/combine_documents/base.py
@@ -24,10 +24,11 @@ DEFAULT_DOCUMENT_PROMPT = PromptTemplate.from_template("{page_content}")
def _validate_prompt(prompt: BasePromptTemplate, document_variable_name: str) -> None:
if document_variable_name not in prompt.input_variables:
- raise ValueError(
+ msg = (
f"Prompt must accept {document_variable_name} as an input variable. "
f"Received prompt with input variables: {prompt.input_variables}"
)
+ raise ValueError(msg)
class BaseCombineDocumentsChain(Chain, ABC):
diff --git a/libs/langchain/langchain/chains/combine_documents/map_reduce.py b/libs/langchain/langchain/chains/combine_documents/map_reduce.py
index 166d5624f2..2c7c199ce0 100644
--- a/libs/langchain/langchain/chains/combine_documents/map_reduce.py
+++ b/libs/langchain/langchain/chains/combine_documents/map_reduce.py
@@ -147,11 +147,12 @@ class MapReduceDocumentsChain(BaseCombineDocumentsChain):
"""For backwards compatibility."""
if "combine_document_chain" in values:
if "reduce_documents_chain" in values:
- raise ValueError(
+ msg = (
"Both `reduce_documents_chain` and `combine_document_chain` "
"cannot be provided at the same time. `combine_document_chain` "
"is deprecated, please only provide `reduce_documents_chain`"
)
+ raise ValueError(msg)
combine_chain = values["combine_document_chain"]
collapse_chain = values.get("collapse_document_chain")
reduce_chain = ReduceDocumentsChain(
@@ -179,23 +180,26 @@ class MapReduceDocumentsChain(BaseCombineDocumentsChain):
def get_default_document_variable_name(cls, values: dict) -> Any:
"""Get default document variable name, if not provided."""
if "llm_chain" not in values:
- raise ValueError("llm_chain must be provided")
+ msg = "llm_chain must be provided"
+ raise ValueError(msg)
llm_chain_variables = values["llm_chain"].prompt.input_variables
if "document_variable_name" not in values:
if len(llm_chain_variables) == 1:
values["document_variable_name"] = llm_chain_variables[0]
else:
- raise ValueError(
+ msg = (
"document_variable_name must be provided if there are "
"multiple llm_chain input_variables"
)
+ raise ValueError(msg)
else:
if values["document_variable_name"] not in llm_chain_variables:
- raise ValueError(
+ msg = (
f"document_variable_name {values['document_variable_name']} was "
f"not found in llm_chain input_variables: {llm_chain_variables}"
)
+ raise ValueError(msg)
return values
@property
@@ -207,11 +211,12 @@ class MapReduceDocumentsChain(BaseCombineDocumentsChain):
else:
return self.reduce_documents_chain.combine_documents_chain
else:
- raise ValueError(
+ msg = (
f"`reduce_documents_chain` is of type "
f"{type(self.reduce_documents_chain)} so it does not have "
f"this attribute."
)
+ raise ValueError(msg)
@property
def combine_document_chain(self) -> BaseCombineDocumentsChain:
@@ -219,11 +224,12 @@ class MapReduceDocumentsChain(BaseCombineDocumentsChain):
if isinstance(self.reduce_documents_chain, ReduceDocumentsChain):
return self.reduce_documents_chain.combine_documents_chain
else:
- raise ValueError(
+ msg = (
f"`reduce_documents_chain` is of type "
f"{type(self.reduce_documents_chain)} so it does not have "
f"this attribute."
)
+ raise ValueError(msg)
def combine_docs(
self,
diff --git a/libs/langchain/langchain/chains/combine_documents/map_rerank.py b/libs/langchain/langchain/chains/combine_documents/map_rerank.py
index 8692f1ff99..3a08a95f5e 100644
--- a/libs/langchain/langchain/chains/combine_documents/map_rerank.py
+++ b/libs/langchain/langchain/chains/combine_documents/map_rerank.py
@@ -122,21 +122,24 @@ class MapRerankDocumentsChain(BaseCombineDocumentsChain):
"""Validate that the combine chain outputs a dictionary."""
output_parser = self.llm_chain.prompt.output_parser
if not isinstance(output_parser, RegexParser):
- raise ValueError(
+ msg = (
"Output parser of llm_chain should be a RegexParser,"
f" got {output_parser}"
)
+ raise ValueError(msg)
output_keys = output_parser.output_keys
if self.rank_key not in output_keys:
- raise ValueError(
+ msg = (
f"Got {self.rank_key} as key to rank on, but did not find "
f"it in the llm_chain output keys ({output_keys})"
)
+ raise ValueError(msg)
if self.answer_key not in output_keys:
- raise ValueError(
+ msg = (
f"Got {self.answer_key} as key to return, but did not find "
f"it in the llm_chain output keys ({output_keys})"
)
+ raise ValueError(msg)
return self
@model_validator(mode="before")
@@ -144,23 +147,26 @@ class MapRerankDocumentsChain(BaseCombineDocumentsChain):
def get_default_document_variable_name(cls, values: dict) -> Any:
"""Get default document variable name, if not provided."""
if "llm_chain" not in values:
- raise ValueError("llm_chain must be provided")
+ msg = "llm_chain must be provided"
+ raise ValueError(msg)
llm_chain_variables = values["llm_chain"].prompt.input_variables
if "document_variable_name" not in values:
if len(llm_chain_variables) == 1:
values["document_variable_name"] = llm_chain_variables[0]
else:
- raise ValueError(
+ msg = (
"document_variable_name must be provided if there are "
"multiple llm_chain input_variables"
)
+ raise ValueError(msg)
else:
if values["document_variable_name"] not in llm_chain_variables:
- raise ValueError(
+ msg = (
f"document_variable_name {values['document_variable_name']} was "
f"not found in llm_chain input_variables: {llm_chain_variables}"
)
+ raise ValueError(msg)
return values
def combine_docs(
diff --git a/libs/langchain/langchain/chains/combine_documents/reduce.py b/libs/langchain/langchain/chains/combine_documents/reduce.py
index 4b684357f5..0814c68a8d 100644
--- a/libs/langchain/langchain/chains/combine_documents/reduce.py
+++ b/libs/langchain/langchain/chains/combine_documents/reduce.py
@@ -48,10 +48,11 @@ def split_list_of_docs(
_num_tokens = length_func(_sub_result_docs, **kwargs)
if _num_tokens > token_max:
if len(_sub_result_docs) == 1:
- raise ValueError(
+ msg = (
"A single document was longer than the context length,"
" we cannot handle this."
)
+ raise ValueError(msg)
new_result_doc_list.append(_sub_result_docs[:-1])
_sub_result_docs = _sub_result_docs[-1:]
new_result_doc_list.append(_sub_result_docs)
@@ -314,10 +315,9 @@ class ReduceDocumentsChain(BaseCombineDocumentsChain):
num_tokens = length_func(result_docs, **kwargs)
retries += 1
if self.collapse_max_retries and retries == self.collapse_max_retries:
- raise ValueError(
- f"Exceed {self.collapse_max_retries} tries to \
+ msg = f"Exceed {self.collapse_max_retries} tries to \
collapse document to {_token_max} tokens."
- )
+ raise ValueError(msg)
return result_docs, {}
async def _acollapse(
@@ -349,10 +349,9 @@ class ReduceDocumentsChain(BaseCombineDocumentsChain):
num_tokens = length_func(result_docs, **kwargs)
retries += 1
if self.collapse_max_retries and retries == self.collapse_max_retries:
- raise ValueError(
- f"Exceed {self.collapse_max_retries} tries to \
+ msg = f"Exceed {self.collapse_max_retries} tries to \
collapse document to {_token_max} tokens."
- )
+ raise ValueError(msg)
return result_docs, {}
@property
diff --git a/libs/langchain/langchain/chains/combine_documents/refine.py b/libs/langchain/langchain/chains/combine_documents/refine.py
index fa03f85cf8..f3bf793e76 100644
--- a/libs/langchain/langchain/chains/combine_documents/refine.py
+++ b/libs/langchain/langchain/chains/combine_documents/refine.py
@@ -127,23 +127,26 @@ class RefineDocumentsChain(BaseCombineDocumentsChain):
def get_default_document_variable_name(cls, values: dict) -> Any:
"""Get default document variable name, if not provided."""
if "initial_llm_chain" not in values:
- raise ValueError("initial_llm_chain must be provided")
+ msg = "initial_llm_chain must be provided"
+ raise ValueError(msg)
llm_chain_variables = values["initial_llm_chain"].prompt.input_variables
if "document_variable_name" not in values:
if len(llm_chain_variables) == 1:
values["document_variable_name"] = llm_chain_variables[0]
else:
- raise ValueError(
+ msg = (
"document_variable_name must be provided if there are "
"multiple llm_chain input_variables"
)
+ raise ValueError(msg)
else:
if values["document_variable_name"] not in llm_chain_variables:
- raise ValueError(
+ msg = (
f"document_variable_name {values['document_variable_name']} was "
f"not found in llm_chain input_variables: {llm_chain_variables}"
)
+ raise ValueError(msg)
return values
def combine_docs(
diff --git a/libs/langchain/langchain/chains/combine_documents/stuff.py b/libs/langchain/langchain/chains/combine_documents/stuff.py
index 2078462c2a..ab837c9de9 100644
--- a/libs/langchain/langchain/chains/combine_documents/stuff.py
+++ b/libs/langchain/langchain/chains/combine_documents/stuff.py
@@ -175,16 +175,18 @@ class StuffDocumentsChain(BaseCombineDocumentsChain):
if len(llm_chain_variables) == 1:
values["document_variable_name"] = llm_chain_variables[0]
else:
- raise ValueError(
+ msg = (
"document_variable_name must be provided if there are "
"multiple llm_chain_variables"
)
+ raise ValueError(msg)
else:
if values["document_variable_name"] not in llm_chain_variables:
- raise ValueError(
+ msg = (
f"document_variable_name {values['document_variable_name']} was "
f"not found in llm_chain input_variables: {llm_chain_variables}"
)
+ raise ValueError(msg)
return values
@property
diff --git a/libs/langchain/langchain/chains/conversation/base.py b/libs/langchain/langchain/chains/conversation/base.py
index e214158b03..314f3d7f4e 100644
--- a/libs/langchain/langchain/chains/conversation/base.py
+++ b/libs/langchain/langchain/chains/conversation/base.py
@@ -126,16 +126,18 @@ class ConversationChain(LLMChain):
memory_keys = self.memory.memory_variables
input_key = self.input_key
if input_key in memory_keys:
- raise ValueError(
+ msg = (
f"The input key {input_key} was also found in the memory keys "
f"({memory_keys}) - please provide keys that don't overlap."
)
+ raise ValueError(msg)
prompt_variables = self.prompt.input_variables
expected_keys = memory_keys + [input_key]
if set(expected_keys) != set(prompt_variables):
- raise ValueError(
+ msg = (
"Got unexpected prompt input variables. The prompt expects "
f"{prompt_variables}, but got {memory_keys} as inputs from "
f"memory, and {input_key} as the normal input key."
)
+ raise ValueError(msg)
return self
diff --git a/libs/langchain/langchain/chains/conversational_retrieval/base.py b/libs/langchain/langchain/chains/conversational_retrieval/base.py
index 46ad0734db..9e9648d861 100644
--- a/libs/langchain/langchain/chains/conversational_retrieval/base.py
+++ b/libs/langchain/langchain/chains/conversational_retrieval/base.py
@@ -52,10 +52,11 @@ def _get_chat_history(chat_history: list[CHAT_TURN_TYPE]) -> str:
ai = "Assistant: " + dialogue_turn[1]
buffer += "\n" + "\n".join([human, ai])
else:
- raise ValueError(
+ msg = (
f"Unsupported chat history format: {type(dialogue_turn)}."
f" Full chat history: {chat_history} "
)
+ raise ValueError(msg)
return buffer
@@ -233,7 +234,8 @@ class BaseConversationalRetrievalChain(Chain):
def save(self, file_path: Union[Path, str]) -> None:
if self.get_chat_history:
- raise ValueError("Chain not saveable when `get_chat_history` is not None.")
+ msg = "Chain not saveable when `get_chat_history` is not None."
+ raise ValueError(msg)
super().save(file_path)
@@ -514,7 +516,8 @@ class ChatVectorDBChain(BaseConversationalRetrievalChain):
run_manager: AsyncCallbackManagerForChainRun,
) -> list[Document]:
"""Get docs."""
- raise NotImplementedError("ChatVectorDBChain does not support async")
+ msg = "ChatVectorDBChain does not support async"
+ raise NotImplementedError(msg)
@classmethod
def from_llm(
diff --git a/libs/langchain/langchain/chains/elasticsearch_database/base.py b/libs/langchain/langchain/chains/elasticsearch_database/base.py
index acf1e8f88a..e27ffa9d34 100644
--- a/libs/langchain/langchain/chains/elasticsearch_database/base.py
+++ b/libs/langchain/langchain/chains/elasticsearch_database/base.py
@@ -60,9 +60,8 @@ class ElasticsearchDatabaseChain(Chain):
@model_validator(mode="after")
def validate_indices(self) -> Self:
if self.include_indices and self.ignore_indices:
- raise ValueError(
- "Cannot specify both 'include_indices' and 'ignore_indices'."
- )
+ msg = "Cannot specify both 'include_indices' and 'ignore_indices'."
+ raise ValueError(msg)
return self
@property
diff --git a/libs/langchain/langchain/chains/flare/base.py b/libs/langchain/langchain/chains/flare/base.py
index e6c1defa04..973ed1b677 100644
--- a/libs/langchain/langchain/chains/flare/base.py
+++ b/libs/langchain/langchain/chains/flare/base.py
@@ -251,11 +251,12 @@ class FlareChain(Chain):
try:
from langchain_openai import ChatOpenAI
except ImportError:
- raise ImportError(
+ msg = (
"OpenAI is required for FlareChain. "
"Please install langchain-openai."
"pip install langchain-openai"
)
+ raise ImportError(msg)
llm = ChatOpenAI(
max_completion_tokens=max_generation_len, logprobs=True, temperature=0
)
diff --git a/libs/langchain/langchain/chains/history_aware_retriever.py b/libs/langchain/langchain/chains/history_aware_retriever.py
index a29d31a856..eafaeaf5cb 100644
--- a/libs/langchain/langchain/chains/history_aware_retriever.py
+++ b/libs/langchain/langchain/chains/history_aware_retriever.py
@@ -49,10 +49,11 @@ def create_history_aware_retriever(
"""
if "input" not in prompt.input_variables:
- raise ValueError(
+ msg = (
"Expected `input` to be a prompt variable, "
f"but got {prompt.input_variables}"
)
+ raise ValueError(msg)
retrieve_documents: RetrieverOutputLike = RunnableBranch(
(
diff --git a/libs/langchain/langchain/chains/hyde/base.py b/libs/langchain/langchain/chains/hyde/base.py
index d8c00d838c..b4f1a87bc3 100644
--- a/libs/langchain/langchain/chains/hyde/base.py
+++ b/libs/langchain/langchain/chains/hyde/base.py
@@ -110,10 +110,11 @@ class HypotheticalDocumentEmbedder(Chain, Embeddings):
elif prompt_key is not None and prompt_key in PROMPT_MAP:
prompt = PROMPT_MAP[prompt_key]
else:
- raise ValueError(
+ msg = (
f"Must specify prompt_key if custom_prompt not provided. Should be one "
f"of {list(PROMPT_MAP.keys())}."
)
+ raise ValueError(msg)
llm_chain = prompt | llm | StrOutputParser()
return cls(base_embeddings=base_embeddings, llm_chain=llm_chain, **kwargs)
diff --git a/libs/langchain/langchain/chains/llm.py b/libs/langchain/langchain/chains/llm.py
index 2ee4e20d68..9489614224 100644
--- a/libs/langchain/langchain/chains/llm.py
+++ b/libs/langchain/langchain/chains/llm.py
@@ -201,9 +201,8 @@ class LLMChain(Chain):
if run_manager:
run_manager.on_text(_text, end="\n", verbose=self.verbose)
if "stop" in inputs and inputs["stop"] != stop:
- raise ValueError(
- "If `stop` is present in any inputs, should be present in all."
- )
+ msg = "If `stop` is present in any inputs, should be present in all."
+ raise ValueError(msg)
prompts.append(prompt)
return prompts, stop
@@ -227,9 +226,8 @@ class LLMChain(Chain):
if run_manager:
await run_manager.on_text(_text, end="\n", verbose=self.verbose)
if "stop" in inputs and inputs["stop"] != stop:
- raise ValueError(
- "If `stop` is present in any inputs, should be present in all."
- )
+ msg = "If `stop` is present in any inputs, should be present in all."
+ raise ValueError(msg)
prompts.append(prompt)
return prompts, stop
@@ -420,7 +418,8 @@ def _get_language_model(llm_like: Runnable) -> BaseLanguageModel:
elif isinstance(llm_like, (RunnableBranch, DynamicRunnable)):
return _get_language_model(llm_like.default)
else:
- raise ValueError(
+ msg = (
f"Unable to extract BaseLanguageModel from llm_like object of type "
f"{type(llm_like)}"
)
+ raise ValueError(msg)
diff --git a/libs/langchain/langchain/chains/llm_bash/__init__.py b/libs/langchain/langchain/chains/llm_bash/__init__.py
index b055d992e4..ea0494dc2c 100644
--- a/libs/langchain/langchain/chains/llm_bash/__init__.py
+++ b/libs/langchain/langchain/chains/llm_bash/__init__.py
@@ -1,9 +1,10 @@
def __getattr__(name: str = "") -> None:
"""Raise an error on import since is deprecated."""
- raise AttributeError(
+ msg = (
"This module has been moved to langchain-experimental. "
"For more details: https://github.com/langchain-ai/langchain/discussions/11352."
"To access this code, install it with `pip install langchain-experimental`."
"`from langchain_experimental.llm_bash.base "
"import LLMBashChain`"
)
+ raise AttributeError(msg)
diff --git a/libs/langchain/langchain/chains/llm_math/base.py b/libs/langchain/langchain/chains/llm_math/base.py
index 96ef5d1046..674d599835 100644
--- a/libs/langchain/langchain/chains/llm_math/base.py
+++ b/libs/langchain/langchain/chains/llm_math/base.py
@@ -167,10 +167,11 @@ class LLMMathChain(Chain):
try:
import numexpr # noqa: F401
except ImportError:
- raise ImportError(
+ msg = (
"LLMMathChain requires the numexpr package. "
"Please install it with `pip install numexpr`."
)
+ raise ImportError(msg)
if "llm" in values:
warnings.warn(
"Directly instantiating an LLMMathChain with an llm is deprecated. "
@@ -211,10 +212,11 @@ class LLMMathChain(Chain):
)
)
except Exception as e:
- raise ValueError(
+ msg = (
f'LLMMathChain._evaluate("{expression}") raised error: {e}.'
" Please try again with a valid numerical expression"
)
+ raise ValueError(msg)
# Remove any leading and trailing brackets from the output
return re.sub(r"^\[|\]$", "", output)
@@ -236,7 +238,8 @@ class LLMMathChain(Chain):
elif "Answer:" in llm_output:
answer = "Answer: " + llm_output.split("Answer:")[-1]
else:
- raise ValueError(f"unknown format from LLM: {llm_output}")
+ msg = f"unknown format from LLM: {llm_output}"
+ raise ValueError(msg)
return {self.output_key: answer}
async def _aprocess_llm_result(
@@ -258,7 +261,8 @@ class LLMMathChain(Chain):
elif "Answer:" in llm_output:
answer = "Answer: " + llm_output.split("Answer:")[-1]
else:
- raise ValueError(f"unknown format from LLM: {llm_output}")
+ msg = f"unknown format from LLM: {llm_output}"
+ raise ValueError(msg)
return {self.output_key: answer}
def _call(
diff --git a/libs/langchain/langchain/chains/llm_summarization_checker/base.py b/libs/langchain/langchain/chains/llm_summarization_checker/base.py
index e1b02a2d04..fd96eeac2e 100644
--- a/libs/langchain/langchain/chains/llm_summarization_checker/base.py
+++ b/libs/langchain/langchain/chains/llm_summarization_checker/base.py
@@ -172,7 +172,8 @@ class LLMSummarizationCheckerChain(Chain):
chain_input = output["revised_summary"]
if not output:
- raise ValueError("No output from chain")
+ msg = "No output from chain"
+ raise ValueError(msg)
return {self.output_key: output["revised_summary"].strip()}
diff --git a/libs/langchain/langchain/chains/llm_symbolic_math/__init__.py b/libs/langchain/langchain/chains/llm_symbolic_math/__init__.py
index a3ce265f06..ae8f59f6e6 100644
--- a/libs/langchain/langchain/chains/llm_symbolic_math/__init__.py
+++ b/libs/langchain/langchain/chains/llm_symbolic_math/__init__.py
@@ -1,9 +1,10 @@
def __getattr__(name: str = "") -> None:
"""Raise an error on import since is deprecated."""
- raise AttributeError(
+ msg = (
"This module has been moved to langchain-experimental. "
"For more details: https://github.com/langchain-ai/langchain/discussions/11352."
"To access this code, install it with `pip install langchain-experimental`."
"`from langchain_experimental.llm_symbolic_math.base "
"import LLMSymbolicMathChain`"
)
+ raise AttributeError(msg)
diff --git a/libs/langchain/langchain/chains/loading.py b/libs/langchain/langchain/chains/loading.py
index 172f0c344b..6879d63222 100644
--- a/libs/langchain/langchain/chains/loading.py
+++ b/libs/langchain/langchain/chains/loading.py
@@ -40,18 +40,20 @@ try:
except ImportError:
def load_llm(*args: Any, **kwargs: Any) -> None:
- raise ImportError(
+ msg = (
"To use this load_llm functionality you must install the "
"langchain_community package. "
"You can install it with `pip install langchain_community`"
)
+ raise ImportError(msg)
def load_llm_from_config(*args: Any, **kwargs: Any) -> None:
- raise ImportError(
+ msg = (
"To use this load_llm_from_config functionality you must install the "
"langchain_community package. "
"You can install it with `pip install langchain_community`"
)
+ raise ImportError(msg)
URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/chains/"
@@ -65,7 +67,8 @@ def _load_llm_chain(config: dict, **kwargs: Any) -> LLMChain:
elif "llm_path" in config:
llm = load_llm(config.pop("llm_path"), **kwargs)
else:
- raise ValueError("One of `llm` or `llm_path` must be present.")
+ msg = "One of `llm` or `llm_path` must be present."
+ raise ValueError(msg)
if "prompt" in config:
prompt_config = config.pop("prompt")
@@ -73,7 +76,8 @@ def _load_llm_chain(config: dict, **kwargs: Any) -> LLMChain:
elif "prompt_path" in config:
prompt = load_prompt(config.pop("prompt_path"))
else:
- raise ValueError("One of `prompt` or `prompt_path` must be present.")
+ msg = "One of `prompt` or `prompt_path` must be present."
+ raise ValueError(msg)
_load_output_parser(config)
return LLMChain(llm=llm, prompt=prompt, **config)
@@ -87,11 +91,13 @@ def _load_hyde_chain(config: dict, **kwargs: Any) -> HypotheticalDocumentEmbedde
elif "llm_chain_path" in config:
llm_chain = load_chain(config.pop("llm_chain_path"), **kwargs)
else:
- raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.")
+ msg = "One of `llm_chain` or `llm_chain_path` must be present."
+ raise ValueError(msg)
if "embeddings" in kwargs:
embeddings = kwargs.pop("embeddings")
else:
- raise ValueError("`embeddings` must be present.")
+ msg = "`embeddings` must be present."
+ raise ValueError(msg)
return HypotheticalDocumentEmbedder(
llm_chain=llm_chain,
base_embeddings=embeddings,
@@ -106,10 +112,12 @@ def _load_stuff_documents_chain(config: dict, **kwargs: Any) -> StuffDocumentsCh
elif "llm_chain_path" in config:
llm_chain = load_chain(config.pop("llm_chain_path"), **kwargs)
else:
- raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.")
+ msg = "One of `llm_chain` or `llm_chain_path` must be present."
+ raise ValueError(msg)
if not isinstance(llm_chain, LLMChain):
- raise ValueError(f"Expected LLMChain, got {llm_chain}")
+ msg = f"Expected LLMChain, got {llm_chain}"
+ raise ValueError(msg)
if "document_prompt" in config:
prompt_config = config.pop("document_prompt")
@@ -117,9 +125,8 @@ def _load_stuff_documents_chain(config: dict, **kwargs: Any) -> StuffDocumentsCh
elif "document_prompt_path" in config:
document_prompt = load_prompt(config.pop("document_prompt_path"))
else:
- raise ValueError(
- "One of `document_prompt` or `document_prompt_path` must be present."
- )
+ msg = "One of `document_prompt` or `document_prompt_path` must be present."
+ raise ValueError(msg)
return StuffDocumentsChain(
llm_chain=llm_chain, document_prompt=document_prompt, **config
@@ -135,10 +142,12 @@ def _load_map_reduce_documents_chain(
elif "llm_chain_path" in config:
llm_chain = load_chain(config.pop("llm_chain_path"), **kwargs)
else:
- raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.")
+ msg = "One of `llm_chain` or `llm_chain_path` must be present."
+ raise ValueError(msg)
if not isinstance(llm_chain, LLMChain):
- raise ValueError(f"Expected LLMChain, got {llm_chain}")
+ msg = f"Expected LLMChain, got {llm_chain}"
+ raise ValueError(msg)
if "reduce_documents_chain" in config:
reduce_documents_chain = load_chain_from_config(
@@ -181,10 +190,11 @@ def _load_reduce_documents_chain(config: dict, **kwargs: Any) -> ReduceDocuments
config.pop("combine_document_chain_path"), **kwargs
)
else:
- raise ValueError(
+ msg = (
"One of `combine_documents_chain` or "
"`combine_documents_chain_path` must be present."
)
+ raise ValueError(msg)
if "collapse_documents_chain" in config:
collapse_document_chain_config = config.pop("collapse_documents_chain")
@@ -220,12 +230,13 @@ def _load_reduce_documents_chain(config: dict, **kwargs: Any) -> ReduceDocuments
def _load_llm_bash_chain(config: dict, **kwargs: Any) -> Any:
"""Load LLM Bash chain from config dict"""
- raise NotImplementedError(
+ msg = (
"LLMBash Chain is not available through LangChain anymore. "
"The relevant code can be found in langchain_experimental, "
"but it is not appropriate for production usage due to security "
"concerns. Please refer to langchain-experimental repository for more details."
)
+ raise NotImplementedError(msg)
def _load_llm_checker_chain(config: dict, **kwargs: Any) -> LLMCheckerChain:
@@ -235,7 +246,8 @@ def _load_llm_checker_chain(config: dict, **kwargs: Any) -> LLMCheckerChain:
elif "llm_path" in config:
llm = load_llm(config.pop("llm_path"), **kwargs)
else:
- raise ValueError("One of `llm` or `llm_path` must be present.")
+ msg = "One of `llm` or `llm_path` must be present."
+ raise ValueError(msg)
if "create_draft_answer_prompt" in config:
create_draft_answer_prompt_config = config.pop("create_draft_answer_prompt")
create_draft_answer_prompt = load_prompt_from_config(
@@ -290,7 +302,8 @@ def _load_llm_math_chain(config: dict, **kwargs: Any) -> LLMMathChain:
elif "llm_path" in config:
llm = load_llm(config.pop("llm_path"), **kwargs)
else:
- raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.")
+ msg = "One of `llm_chain` or `llm_chain_path` must be present."
+ raise ValueError(msg)
if "prompt" in config:
prompt_config = config.pop("prompt")
prompt = load_prompt_from_config(prompt_config)
@@ -311,17 +324,19 @@ def _load_map_rerank_documents_chain(
elif "llm_chain_path" in config:
llm_chain = load_chain(config.pop("llm_chain_path"), **kwargs)
else:
- raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.")
+ msg = "One of `llm_chain` or `llm_chain_path` must be present."
+ raise ValueError(msg)
return MapRerankDocumentsChain(llm_chain=llm_chain, **config) # type: ignore[arg-type]
def _load_pal_chain(config: dict, **kwargs: Any) -> Any:
- raise NotImplementedError(
+ msg = (
"PALChain is not available through LangChain anymore. "
"The relevant code can be found in langchain_experimental, "
"but it is not appropriate for production usage due to security "
"concerns. Please refer to langchain-experimental repository for more details."
)
+ raise NotImplementedError(msg)
def _load_refine_documents_chain(config: dict, **kwargs: Any) -> RefineDocumentsChain:
@@ -331,18 +346,16 @@ def _load_refine_documents_chain(config: dict, **kwargs: Any) -> RefineDocuments
elif "initial_llm_chain_path" in config:
initial_llm_chain = load_chain(config.pop("initial_llm_chain_path"), **kwargs)
else:
- raise ValueError(
- "One of `initial_llm_chain` or `initial_llm_chain_path` must be present."
- )
+ msg = "One of `initial_llm_chain` or `initial_llm_chain_path` must be present."
+ raise ValueError(msg)
if "refine_llm_chain" in config:
refine_llm_chain_config = config.pop("refine_llm_chain")
refine_llm_chain = load_chain_from_config(refine_llm_chain_config, **kwargs)
elif "refine_llm_chain_path" in config:
refine_llm_chain = load_chain(config.pop("refine_llm_chain_path"), **kwargs)
else:
- raise ValueError(
- "One of `refine_llm_chain` or `refine_llm_chain_path` must be present."
- )
+ msg = "One of `refine_llm_chain` or `refine_llm_chain_path` must be present."
+ raise ValueError(msg)
if "document_prompt" in config:
prompt_config = config.pop("document_prompt")
document_prompt = load_prompt_from_config(prompt_config)
@@ -367,16 +380,17 @@ def _load_qa_with_sources_chain(config: dict, **kwargs: Any) -> QAWithSourcesCha
config.pop("combine_documents_chain_path"), **kwargs
)
else:
- raise ValueError(
+ msg = (
"One of `combine_documents_chain` or "
"`combine_documents_chain_path` must be present."
)
+ raise ValueError(msg)
return QAWithSourcesChain(combine_documents_chain=combine_documents_chain, **config) # type: ignore[arg-type]
def _load_sql_database_chain(config: dict, **kwargs: Any) -> Any:
"""Load SQL Database chain from config dict."""
- raise NotImplementedError(
+ msg = (
"SQLDatabaseChain is not available through LangChain anymore. "
"The relevant code can be found in langchain_experimental, "
"but it is not appropriate for production usage due to security "
@@ -384,6 +398,7 @@ def _load_sql_database_chain(config: dict, **kwargs: Any) -> Any:
"or refer to this tutorial for best practices: "
"https://python.langchain.com/docs/tutorials/sql_qa/"
)
+ raise NotImplementedError(msg)
def _load_vector_db_qa_with_sources_chain(
@@ -392,7 +407,8 @@ def _load_vector_db_qa_with_sources_chain(
if "vectorstore" in kwargs:
vectorstore = kwargs.pop("vectorstore")
else:
- raise ValueError("`vectorstore` must be present.")
+ msg = "`vectorstore` must be present."
+ raise ValueError(msg)
if "combine_documents_chain" in config:
combine_documents_chain_config = config.pop("combine_documents_chain")
combine_documents_chain = load_chain_from_config(
@@ -403,10 +419,11 @@ def _load_vector_db_qa_with_sources_chain(
config.pop("combine_documents_chain_path"), **kwargs
)
else:
- raise ValueError(
+ msg = (
"One of `combine_documents_chain` or "
"`combine_documents_chain_path` must be present."
)
+ raise ValueError(msg)
return VectorDBQAWithSourcesChain(
combine_documents_chain=combine_documents_chain, # type: ignore[arg-type]
vectorstore=vectorstore,
@@ -418,7 +435,8 @@ def _load_retrieval_qa(config: dict, **kwargs: Any) -> RetrievalQA:
if "retriever" in kwargs:
retriever = kwargs.pop("retriever")
else:
- raise ValueError("`retriever` must be present.")
+ msg = "`retriever` must be present."
+ raise ValueError(msg)
if "combine_documents_chain" in config:
combine_documents_chain_config = config.pop("combine_documents_chain")
combine_documents_chain = load_chain_from_config(
@@ -429,10 +447,11 @@ def _load_retrieval_qa(config: dict, **kwargs: Any) -> RetrievalQA:
config.pop("combine_documents_chain_path"), **kwargs
)
else:
- raise ValueError(
+ msg = (
"One of `combine_documents_chain` or "
"`combine_documents_chain_path` must be present."
)
+ raise ValueError(msg)
return RetrievalQA(
combine_documents_chain=combine_documents_chain, # type: ignore[arg-type]
retriever=retriever,
@@ -446,7 +465,8 @@ def _load_retrieval_qa_with_sources_chain(
if "retriever" in kwargs:
retriever = kwargs.pop("retriever")
else:
- raise ValueError("`retriever` must be present.")
+ msg = "`retriever` must be present."
+ raise ValueError(msg)
if "combine_documents_chain" in config:
combine_documents_chain_config = config.pop("combine_documents_chain")
combine_documents_chain = load_chain_from_config(
@@ -457,10 +477,11 @@ def _load_retrieval_qa_with_sources_chain(
config.pop("combine_documents_chain_path"), **kwargs
)
else:
- raise ValueError(
+ msg = (
"One of `combine_documents_chain` or "
"`combine_documents_chain_path` must be present."
)
+ raise ValueError(msg)
return RetrievalQAWithSourcesChain(
combine_documents_chain=combine_documents_chain, # type: ignore[arg-type]
retriever=retriever,
@@ -472,7 +493,8 @@ def _load_vector_db_qa(config: dict, **kwargs: Any) -> VectorDBQA:
if "vectorstore" in kwargs:
vectorstore = kwargs.pop("vectorstore")
else:
- raise ValueError("`vectorstore` must be present.")
+ msg = "`vectorstore` must be present."
+ raise ValueError(msg)
if "combine_documents_chain" in config:
combine_documents_chain_config = config.pop("combine_documents_chain")
combine_documents_chain = load_chain_from_config(
@@ -483,10 +505,11 @@ def _load_vector_db_qa(config: dict, **kwargs: Any) -> VectorDBQA:
config.pop("combine_documents_chain_path"), **kwargs
)
else:
- raise ValueError(
+ msg = (
"One of `combine_documents_chain` or "
"`combine_documents_chain_path` must be present."
)
+ raise ValueError(msg)
return VectorDBQA(
combine_documents_chain=combine_documents_chain, # type: ignore[arg-type]
vectorstore=vectorstore,
@@ -498,28 +521,32 @@ def _load_graph_cypher_chain(config: dict, **kwargs: Any) -> GraphCypherQAChain:
if "graph" in kwargs:
graph = kwargs.pop("graph")
else:
- raise ValueError("`graph` must be present.")
+ msg = "`graph` must be present."
+ raise ValueError(msg)
if "cypher_generation_chain" in config:
cypher_generation_chain_config = config.pop("cypher_generation_chain")
cypher_generation_chain = load_chain_from_config(
cypher_generation_chain_config, **kwargs
)
else:
- raise ValueError("`cypher_generation_chain` must be present.")
+ msg = "`cypher_generation_chain` must be present."
+ raise ValueError(msg)
if "qa_chain" in config:
qa_chain_config = config.pop("qa_chain")
qa_chain = load_chain_from_config(qa_chain_config, **kwargs)
else:
- raise ValueError("`qa_chain` must be present.")
+ msg = "`qa_chain` must be present."
+ raise ValueError(msg)
try:
from langchain_community.chains.graph_qa.cypher import GraphCypherQAChain
except ImportError:
- raise ImportError(
+ msg = (
"To use this GraphCypherQAChain functionality you must install the "
"langchain_community package. "
"You can install it with `pip install langchain_community`"
)
+ raise ImportError(msg)
return GraphCypherQAChain(
graph=graph,
cypher_generation_chain=cypher_generation_chain,
@@ -535,22 +562,21 @@ def _load_api_chain(config: dict, **kwargs: Any) -> APIChain:
elif "api_request_chain_path" in config:
api_request_chain = load_chain(config.pop("api_request_chain_path"))
else:
- raise ValueError(
- "One of `api_request_chain` or `api_request_chain_path` must be present."
- )
+ msg = "One of `api_request_chain` or `api_request_chain_path` must be present."
+ raise ValueError(msg)
if "api_answer_chain" in config:
api_answer_chain_config = config.pop("api_answer_chain")
api_answer_chain = load_chain_from_config(api_answer_chain_config, **kwargs)
elif "api_answer_chain_path" in config:
api_answer_chain = load_chain(config.pop("api_answer_chain_path"), **kwargs)
else:
- raise ValueError(
- "One of `api_answer_chain` or `api_answer_chain_path` must be present."
- )
+ msg = "One of `api_answer_chain` or `api_answer_chain_path` must be present."
+ raise ValueError(msg)
if "requests_wrapper" in kwargs:
requests_wrapper = kwargs.pop("requests_wrapper")
else:
- raise ValueError("`requests_wrapper` must be present.")
+ msg = "`requests_wrapper` must be present."
+ raise ValueError(msg)
return APIChain(
api_request_chain=api_request_chain, # type: ignore[arg-type]
api_answer_chain=api_answer_chain, # type: ignore[arg-type]
@@ -563,11 +589,12 @@ def _load_llm_requests_chain(config: dict, **kwargs: Any) -> LLMRequestsChain:
try:
from langchain.chains.llm_requests import LLMRequestsChain
except ImportError:
- raise ImportError(
+ msg = (
"To use this LLMRequestsChain functionality you must install the "
"langchain package. "
"You can install it with `pip install langchain`"
)
+ raise ImportError(msg)
if "llm_chain" in config:
llm_chain_config = config.pop("llm_chain")
@@ -575,7 +602,8 @@ def _load_llm_requests_chain(config: dict, **kwargs: Any) -> LLMRequestsChain:
elif "llm_chain_path" in config:
llm_chain = load_chain(config.pop("llm_chain_path"), **kwargs)
else:
- raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.")
+ msg = "One of `llm_chain` or `llm_chain_path` must be present."
+ raise ValueError(msg)
if "requests_wrapper" in kwargs:
requests_wrapper = kwargs.pop("requests_wrapper")
return LLMRequestsChain(
@@ -620,11 +648,13 @@ type_to_loader_dict = {
def load_chain_from_config(config: dict, **kwargs: Any) -> Chain:
"""Load chain from Config Dict."""
if "_type" not in config:
- raise ValueError("Must specify a chain Type in config")
+ msg = "Must specify a chain Type in config"
+ raise ValueError(msg)
config_type = config.pop("_type")
if config_type not in type_to_loader_dict:
- raise ValueError(f"Loading {config_type} chain not supported")
+ msg = f"Loading {config_type} chain not supported"
+ raise ValueError(msg)
chain_loader = type_to_loader_dict[config_type]
return chain_loader(config, **kwargs)
@@ -641,11 +671,12 @@ def load_chain_from_config(config: dict, **kwargs: Any) -> Chain:
def load_chain(path: Union[str, Path], **kwargs: Any) -> Chain:
"""Unified method for loading a chain from LangChainHub or local fs."""
if isinstance(path, str) and path.startswith("lc://"):
- raise RuntimeError(
+ msg = (
"Loading from the deprecated github-based Hub is no longer supported. "
"Please use the new LangChain Hub at https://smith.langchain.com/hub "
"instead."
)
+ raise RuntimeError(msg)
return _load_chain_from_file(path, **kwargs)
@@ -664,7 +695,8 @@ def _load_chain_from_file(file: Union[str, Path], **kwargs: Any) -> Chain:
with open(file_path) as f:
config = yaml.safe_load(f)
else:
- raise ValueError("File type must be json or yaml")
+ msg = "File type must be json or yaml"
+ raise ValueError(msg)
# Override default 'verbose' and 'memory' for the chain
if "verbose" in kwargs:
diff --git a/libs/langchain/langchain/chains/moderation.py b/libs/langchain/langchain/chains/moderation.py
index e31418a849..e906de8c99 100644
--- a/libs/langchain/langchain/chains/moderation.py
+++ b/libs/langchain/langchain/chains/moderation.py
@@ -71,10 +71,11 @@ class OpenAIModerationChain(Chain):
values["async_client"] = openai.AsyncOpenAI(api_key=openai_api_key)
except ImportError:
- raise ImportError(
+ msg = (
"Could not import openai python package. "
"Please install it with `pip install openai`."
)
+ raise ImportError(msg)
return values
@property
diff --git a/libs/langchain/langchain/chains/natbot/base.py b/libs/langchain/langchain/chains/natbot/base.py
index 2dcfb6b47b..c71cb6631e 100644
--- a/libs/langchain/langchain/chains/natbot/base.py
+++ b/libs/langchain/langchain/chains/natbot/base.py
@@ -82,11 +82,12 @@ class NatBotChain(Chain):
@classmethod
def from_default(cls, objective: str, **kwargs: Any) -> NatBotChain:
"""Load with default LLMChain."""
- raise NotImplementedError(
+ msg = (
"This method is no longer implemented. Please use from_llm."
"llm = OpenAI(temperature=0.5, best_of=10, n=3, max_tokens=50)"
"For example, NatBotChain.from_llm(llm, objective)"
)
+ raise NotImplementedError(msg)
@classmethod
def from_llm(
diff --git a/libs/langchain/langchain/chains/openai_functions/base.py b/libs/langchain/langchain/chains/openai_functions/base.py
index ca191a3514..c6b37a01fe 100644
--- a/libs/langchain/langchain/chains/openai_functions/base.py
+++ b/libs/langchain/langchain/chains/openai_functions/base.py
@@ -123,7 +123,8 @@ def create_openai_fn_chain(
# -> RecordDog(name="Harry", color="brown", fav_food="chicken")
""" # noqa: E501
if not functions:
- raise ValueError("Need to pass in at least one function. Received zero.")
+ msg = "Need to pass in at least one function. Received zero."
+ raise ValueError(msg)
openai_functions = [convert_to_openai_function(f) for f in functions]
output_parser = output_parser or get_openai_output_parser(functions)
llm_kwargs: dict[str, Any] = {
diff --git a/libs/langchain/langchain/chains/openai_functions/citation_fuzzy_match.py b/libs/langchain/langchain/chains/openai_functions/citation_fuzzy_match.py
index 674a0809cb..01e8a9c83b 100644
--- a/libs/langchain/langchain/chains/openai_functions/citation_fuzzy_match.py
+++ b/libs/langchain/langchain/chains/openai_functions/citation_fuzzy_match.py
@@ -88,9 +88,8 @@ def create_citation_fuzzy_match_runnable(llm: BaseChatModel) -> Runnable:
Runnable that can be used to answer questions with citations.
"""
if llm.bind_tools is BaseChatModel.bind_tools:
- raise ValueError(
- "Language model must implement bind_tools to use this function."
- )
+ msg = "Language model must implement bind_tools to use this function."
+ raise ValueError(msg)
prompt = ChatPromptTemplate(
[
SystemMessage(
diff --git a/libs/langchain/langchain/chains/openai_functions/openapi.py b/libs/langchain/langchain/chains/openai_functions/openapi.py
index 76fa27fc37..94d4ad3be2 100644
--- a/libs/langchain/langchain/chains/openai_functions/openapi.py
+++ b/libs/langchain/langchain/chains/openai_functions/openapi.py
@@ -103,10 +103,11 @@ def openapi_spec_to_openai_fn(
try:
from langchain_community.tools import APIOperation
except ImportError:
- raise ImportError(
+ msg = (
"Could not import langchain_community.tools. "
"Please install it with `pip install langchain-community`."
)
+ raise ImportError(msg)
if not spec.paths:
return [], lambda: None
@@ -353,10 +354,11 @@ def get_openapi_chain(
try:
from langchain_community.utilities.openapi import OpenAPISpec
except ImportError as e:
- raise ImportError(
+ msg = (
"Could not import langchain_community.utilities.openapi. "
"Please install it with `pip install langchain-community`."
- ) from e
+ )
+ raise ImportError(msg) from e
if isinstance(spec, str):
for conversion in (
OpenAPISpec.from_url,
@@ -371,14 +373,16 @@ def get_openapi_chain(
except Exception: # noqa: S110
pass
if isinstance(spec, str):
- raise ValueError(f"Unable to parse spec from source {spec}")
+ msg = f"Unable to parse spec from source {spec}"
+ raise ValueError(msg)
openai_fns, call_api_fn = openapi_spec_to_openai_fn(spec)
if not llm:
- raise ValueError(
+ msg = (
"Must provide an LLM for this chain.For example,\n"
"from langchain_openai import ChatOpenAI\n"
"llm = ChatOpenAI()\n"
)
+ raise ValueError(msg)
prompt = prompt or ChatPromptTemplate.from_template(
"Use the provided API's to respond to this user query:\n\n{query}"
)
diff --git a/libs/langchain/langchain/chains/openai_functions/qa_with_structure.py b/libs/langchain/langchain/chains/openai_functions/qa_with_structure.py
index f76a281341..4520a5b15e 100644
--- a/libs/langchain/langchain/chains/openai_functions/qa_with_structure.py
+++ b/libs/langchain/langchain/chains/openai_functions/qa_with_structure.py
@@ -57,20 +57,22 @@ def create_qa_with_structure_chain(
"""
if output_parser == "pydantic":
if not (isinstance(schema, type) and is_basemodel_subclass(schema)):
- raise ValueError(
+ msg = (
"Must provide a pydantic class for schema when output_parser is "
"'pydantic'."
)
+ raise ValueError(msg)
_output_parser: BaseLLMOutputParser = PydanticOutputFunctionsParser(
pydantic_schema=schema
)
elif output_parser == "base":
_output_parser = OutputFunctionsParser()
else:
- raise ValueError(
+ msg = (
f"Got unexpected output_parser: {output_parser}. "
f"Should be one of `pydantic` or `base`."
)
+ raise ValueError(msg)
if isinstance(schema, type) and is_basemodel_subclass(schema):
if hasattr(schema, "model_json_schema"):
schema_dict = cast(dict, schema.model_json_schema())
diff --git a/libs/langchain/langchain/chains/qa_with_sources/loading.py b/libs/langchain/langchain/chains/qa_with_sources/loading.py
index b9e04911e8..19fcaa14c4 100644
--- a/libs/langchain/langchain/chains/qa_with_sources/loading.py
+++ b/libs/langchain/langchain/chains/qa_with_sources/loading.py
@@ -98,10 +98,11 @@ def _load_map_reduce_chain(
if collapse_prompt is None:
collapse_chain = None
if collapse_llm is not None:
- raise ValueError(
+ msg = (
"collapse_llm provided, but collapse_prompt was not: please "
"provide one or stop providing collapse_llm."
)
+ raise ValueError(msg)
else:
_collapse_llm = collapse_llm or llm
collapse_chain = StuffDocumentsChain(
@@ -193,9 +194,10 @@ def load_qa_with_sources_chain(
"map_rerank": _load_map_rerank_chain,
}
if chain_type not in loader_mapping:
- raise ValueError(
+ msg = (
f"Got unsupported chain type: {chain_type}. "
f"Should be one of {loader_mapping.keys()}"
)
+ raise ValueError(msg)
_func: LoadingCallable = loader_mapping[chain_type]
return _func(llm, verbose=verbose, **kwargs)
diff --git a/libs/langchain/langchain/chains/qa_with_sources/vector_db.py b/libs/langchain/langchain/chains/qa_with_sources/vector_db.py
index e8ca728686..c6cb0e0d01 100644
--- a/libs/langchain/langchain/chains/qa_with_sources/vector_db.py
+++ b/libs/langchain/langchain/chains/qa_with_sources/vector_db.py
@@ -59,7 +59,8 @@ class VectorDBQAWithSourcesChain(BaseQAWithSourcesChain):
async def _aget_docs(
self, inputs: dict[str, Any], *, run_manager: AsyncCallbackManagerForChainRun
) -> list[Document]:
- raise NotImplementedError("VectorDBQAWithSourcesChain does not support async")
+ msg = "VectorDBQAWithSourcesChain does not support async"
+ raise NotImplementedError(msg)
@model_validator(mode="before")
@classmethod
diff --git a/libs/langchain/langchain/chains/query_constructor/base.py b/libs/langchain/langchain/chains/query_constructor/base.py
index c1dadaaba5..9450dfa73d 100644
--- a/libs/langchain/langchain/chains/query_constructor/base.py
+++ b/libs/langchain/langchain/chains/query_constructor/base.py
@@ -63,9 +63,8 @@ class StructuredQueryOutputParser(BaseOutputParser[StructuredQuery]):
**{k: v for k, v in parsed.items() if k in allowed_keys}
)
except Exception as e:
- raise OutputParserException(
- f"Parsing text\n{text}\n raised following error:\n{e}"
- )
+ msg = f"Parsing text\n{text}\n raised following error:\n{e}"
+ raise OutputParserException(msg)
@classmethod
def from_components(
diff --git a/libs/langchain/langchain/chains/query_constructor/parser.py b/libs/langchain/langchain/chains/query_constructor/parser.py
index 8e39fd1dc3..62b6ea24fe 100644
--- a/libs/langchain/langchain/chains/query_constructor/parser.py
+++ b/libs/langchain/langchain/chains/query_constructor/parser.py
@@ -95,10 +95,11 @@ class QueryTransformer(Transformer):
func = self._match_func_name(str(func_name))
if isinstance(func, Comparator):
if self.allowed_attributes and args[0] not in self.allowed_attributes:
- raise ValueError(
+ msg = (
f"Received invalid attributes {args[0]}. Allowed attributes are "
f"{self.allowed_attributes}"
)
+ raise ValueError(msg)
return Comparison(comparator=func, attribute=args[0], value=args[1])
elif len(args) == 1 and func in (Operator.AND, Operator.OR):
return args[0]
@@ -109,24 +110,27 @@ class QueryTransformer(Transformer):
if func_name in set(Comparator):
if self.allowed_comparators is not None:
if func_name not in self.allowed_comparators:
- raise ValueError(
+ msg = (
f"Received disallowed comparator {func_name}. Allowed "
f"comparators are {self.allowed_comparators}"
)
+ raise ValueError(msg)
return Comparator(func_name)
elif func_name in set(Operator):
if self.allowed_operators is not None:
if func_name not in self.allowed_operators:
- raise ValueError(
+ msg = (
f"Received disallowed operator {func_name}. Allowed operators"
f" are {self.allowed_operators}"
)
+ raise ValueError(msg)
return Operator(func_name)
else:
- raise ValueError(
+ msg = (
f"Received unrecognized function {func_name}. Valid functions are "
f"{list(Operator) + list(Comparator)}"
)
+ raise ValueError(msg)
def args(self, *items: Any) -> tuple:
return items
@@ -168,9 +172,8 @@ class QueryTransformer(Transformer):
try:
datetime.datetime.strptime(item, "%Y-%m-%dT%H:%M:%S")
except ValueError:
- raise ValueError(
- "Datetime values are expected to be in ISO 8601 format."
- )
+ msg = "Datetime values are expected to be in ISO 8601 format."
+ raise ValueError(msg)
return {"datetime": item, "type": "datetime"}
def string(self, item: Any) -> str:
@@ -194,9 +197,8 @@ def get_parser(
"""
# QueryTransformer is None when Lark cannot be imported.
if QueryTransformer is None:
- raise ImportError(
- "Cannot import lark, please install it with 'pip install lark'."
- )
+ msg = "Cannot import lark, please install it with 'pip install lark'."
+ raise ImportError(msg)
transformer = QueryTransformer(
allowed_comparators=allowed_comparators,
allowed_operators=allowed_operators,
diff --git a/libs/langchain/langchain/chains/question_answering/chain.py b/libs/langchain/langchain/chains/question_answering/chain.py
index 8dbf6934f4..0f2376333e 100644
--- a/libs/langchain/langchain/chains/question_answering/chain.py
+++ b/libs/langchain/langchain/chains/question_answering/chain.py
@@ -138,10 +138,11 @@ def _load_map_reduce_chain(
if collapse_prompt is None:
collapse_chain = None
if collapse_llm is not None:
- raise ValueError(
+ msg = (
"collapse_llm provided, but collapse_prompt was not: please "
"provide one or stop providing collapse_llm."
)
+ raise ValueError(msg)
else:
_collapse_llm = collapse_llm or llm
collapse_chain = StuffDocumentsChain(
@@ -259,10 +260,11 @@ def load_qa_chain(
"map_rerank": _load_map_rerank_chain,
}
if chain_type not in loader_mapping:
- raise ValueError(
+ msg = (
f"Got unsupported chain type: {chain_type}. "
f"Should be one of {loader_mapping.keys()}"
)
+ raise ValueError(msg)
return loader_mapping[chain_type](
llm, verbose=verbose, callback_manager=callback_manager, **kwargs
)
diff --git a/libs/langchain/langchain/chains/retrieval_qa/base.py b/libs/langchain/langchain/chains/retrieval_qa/base.py
index 0cf59cd1c2..491891e44f 100644
--- a/libs/langchain/langchain/chains/retrieval_qa/base.py
+++ b/libs/langchain/langchain/chains/retrieval_qa/base.py
@@ -326,7 +326,8 @@ class VectorDBQA(BaseRetrievalQA):
if "search_type" in values:
search_type = values["search_type"]
if search_type not in ("similarity", "mmr"):
- raise ValueError(f"search_type of {search_type} not allowed.")
+ msg = f"search_type of {search_type} not allowed."
+ raise ValueError(msg)
return values
def _get_docs(
@@ -345,7 +346,8 @@ class VectorDBQA(BaseRetrievalQA):
question, k=self.k, **self.search_kwargs
)
else:
- raise ValueError(f"search_type of {self.search_type} not allowed.")
+ msg = f"search_type of {self.search_type} not allowed."
+ raise ValueError(msg)
return docs
async def _aget_docs(
@@ -355,7 +357,8 @@ class VectorDBQA(BaseRetrievalQA):
run_manager: AsyncCallbackManagerForChainRun,
) -> list[Document]:
"""Get docs."""
- raise NotImplementedError("VectorDBQA does not support async")
+ msg = "VectorDBQA does not support async"
+ raise NotImplementedError(msg)
@property
def _chain_type(self) -> str:
diff --git a/libs/langchain/langchain/chains/router/base.py b/libs/langchain/langchain/chains/router/base.py
index e9561d39f2..46e058b769 100644
--- a/libs/langchain/langchain/chains/router/base.py
+++ b/libs/langchain/langchain/chains/router/base.py
@@ -104,9 +104,8 @@ class MultiRouteChain(Chain):
elif self.silent_errors:
return self.default_chain(route.next_inputs, callbacks=callbacks)
else:
- raise ValueError(
- f"Received invalid destination chain name '{route.destination}'"
- )
+ msg = f"Received invalid destination chain name '{route.destination}'"
+ raise ValueError(msg)
async def _acall(
self,
@@ -133,6 +132,5 @@ class MultiRouteChain(Chain):
route.next_inputs, callbacks=callbacks
)
else:
- raise ValueError(
- f"Received invalid destination chain name '{route.destination}'"
- )
+ msg = f"Received invalid destination chain name '{route.destination}'"
+ raise ValueError(msg)
diff --git a/libs/langchain/langchain/chains/router/llm_router.py b/libs/langchain/langchain/chains/router/llm_router.py
index 759e6f9359..2cf6a44251 100644
--- a/libs/langchain/langchain/chains/router/llm_router.py
+++ b/libs/langchain/langchain/chains/router/llm_router.py
@@ -105,12 +105,13 @@ class LLMRouterChain(RouterChain):
def validate_prompt(self) -> Self:
prompt = self.llm_chain.prompt
if prompt.output_parser is None:
- raise ValueError(
+ msg = (
"LLMRouterChain requires base llm_chain prompt to have an output"
" parser that converts LLM text output to a dictionary with keys"
" 'destination' and 'next_inputs'. Received a prompt with no output"
" parser."
)
+ raise ValueError(msg)
return self
@property
@@ -175,11 +176,11 @@ class RouterOutputParser(BaseOutputParser[dict[str, str]]):
expected_keys = ["destination", "next_inputs"]
parsed = parse_and_check_json_markdown(text, expected_keys)
if not isinstance(parsed["destination"], str):
- raise ValueError("Expected 'destination' to be a string.")
+ msg = "Expected 'destination' to be a string."
+ raise ValueError(msg)
if not isinstance(parsed["next_inputs"], self.next_inputs_type):
- raise ValueError(
- f"Expected 'next_inputs' to be {self.next_inputs_type}."
- )
+ msg = f"Expected 'next_inputs' to be {self.next_inputs_type}."
+ raise ValueError(msg)
parsed["next_inputs"] = {self.next_inputs_inner_key: parsed["next_inputs"]}
if (
parsed["destination"].strip().lower()
@@ -190,6 +191,5 @@ class RouterOutputParser(BaseOutputParser[dict[str, str]]):
parsed["destination"] = parsed["destination"].strip()
return parsed
except Exception as e:
- raise OutputParserException(
- f"Parsing text\n{text}\n raised following error:\n{e}"
- )
+ msg = f"Parsing text\n{text}\n raised following error:\n{e}"
+ raise OutputParserException(msg)
diff --git a/libs/langchain/langchain/chains/router/multi_retrieval_qa.py b/libs/langchain/langchain/chains/router/multi_retrieval_qa.py
index fe900d86be..2eb3bdd4f0 100644
--- a/libs/langchain/langchain/chains/router/multi_retrieval_qa.py
+++ b/libs/langchain/langchain/chains/router/multi_retrieval_qa.py
@@ -48,10 +48,11 @@ class MultiRetrievalQAChain(MultiRouteChain):
**kwargs: Any,
) -> MultiRetrievalQAChain:
if default_prompt and not default_retriever:
- raise ValueError(
+ msg = (
"`default_retriever` must be specified if `default_prompt` is "
"provided. Received only `default_prompt`."
)
+ raise ValueError(msg)
destinations = [f"{r['name']}: {r['description']}" for r in retriever_infos]
destinations_str = "\n".join(destinations)
router_template = MULTI_RETRIEVAL_ROUTER_TEMPLATE.format(
@@ -82,7 +83,7 @@ class MultiRetrievalQAChain(MultiRouteChain):
template=prompt_template, input_variables=["history", "query"]
)
if default_chain_llm is None:
- raise NotImplementedError(
+ msg = (
"conversation_llm must be provided if default_chain is not "
"specified. This API has been changed to avoid instantiating "
"default LLMs on behalf of users."
@@ -90,6 +91,7 @@ class MultiRetrievalQAChain(MultiRouteChain):
"from langchain_openai import ChatOpenAI\n"
"llm = ChatOpenAI()"
)
+ raise NotImplementedError(msg)
_default_chain = ConversationChain(
llm=default_chain_llm,
prompt=prompt,
diff --git a/libs/langchain/langchain/chains/sequential.py b/libs/langchain/langchain/chains/sequential.py
index bc6c0ed1ad..0a54e02985 100644
--- a/libs/langchain/langchain/chains/sequential.py
+++ b/libs/langchain/langchain/chains/sequential.py
@@ -54,11 +54,12 @@ class SequentialChain(Chain):
memory_keys = values["memory"].memory_variables
if set(input_variables).intersection(set(memory_keys)):
overlapping_keys = set(input_variables) & set(memory_keys)
- raise ValueError(
+ msg = (
f"The input key(s) {''.join(overlapping_keys)} are found "
f"in the Memory keys ({memory_keys}) - please use input and "
f"memory keys that don't overlap."
)
+ raise ValueError(msg)
known_variables = set(input_variables + memory_keys)
@@ -68,15 +69,15 @@ class SequentialChain(Chain):
missing_vars = missing_vars.difference(chain.memory.memory_variables)
if missing_vars:
- raise ValueError(
+ msg = (
f"Missing required input keys: {missing_vars}, "
f"only had {known_variables}"
)
+ raise ValueError(msg)
overlapping_keys = known_variables.intersection(chain.output_keys)
if overlapping_keys:
- raise ValueError(
- f"Chain returned keys that already exist: {overlapping_keys}"
- )
+ msg = f"Chain returned keys that already exist: {overlapping_keys}"
+ raise ValueError(msg)
known_variables |= set(chain.output_keys)
@@ -89,9 +90,8 @@ class SequentialChain(Chain):
else:
missing_vars = set(values["output_variables"]).difference(known_variables)
if missing_vars:
- raise ValueError(
- f"Expected output variables that were not found: {missing_vars}."
- )
+ msg = f"Expected output variables that were not found: {missing_vars}."
+ raise ValueError(msg)
return values
@@ -158,15 +158,17 @@ class SimpleSequentialChain(Chain):
"""Validate that chains are all single input/output."""
for chain in self.chains:
if len(chain.input_keys) != 1:
- raise ValueError(
+ msg = (
"Chains used in SimplePipeline should all have one input, got "
f"{chain} with {len(chain.input_keys)} inputs."
)
+ raise ValueError(msg)
if len(chain.output_keys) != 1:
- raise ValueError(
+ msg = (
"Chains used in SimplePipeline should all have one output, got "
f"{chain} with {len(chain.output_keys)} outputs."
)
+ raise ValueError(msg)
return self
def _call(
diff --git a/libs/langchain/langchain/chains/sql_database/query.py b/libs/langchain/langchain/chains/sql_database/query.py
index c83495ced0..ce7018ffa0 100644
--- a/libs/langchain/langchain/chains/sql_database/query.py
+++ b/libs/langchain/langchain/chains/sql_database/query.py
@@ -123,22 +123,24 @@ def create_sql_query_chain(
if {"input", "top_k", "table_info"}.difference(
prompt_to_use.input_variables + list(prompt_to_use.partial_variables)
):
- raise ValueError(
+ msg = (
f"Prompt must have input variables: 'input', 'top_k', "
f"'table_info'. Received prompt with input variables: "
f"{prompt_to_use.input_variables}. Full prompt:\n\n{prompt_to_use}"
)
+ raise ValueError(msg)
if "dialect" in prompt_to_use.input_variables:
prompt_to_use = prompt_to_use.partial(dialect=db.dialect)
table_info_kwargs = {}
if get_col_comments:
if db.dialect not in ("postgresql", "mysql", "oracle"):
- raise ValueError(
+ msg = (
f"get_col_comments=True is only supported for dialects "
f"'postgresql', 'mysql', and 'oracle'. Received dialect: "
f"{db.dialect}"
)
+ raise ValueError(msg)
else:
table_info_kwargs["get_col_comments"] = True
diff --git a/libs/langchain/langchain/chains/structured_output/base.py b/libs/langchain/langchain/chains/structured_output/base.py
index 1f3887ed91..c4c431d6d1 100644
--- a/libs/langchain/langchain/chains/structured_output/base.py
+++ b/libs/langchain/langchain/chains/structured_output/base.py
@@ -134,7 +134,8 @@ def create_openai_fn_runnable(
# -> RecordDog(name="Harry", color="brown", fav_food="chicken")
""" # noqa: E501
if not functions:
- raise ValueError("Need to pass in at least one function. Received zero.")
+ msg = "Need to pass in at least one function. Received zero."
+ raise ValueError(msg)
openai_functions = [convert_to_openai_function(f) for f in functions]
llm_kwargs_: dict[str, Any] = {"functions": openai_functions, **llm_kwargs}
if len(openai_functions) == 1 and enforce_single_function_usage:
@@ -400,9 +401,8 @@ def create_structured_output_runnable(
# Backwards compatibility keys
unrecognized_keys = keys_in_kwargs - {"enforce_single_function_usage"}
if unrecognized_keys:
- raise TypeError(
- f"Got an unexpected keyword argument(s): {unrecognized_keys}."
- )
+ msg = f"Got an unexpected keyword argument(s): {unrecognized_keys}."
+ raise TypeError(msg)
return _create_openai_tools_runnable(
output_schema,
@@ -424,17 +424,19 @@ def create_structured_output_runnable(
)
elif mode == "openai-json":
if force_function_usage:
- raise ValueError(
+ msg = (
"enforce_single_function_usage is not supported for mode='openai-json'."
)
+ raise ValueError(msg)
return _create_openai_json_runnable(
output_schema, llm, prompt=prompt, output_parser=output_parser, **kwargs
)
else:
- raise ValueError(
+ msg = (
f"Invalid mode {mode}. Expected one of 'openai-tools', 'openai-functions', "
f"'openai-json'."
)
+ raise ValueError(msg)
def _create_openai_tools_runnable(
diff --git a/libs/langchain/langchain/chains/summarize/chain.py b/libs/langchain/langchain/chains/summarize/chain.py
index b5bccbd2d1..afe9a58eed 100644
--- a/libs/langchain/langchain/chains/summarize/chain.py
+++ b/libs/langchain/langchain/chains/summarize/chain.py
@@ -81,10 +81,11 @@ def _load_map_reduce_chain(
if collapse_prompt is None:
collapse_chain = None
if collapse_llm is not None:
- raise ValueError(
+ msg = (
"collapse_llm provided, but collapse_prompt was not: please "
"provide one or stop providing collapse_llm."
)
+ raise ValueError(msg)
else:
_collapse_llm = collapse_llm or llm
collapse_chain = StuffDocumentsChain(
@@ -161,8 +162,9 @@ def load_summarize_chain(
"refine": _load_refine_chain,
}
if chain_type not in loader_mapping:
- raise ValueError(
+ msg = (
f"Got unsupported chain type: {chain_type}. "
f"Should be one of {loader_mapping.keys()}"
)
+ raise ValueError(msg)
return loader_mapping[chain_type](llm, verbose=verbose, **kwargs)
diff --git a/libs/langchain/langchain/chat_models/base.py b/libs/langchain/langchain/chat_models/base.py
index bb8b899a58..59f32e3ab9 100644
--- a/libs/langchain/langchain/chat_models/base.py
+++ b/libs/langchain/langchain/chat_models/base.py
@@ -456,10 +456,11 @@ def _init_chat_model_helper(
return ChatPerplexity(model=model, **kwargs)
else:
supported = ", ".join(_SUPPORTED_PROVIDERS)
- raise ValueError(
+ msg = (
f"Unsupported {model_provider=}.\n\nSupported model providers are: "
f"{supported}"
)
+ raise ValueError(msg)
_SUPPORTED_PROVIDERS = {
@@ -521,10 +522,11 @@ def _parse_model(model: str, model_provider: Optional[str]) -> tuple[str, str]:
model = ":".join(model.split(":")[1:])
model_provider = model_provider or _attempt_infer_model_provider(model)
if not model_provider:
- raise ValueError(
+ msg = (
f"Unable to infer model provider for {model=}, please specify "
f"model_provider directly."
)
+ raise ValueError(msg)
model_provider = model_provider.replace("-", "_").lower()
return model, model_provider
@@ -532,9 +534,10 @@ def _parse_model(model: str, model_provider: Optional[str]) -> tuple[str, str]:
def _check_pkg(pkg: str, *, pkg_kebab: Optional[str] = None) -> None:
if not util.find_spec(pkg):
pkg_kebab = pkg_kebab if pkg_kebab is not None else pkg.replace("_", "-")
- raise ImportError(
+ msg = (
f"Unable to import {pkg}. Please install with `pip install -U {pkg_kebab}`"
)
+ raise ImportError(msg)
def _remove_prefix(s: str, prefix: str) -> str:
diff --git a/libs/langchain/langchain/embeddings/base.py b/libs/langchain/langchain/embeddings/base.py
index 7c20e91c77..308a0b5024 100644
--- a/libs/langchain/langchain/embeddings/base.py
+++ b/libs/langchain/langchain/embeddings/base.py
@@ -50,7 +50,7 @@ def _parse_model_string(model_name: str) -> tuple[str, str]:
"""
if ":" not in model_name:
providers = _SUPPORTED_PROVIDERS
- raise ValueError(
+ msg = (
f"Invalid model format '{model_name}'.\n"
f"Model name must be in format 'provider:model-name'\n"
f"Example valid model strings:\n"
@@ -59,19 +59,22 @@ def _parse_model_string(model_name: str) -> tuple[str, str]:
f" - cohere:embed-english-v3.0\n"
f"Supported providers: {providers}"
)
+ raise ValueError(msg)
provider, model = model_name.split(":", 1)
provider = provider.lower().strip()
model = model.strip()
if provider not in _SUPPORTED_PROVIDERS:
- raise ValueError(
+ msg = (
f"Provider '{provider}' is not supported.\n"
f"Supported providers and their required packages:\n"
f"{_get_provider_list()}"
)
+ raise ValueError(msg)
if not model:
- raise ValueError("Model name cannot be empty")
+ msg = "Model name cannot be empty"
+ raise ValueError(msg)
return provider, model
@@ -79,7 +82,8 @@ def _infer_model_and_provider(
model: str, *, provider: Optional[str] = None
) -> tuple[str, str]:
if not model.strip():
- raise ValueError("Model name cannot be empty")
+ msg = "Model name cannot be empty"
+ raise ValueError(msg)
if provider is None and ":" in model:
provider, model_name = _parse_model_string(model)
else:
@@ -88,20 +92,22 @@ def _infer_model_and_provider(
if not provider:
providers = _SUPPORTED_PROVIDERS
- raise ValueError(
+ msg = (
"Must specify either:\n"
"1. A model string in format 'provider:model-name'\n"
" Example: 'openai:text-embedding-3-small'\n"
"2. Or explicitly set provider from: "
f"{providers}"
)
+ raise ValueError(msg)
if provider not in _SUPPORTED_PROVIDERS:
- raise ValueError(
+ msg = (
f"Provider '{provider}' is not supported.\n"
f"Supported providers and their required packages:\n"
f"{_get_provider_list()}"
)
+ raise ValueError(msg)
return provider, model_name
@@ -109,10 +115,11 @@ def _infer_model_and_provider(
def _check_pkg(pkg: str) -> None:
"""Check if a package is installed."""
if not util.find_spec(pkg):
- raise ImportError(
+ msg = (
f"Could not import {pkg} python package. "
f"Please install it with `pip install {pkg}`"
)
+ raise ImportError(msg)
def init_embeddings(
@@ -172,9 +179,10 @@ def init_embeddings(
"""
if not model:
providers = _SUPPORTED_PROVIDERS.keys()
- raise ValueError(
+ msg = (
f"Must specify model name. Supported providers are: {', '.join(providers)}"
)
+ raise ValueError(msg)
provider, model_name = _infer_model_and_provider(model, provider=provider)
pkg = _SUPPORTED_PROVIDERS[provider]
@@ -213,11 +221,12 @@ def init_embeddings(
return OllamaEmbeddings(model=model_name, **kwargs)
else:
- raise ValueError(
+ msg = (
f"Provider '{provider}' is not supported.\n"
f"Supported providers and their required packages:\n"
f"{_get_provider_list()}"
)
+ raise ValueError(msg)
__all__ = [
diff --git a/libs/langchain/langchain/embeddings/cache.py b/libs/langchain/langchain/embeddings/cache.py
index 6da3465f05..2fc73627a4 100644
--- a/libs/langchain/langchain/embeddings/cache.py
+++ b/libs/langchain/langchain/embeddings/cache.py
@@ -67,7 +67,8 @@ def _make_default_key_encoder(namespace: str, algorithm: str) -> Callable[[str],
return f"{namespace}{hashlib.sha256(key.encode('utf-8')).hexdigest()}"
if algorithm == "sha512":
return f"{namespace}{hashlib.sha512(key.encode('utf-8')).hexdigest()}"
- raise ValueError(f"Unsupported algorithm: {algorithm}")
+ msg = f"Unsupported algorithm: {algorithm}"
+ raise ValueError(msg)
return _key_encoder
@@ -326,15 +327,17 @@ class CacheBackedEmbeddings(Embeddings):
# namespace.
# A user can handle namespacing in directly their custom key encoder.
if namespace:
- raise ValueError(
+ msg = (
"Do not supply `namespace` when using a custom key_encoder; "
"add any prefixing inside the encoder itself."
)
+ raise ValueError(msg)
else:
- raise ValueError(
+ msg = (
"key_encoder must be either 'blake2b', 'sha1', 'sha256', 'sha512' "
"or a callable that encodes keys."
)
+ raise ValueError(msg)
document_embedding_store = EncoderBackedStore[str, list[float]](
document_embedding_cache,
diff --git a/libs/langchain/langchain/evaluation/agents/trajectory_eval_chain.py b/libs/langchain/langchain/evaluation/agents/trajectory_eval_chain.py
index 68c2e9d2e2..dd0a2c5e89 100644
--- a/libs/langchain/langchain/evaluation/agents/trajectory_eval_chain.py
+++ b/libs/langchain/langchain/evaluation/agents/trajectory_eval_chain.py
@@ -66,9 +66,8 @@ class TrajectoryOutputParser(BaseOutputParser):
if the LLM's score is not a digit in the range 1-5.
"""
if "Score:" not in text:
- raise OutputParserException(
- f"Could not find score in model eval output: {text}"
- )
+ msg = f"Could not find score in model eval output: {text}"
+ raise OutputParserException(msg)
reasoning, score_str = text.split("Score: ", maxsplit=1)
@@ -82,15 +81,13 @@ class TrajectoryOutputParser(BaseOutputParser):
_score = re.search(r"(\d+(\.\d+)?)", score_str)
# If the score is not found or is a float, raise an exception.
if _score is None or "." in _score.group(1):
- raise OutputParserException(
- f"Score is not an integer digit in the range 1-5: {text}"
- )
+ msg = f"Score is not an integer digit in the range 1-5: {text}"
+ raise OutputParserException(msg)
score = int(_score.group(1))
# If the score is not in the range 1-5, raise an exception.
if not 1 <= score <= 5:
- raise OutputParserException(
- f"Score is not a digit in the range 1-5: {text}"
- )
+ msg = f"Score is not a digit in the range 1-5: {text}"
+ raise OutputParserException(msg)
normalized_score = (score - 1) / 4
return TrajectoryEval(score=normalized_score, reasoning=reasoning)
@@ -244,9 +241,8 @@ The following is the expected answer. Use this to measure correctness:
TrajectoryEvalChain: The TrajectoryEvalChain object.
"""
if not isinstance(llm, BaseChatModel):
- raise NotImplementedError(
- "Only chat models supported by the current trajectory eval"
- )
+ msg = "Only chat models supported by the current trajectory eval"
+ raise NotImplementedError(msg)
if agent_tools:
prompt = EVAL_CHAT_PROMPT
else:
diff --git a/libs/langchain/langchain/evaluation/comparison/eval_chain.py b/libs/langchain/langchain/evaluation/comparison/eval_chain.py
index 795aeef6b1..b70ef3758a 100644
--- a/libs/langchain/langchain/evaluation/comparison/eval_chain.py
+++ b/libs/langchain/langchain/evaluation/comparison/eval_chain.py
@@ -86,11 +86,12 @@ def resolve_pairwise_criteria(
}
else:
if not criteria:
- raise ValueError(
+ msg = (
"Criteria cannot be empty. "
"Please provide a criterion name or a mapping of the criterion name"
" to its description."
)
+ raise ValueError(msg)
criteria_ = dict(criteria)
return criteria_
@@ -132,11 +133,12 @@ class PairwiseStringResultOutputParser(BaseOutputParser[dict]):
verdict = match.group(1)
if not match or verdict not in {"A", "B", "C"}:
- raise ValueError(
+ msg = (
f"Invalid output: {text}. "
"Output must contain a double bracketed string\
with the verdict 'A', 'B', or 'C'."
)
+ raise ValueError(msg)
# C means the models are tied. Return 'None' meaning no preference
verdict_ = None if verdict == "C" else verdict
score = {
@@ -262,10 +264,11 @@ Performance may be significantly worse with other models."
expected_input_vars = {"prediction", "prediction_b", "input", "criteria"}
prompt_ = prompt or COMPARISON_TEMPLATE.partial(reference="")
if expected_input_vars != set(prompt_.input_variables):
- raise ValueError(
+ msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
+ raise ValueError(msg)
criteria_ = resolve_pairwise_criteria(criteria)
criteria_str = "\n".join(f"{k}: {v}" if v else k for k, v in criteria_.items())
criteria_str = CRITERIA_INSTRUCTIONS + criteria_str if criteria_str else ""
@@ -444,10 +447,11 @@ class LabeledPairwiseStringEvalChain(PairwiseStringEvalChain):
}
prompt_ = prompt or COMPARISON_TEMPLATE_WITH_REFERENCE
if expected_input_vars != set(prompt_.input_variables):
- raise ValueError(
+ msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
+ raise ValueError(msg)
criteria_ = resolve_pairwise_criteria(criteria)
criteria_str = "\n".join(f"{k}: {v}" for k, v in criteria_.items())
criteria_str = CRITERIA_INSTRUCTIONS + criteria_str if criteria_str else ""
diff --git a/libs/langchain/langchain/evaluation/criteria/eval_chain.py b/libs/langchain/langchain/evaluation/criteria/eval_chain.py
index 8b4aac3498..fcc85e6120 100644
--- a/libs/langchain/langchain/evaluation/criteria/eval_chain.py
+++ b/libs/langchain/langchain/evaluation/criteria/eval_chain.py
@@ -156,11 +156,12 @@ def resolve_criteria(
criteria_ = {criteria.name: criteria.critique_request}
else:
if not criteria:
- raise ValueError(
+ msg = (
"Criteria cannot be empty. "
"Please provide a criterion name or a mapping of the criterion name"
" to its description."
)
+ raise ValueError(msg)
criteria_ = dict(criteria)
return criteria_
@@ -276,10 +277,11 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
expected_input_vars = {"input", "output", "criteria"}
prompt_ = prompt or PROMPT
if expected_input_vars != set(prompt_.input_variables):
- raise ValueError(
+ msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
+ raise ValueError(msg)
return prompt_
@classmethod
@@ -360,12 +362,13 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
"""
prompt_ = cls._resolve_prompt(prompt)
if criteria == Criteria.CORRECTNESS:
- raise ValueError(
+ msg = (
"Correctness should not be used in the reference-free"
" 'criteria' evaluator (CriteriaEvalChain)."
" Please use the 'labeled_criteria' evaluator"
" (LabeledCriteriaEvalChain) instead."
)
+ raise ValueError(msg)
criteria_ = cls.resolve_criteria(criteria)
criteria_str = "\n".join(f"{k}: {v}" for k, v in criteria_.items())
prompt_ = prompt_.partial(criteria=criteria_str)
@@ -528,10 +531,11 @@ class LabeledCriteriaEvalChain(CriteriaEvalChain):
expected_input_vars = {"input", "output", "criteria", "reference"}
prompt_ = prompt or PROMPT_WITH_REFERENCES
if expected_input_vars != set(prompt_.input_variables):
- raise ValueError(
+ msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
+ raise ValueError(msg)
return prompt_
@classmethod
diff --git a/libs/langchain/langchain/evaluation/embedding_distance/base.py b/libs/langchain/langchain/evaluation/embedding_distance/base.py
index 5832ca6b5c..c072168194 100644
--- a/libs/langchain/langchain/evaluation/embedding_distance/base.py
+++ b/libs/langchain/langchain/evaluation/embedding_distance/base.py
@@ -26,9 +26,8 @@ def _import_numpy() -> Any:
return np
except ImportError as e:
- raise ImportError(
- "Could not import numpy, please install with `pip install numpy`."
- ) from e
+ msg = "Could not import numpy, please install with `pip install numpy`."
+ raise ImportError(msg) from e
logger = logging.getLogger(__name__)
@@ -64,10 +63,11 @@ def _embedding_factory() -> Embeddings:
OpenAIEmbeddings,
)
except ImportError:
- raise ImportError(
+ msg = (
"Could not import OpenAIEmbeddings. Please install the "
"OpenAIEmbeddings package using `pip install langchain-openai`."
)
+ raise ImportError(msg)
return OpenAIEmbeddings()
@@ -130,21 +130,23 @@ class _EmbeddingDistanceChainMixin(Chain):
pass
if not types_:
- raise ImportError(
+ msg = (
"Could not import OpenAIEmbeddings. Please install the "
"OpenAIEmbeddings package using `pip install langchain-openai`."
)
+ raise ImportError(msg)
if isinstance(embeddings, tuple(types_)):
try:
import tiktoken # noqa: F401
except ImportError:
- raise ImportError(
+ msg = (
"The tiktoken library is required to use the default "
"OpenAI embeddings with embedding distance evaluators."
" Please either manually select a different Embeddings object"
" or install tiktoken using `pip install tiktoken`."
)
+ raise ImportError(msg)
return values
model_config = ConfigDict(
@@ -185,7 +187,8 @@ class _EmbeddingDistanceChainMixin(Chain):
if metric in metrics:
return metrics[metric]
else:
- raise ValueError(f"Invalid metric: {metric}")
+ msg = f"Invalid metric: {metric}"
+ raise ValueError(msg)
@staticmethod
def _cosine_distance(a: Any, b: Any) -> Any:
@@ -201,11 +204,12 @@ class _EmbeddingDistanceChainMixin(Chain):
try:
from langchain_community.utils.math import cosine_similarity
except ImportError:
- raise ImportError(
+ msg = (
"The cosine_similarity function is required to compute cosine distance."
" Please install the langchain-community package using"
" `pip install langchain-community`."
)
+ raise ImportError(msg)
return 1.0 - cosine_similarity(a, b)
@staticmethod
diff --git a/libs/langchain/langchain/evaluation/loading.py b/libs/langchain/langchain/evaluation/loading.py
index 81eb421668..67897fe457 100644
--- a/libs/langchain/langchain/evaluation/loading.py
+++ b/libs/langchain/langchain/evaluation/loading.py
@@ -62,10 +62,11 @@ def load_dataset(uri: str) -> list[dict]:
try:
from datasets import load_dataset
except ImportError:
- raise ImportError(
+ msg = (
"load_dataset requires the `datasets` package."
" Please install with `pip install datasets`"
)
+ raise ImportError(msg)
dataset = load_dataset(f"LangChainDatasets/{uri}")
return [d for d in dataset["train"]]
@@ -125,10 +126,11 @@ def load_evaluator(
>>> evaluator = load_evaluator(EvaluatorType.QA)
"""
if evaluator not in _EVALUATOR_MAP:
- raise ValueError(
+ msg = (
f"Unknown evaluator type: {evaluator}"
f"\nValid types are: {list(_EVALUATOR_MAP.keys())}"
)
+ raise ValueError(msg)
evaluator_cls = _EVALUATOR_MAP[evaluator]
if issubclass(evaluator_cls, LLMEvalChain):
try:
@@ -140,23 +142,25 @@ def load_evaluator(
ChatOpenAI,
)
except ImportError:
- raise ImportError(
+ msg = (
"Could not import langchain_openai or fallback onto "
"langchain_community. Please install langchain_openai "
"or specify a language model explicitly. "
"It's recommended to install langchain_openai AND "
"specify a language model explicitly."
)
+ raise ImportError(msg)
llm = llm or ChatOpenAI(model="gpt-4", seed=42, temperature=0)
except Exception as e:
- raise ValueError(
+ msg = (
f"Evaluation with the {evaluator_cls} requires a "
"language model to function."
" Failed to create the default 'gpt-4' model."
" Please manually provide an evaluation LLM"
" or check your openai credentials."
- ) from e
+ )
+ raise ValueError(msg) from e
return evaluator_cls.from_llm(llm=llm, **kwargs)
else:
return evaluator_cls(**kwargs)
diff --git a/libs/langchain/langchain/evaluation/parsing/json_distance.py b/libs/langchain/langchain/evaluation/parsing/json_distance.py
index 8aa1fb392b..48efdb6c45 100644
--- a/libs/langchain/langchain/evaluation/parsing/json_distance.py
+++ b/libs/langchain/langchain/evaluation/parsing/json_distance.py
@@ -48,12 +48,13 @@ class JsonEditDistanceEvaluator(StringEvaluator):
try:
from rapidfuzz import distance as rfd
except ImportError:
- raise ImportError(
+ msg = (
"The default string_distance operator for the "
" JsonEditDistanceEvaluator requires installation of "
"the rapidfuzz package. "
"Please install it with `pip install rapidfuzz`."
)
+ raise ImportError(msg)
self._string_distance = rfd.DamerauLevenshtein.normalized_distance
if canonicalize is not None:
self._canonicalize = canonicalize
diff --git a/libs/langchain/langchain/evaluation/parsing/json_schema.py b/libs/langchain/langchain/evaluation/parsing/json_schema.py
index ff3d3f8027..38772dd8e3 100644
--- a/libs/langchain/langchain/evaluation/parsing/json_schema.py
+++ b/libs/langchain/langchain/evaluation/parsing/json_schema.py
@@ -45,10 +45,11 @@ class JsonSchemaEvaluator(StringEvaluator):
try:
import jsonschema # noqa: F401
except ImportError:
- raise ImportError(
+ msg = (
"The JsonSchemaEvaluator requires the jsonschema package."
" Please install it with `pip install jsonschema`."
)
+ raise ImportError(msg)
@property
def requires_input(self) -> bool:
diff --git a/libs/langchain/langchain/evaluation/qa/eval_chain.py b/libs/langchain/langchain/evaluation/qa/eval_chain.py
index 31399c1e4a..ce3ad0c339 100644
--- a/libs/langchain/langchain/evaluation/qa/eval_chain.py
+++ b/libs/langchain/langchain/evaluation/qa/eval_chain.py
@@ -119,10 +119,11 @@ class QAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):
prompt = prompt or PROMPT
expected_input_vars = {"query", "answer", "result"}
if expected_input_vars != set(prompt.input_variables):
- raise ValueError(
+ msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt.input_variables}"
)
+ raise ValueError(msg)
return cls(llm=llm, prompt=prompt, **kwargs)
def evaluate(
@@ -231,10 +232,11 @@ class ContextQAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):
def _validate_input_vars(cls, prompt: PromptTemplate) -> None:
expected_input_vars = {"query", "context", "result"}
if expected_input_vars != set(prompt.input_variables):
- raise ValueError(
+ msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt.input_variables}"
)
+ raise ValueError(msg)
@property
def evaluation_name(self) -> str:
diff --git a/libs/langchain/langchain/evaluation/schema.py b/libs/langchain/langchain/evaluation/schema.py
index 24796e87f9..ce29981e93 100644
--- a/libs/langchain/langchain/evaluation/schema.py
+++ b/libs/langchain/langchain/evaluation/schema.py
@@ -121,11 +121,13 @@ class _EvalArgsMixin:
or if the evaluator requires a reference label but none is provided.
"""
if self.requires_input and input is None:
- raise ValueError(f"{self.__class__.__name__} requires an input string.")
+ msg = f"{self.__class__.__name__} requires an input string."
+ raise ValueError(msg)
elif input is not None and not self.requires_input:
warn(self._skip_input_warning)
if self.requires_reference and reference is None:
- raise ValueError(f"{self.__class__.__name__} requires a reference string.")
+ msg = f"{self.__class__.__name__} requires a reference string."
+ raise ValueError(msg)
elif reference is not None and not self.requires_reference:
warn(self._skip_reference_warning)
diff --git a/libs/langchain/langchain/evaluation/scoring/eval_chain.py b/libs/langchain/langchain/evaluation/scoring/eval_chain.py
index e00f7fd912..316f6391d6 100644
--- a/libs/langchain/langchain/evaluation/scoring/eval_chain.py
+++ b/libs/langchain/langchain/evaluation/scoring/eval_chain.py
@@ -86,11 +86,12 @@ def resolve_criteria(
}
else:
if not criteria:
- raise ValueError(
+ msg = (
"Criteria cannot be empty. "
"Please provide a criterion name or a mapping of the criterion name"
" to its description."
)
+ raise ValueError(msg)
criteria_ = dict(criteria)
return criteria_
@@ -132,11 +133,12 @@ class ScoreStringResultOutputParser(BaseOutputParser[dict]):
verdict = match.group(1)
if not match or verdict not in list("123456789") + ["10"]:
- raise ValueError(
+ msg = (
f"Invalid output: {text}. "
"Output must contain a double bracketed string\
with the verdict between 1 and 10."
)
+ raise ValueError(msg)
return {
"reasoning": text,
@@ -265,10 +267,11 @@ Performance may be significantly worse with other models."
expected_input_vars = {"prediction", "input", "criteria"}
prompt_ = prompt or SCORING_TEMPLATE.partial(reference="")
if expected_input_vars != set(prompt_.input_variables):
- raise ValueError(
+ msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
+ raise ValueError(msg)
criteria_ = resolve_criteria(criteria)
criteria_str = "\n".join(
f"{k}: {v}" if v else k for k, v in criteria_.items()
@@ -448,10 +451,11 @@ class LabeledScoreStringEvalChain(ScoreStringEvalChain):
}
prompt_ = prompt or SCORING_TEMPLATE_WITH_REFERENCE
if expected_input_vars != set(prompt_.input_variables):
- raise ValueError(
+ msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
+ raise ValueError(msg)
criteria_ = resolve_criteria(criteria)
criteria_str = "\n".join(f"{k}: {v}" for k, v in criteria_.items()).strip()
criteria_str = (
diff --git a/libs/langchain/langchain/evaluation/string_distance/base.py b/libs/langchain/langchain/evaluation/string_distance/base.py
index 01d309fffb..418df7fc70 100644
--- a/libs/langchain/langchain/evaluation/string_distance/base.py
+++ b/libs/langchain/langchain/evaluation/string_distance/base.py
@@ -29,10 +29,11 @@ def _load_rapidfuzz() -> Any:
try:
import rapidfuzz
except ImportError:
- raise ImportError(
+ msg = (
"Please install the rapidfuzz library to use the FuzzyMatchStringEvaluator."
"Please install it with `pip install rapidfuzz`."
)
+ raise ImportError(msg)
return rapidfuzz.distance
@@ -128,10 +129,11 @@ class _RapidFuzzChainMixin(Chain):
StringDistance.INDEL: rf_distance.Indel,
}
if distance not in module_map:
- raise ValueError(
+ msg = (
f"Invalid distance metric: {distance}"
f"\nMust be one of: {list(StringDistance)}"
)
+ raise ValueError(msg)
module = module_map[distance]
if normalize_score:
return module.normalized_distance
diff --git a/libs/langchain/langchain/hub.py b/libs/langchain/langchain/hub.py
index d4323b9c7d..a06064b4b1 100644
--- a/libs/langchain/langchain/hub.py
+++ b/libs/langchain/langchain/hub.py
@@ -31,10 +31,11 @@ def _get_client(
return LangChainHubClient(api_url, api_key=api_key)
except ImportError as e:
- raise ImportError(
+ msg = (
"Could not import langsmith or langchainhub (deprecated),"
"please install with `pip install langsmith`."
- ) from e
+ )
+ raise ImportError(msg) from e
def push(
diff --git a/libs/langchain/langchain/indexes/_sql_record_manager.py b/libs/langchain/langchain/indexes/_sql_record_manager.py
index d18546f081..5270417ea7 100644
--- a/libs/langchain/langchain/indexes/_sql_record_manager.py
+++ b/libs/langchain/langchain/indexes/_sql_record_manager.py
@@ -119,10 +119,12 @@ class SQLRecordManager(RecordManager):
"""
super().__init__(namespace=namespace)
if db_url is None and engine is None:
- raise ValueError("Must specify either db_url or engine")
+ msg = "Must specify either db_url or engine"
+ raise ValueError(msg)
if db_url is not None and engine is not None:
- raise ValueError("Must specify either db_url or engine, not both")
+ msg = "Must specify either db_url or engine, not both"
+ raise ValueError(msg)
_engine: Union[Engine, AsyncEngine]
if db_url:
@@ -134,7 +136,8 @@ class SQLRecordManager(RecordManager):
_engine = engine
else:
- raise AssertionError("Something went wrong with configuration of engine.")
+ msg = "Something went wrong with configuration of engine."
+ raise AssertionError(msg)
_session_factory: Union[sessionmaker[Session], async_sessionmaker[AsyncSession]]
if isinstance(_engine, AsyncEngine):
@@ -149,7 +152,8 @@ class SQLRecordManager(RecordManager):
def create_schema(self) -> None:
"""Create the database schema."""
if isinstance(self.engine, AsyncEngine):
- raise AssertionError("This method is not supported for async engines.")
+ msg = "This method is not supported for async engines."
+ raise AssertionError(msg)
Base.metadata.create_all(self.engine)
@@ -157,7 +161,8 @@ class SQLRecordManager(RecordManager):
"""Create the database schema."""
if not isinstance(self.engine, AsyncEngine):
- raise AssertionError("This method is not supported for sync engines.")
+ msg = "This method is not supported for sync engines."
+ raise AssertionError(msg)
async with self.engine.begin() as session:
await session.run_sync(Base.metadata.create_all)
@@ -167,7 +172,8 @@ class SQLRecordManager(RecordManager):
"""Create a session and close it after use."""
if isinstance(self.session_factory, async_sessionmaker):
- raise AssertionError("This method is not supported for async engines.")
+ msg = "This method is not supported for async engines."
+ raise AssertionError(msg)
session = self.session_factory()
try:
@@ -180,7 +186,8 @@ class SQLRecordManager(RecordManager):
"""Create a session and close it after use."""
if not isinstance(self.session_factory, async_sessionmaker):
- raise AssertionError("This method is not supported for sync engines.")
+ msg = "This method is not supported for sync engines."
+ raise AssertionError(msg)
async with self.session_factory() as session:
yield session
@@ -206,13 +213,15 @@ class SQLRecordManager(RecordManager):
elif self.dialect == "postgresql":
query = text("SELECT EXTRACT (EPOCH FROM CURRENT_TIMESTAMP);")
else:
- raise NotImplementedError(f"Not implemented for dialect {self.dialect}")
+ msg = f"Not implemented for dialect {self.dialect}"
+ raise NotImplementedError(msg)
dt = session.execute(query).scalar()
if isinstance(dt, decimal.Decimal):
dt = float(dt)
if not isinstance(dt, float):
- raise AssertionError(f"Unexpected type for datetime: {type(dt)}")
+ msg = f"Unexpected type for datetime: {type(dt)}"
+ raise AssertionError(msg)
return dt
async def aget_time(self) -> float:
@@ -236,14 +245,16 @@ class SQLRecordManager(RecordManager):
elif self.dialect == "postgresql":
query = text("SELECT EXTRACT (EPOCH FROM CURRENT_TIMESTAMP);")
else:
- raise NotImplementedError(f"Not implemented for dialect {self.dialect}")
+ msg = f"Not implemented for dialect {self.dialect}"
+ raise NotImplementedError(msg)
dt = (await session.execute(query)).scalar_one_or_none()
if isinstance(dt, decimal.Decimal):
dt = float(dt)
if not isinstance(dt, float):
- raise AssertionError(f"Unexpected type for datetime: {type(dt)}")
+ msg = f"Unexpected type for datetime: {type(dt)}"
+ raise AssertionError(msg)
return dt
def update(
@@ -258,10 +269,11 @@ class SQLRecordManager(RecordManager):
group_ids = [None] * len(keys)
if len(keys) != len(group_ids):
- raise ValueError(
+ msg = (
f"Number of keys ({len(keys)}) does not match number of "
f"group_ids ({len(group_ids)})"
)
+ raise ValueError(msg)
# Get the current time from the server.
# This makes an extra round trip to the server, should not be a big deal
@@ -274,7 +286,8 @@ class SQLRecordManager(RecordManager):
if time_at_least and update_time < time_at_least:
# Safeguard against time sync issues
- raise AssertionError(f"Time sync issue: {update_time} < {time_at_least}")
+ msg = f"Time sync issue: {update_time} < {time_at_least}"
+ raise AssertionError(msg)
records_to_upsert = [
{
@@ -320,7 +333,8 @@ class SQLRecordManager(RecordManager):
),
)
else:
- raise NotImplementedError(f"Unsupported dialect {self.dialect}")
+ msg = f"Unsupported dialect {self.dialect}"
+ raise NotImplementedError(msg)
session.execute(stmt)
session.commit()
@@ -337,10 +351,11 @@ class SQLRecordManager(RecordManager):
group_ids = [None] * len(keys)
if len(keys) != len(group_ids):
- raise ValueError(
+ msg = (
f"Number of keys ({len(keys)}) does not match number of "
f"group_ids ({len(group_ids)})"
)
+ raise ValueError(msg)
# Get the current time from the server.
# This makes an extra round trip to the server, should not be a big deal
@@ -353,7 +368,8 @@ class SQLRecordManager(RecordManager):
if time_at_least and update_time < time_at_least:
# Safeguard against time sync issues
- raise AssertionError(f"Time sync issue: {update_time} < {time_at_least}")
+ msg = f"Time sync issue: {update_time} < {time_at_least}"
+ raise AssertionError(msg)
records_to_upsert = [
{
@@ -399,7 +415,8 @@ class SQLRecordManager(RecordManager):
),
)
else:
- raise NotImplementedError(f"Unsupported dialect {self.dialect}")
+ msg = f"Unsupported dialect {self.dialect}"
+ raise NotImplementedError(msg)
await session.execute(stmt)
await session.commit()
diff --git a/libs/langchain/langchain/indexes/vectorstore.py b/libs/langchain/langchain/indexes/vectorstore.py
index db2d8fc506..5549b33ae7 100644
--- a/libs/langchain/langchain/indexes/vectorstore.py
+++ b/libs/langchain/langchain/indexes/vectorstore.py
@@ -48,13 +48,14 @@ class VectorStoreIndexWrapper(BaseModel):
The result string from the RetrievalQA chain.
"""
if llm is None:
- raise NotImplementedError(
+ msg = (
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"llm = OpenAI(temperature=0)"
)
+ raise NotImplementedError(msg)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQA.from_chain_type(
llm, retriever=self.vectorstore.as_retriever(**retriever_kwargs), **kwargs
@@ -80,13 +81,14 @@ class VectorStoreIndexWrapper(BaseModel):
The asynchronous result string from the RetrievalQA chain.
"""
if llm is None:
- raise NotImplementedError(
+ msg = (
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"llm = OpenAI(temperature=0)"
)
+ raise NotImplementedError(msg)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQA.from_chain_type(
llm, retriever=self.vectorstore.as_retriever(**retriever_kwargs), **kwargs
@@ -112,13 +114,14 @@ class VectorStoreIndexWrapper(BaseModel):
A dictionary containing the answer and source documents.
"""
if llm is None:
- raise NotImplementedError(
+ msg = (
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"llm = OpenAI(temperature=0)"
)
+ raise NotImplementedError(msg)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQAWithSourcesChain.from_chain_type(
llm, retriever=self.vectorstore.as_retriever(**retriever_kwargs), **kwargs
@@ -144,13 +147,14 @@ class VectorStoreIndexWrapper(BaseModel):
A dictionary containing the answer and source documents.
"""
if llm is None:
- raise NotImplementedError(
+ msg = (
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"llm = OpenAI(temperature=0)"
)
+ raise NotImplementedError(msg)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQAWithSourcesChain.from_chain_type(
llm, retriever=self.vectorstore.as_retriever(**retriever_kwargs), **kwargs
@@ -165,9 +169,8 @@ def _get_in_memory_vectorstore() -> type[VectorStore]:
try:
from langchain_community.vectorstores.inmemory import InMemoryVectorStore
except ImportError:
- raise ImportError(
- "Please install langchain-community to use the InMemoryVectorStore."
- )
+ msg = "Please install langchain-community to use the InMemoryVectorStore."
+ raise ImportError(msg)
warnings.warn(
"Using InMemoryVectorStore as the default vectorstore."
"This memory store won't persist data. You should explicitly"
diff --git a/libs/langchain/langchain/memory/buffer.py b/libs/langchain/langchain/memory/buffer.py
index 010d61f2ea..394acdf2bd 100644
--- a/libs/langchain/langchain/memory/buffer.py
+++ b/libs/langchain/langchain/memory/buffer.py
@@ -121,9 +121,8 @@ class ConversationStringBufferMemory(BaseMemory):
def validate_chains(cls, values: dict) -> dict:
"""Validate that return messages is not True."""
if values.get("return_messages", False):
- raise ValueError(
- "return_messages must be False for ConversationStringBufferMemory"
- )
+ msg = "return_messages must be False for ConversationStringBufferMemory"
+ raise ValueError(msg)
return values
@property
@@ -149,7 +148,8 @@ class ConversationStringBufferMemory(BaseMemory):
prompt_input_key = self.input_key
if self.output_key is None:
if len(outputs) != 1:
- raise ValueError(f"One output key expected, got {outputs.keys()}")
+ msg = f"One output key expected, got {outputs.keys()}"
+ raise ValueError(msg)
output_key = list(outputs.keys())[0]
else:
output_key = self.output_key
diff --git a/libs/langchain/langchain/memory/chat_memory.py b/libs/langchain/langchain/memory/chat_memory.py
index da14dd0000..f8bfde0db1 100644
--- a/libs/langchain/langchain/memory/chat_memory.py
+++ b/libs/langchain/langchain/memory/chat_memory.py
@@ -58,11 +58,12 @@ class BaseChatMemory(BaseMemory, ABC):
f" If this is not desired, please manually set 'output_key'."
)
else:
- raise ValueError(
+ msg = (
f"Got multiple output keys: {outputs.keys()}, cannot "
f"determine which to store in memory. Please set the "
f"'output_key' explicitly."
)
+ raise ValueError(msg)
else:
output_key = self.output_key
return inputs[prompt_input_key], outputs[output_key]
diff --git a/libs/langchain/langchain/memory/combined.py b/libs/langchain/langchain/memory/combined.py
index 8f737eaa46..06fe6febfe 100644
--- a/libs/langchain/langchain/memory/combined.py
+++ b/libs/langchain/langchain/memory/combined.py
@@ -22,10 +22,11 @@ class CombinedMemory(BaseMemory):
for val in value:
overlap = all_variables.intersection(val.memory_variables)
if overlap:
- raise ValueError(
+ msg = (
f"The same variables {overlap} are found in multiple"
"memory object, which is not allowed by CombinedMemory."
)
+ raise ValueError(msg)
all_variables |= set(val.memory_variables)
return value
@@ -65,9 +66,8 @@ class CombinedMemory(BaseMemory):
data = memory.load_memory_variables(inputs)
for key, value in data.items():
if key in memory_data:
- raise ValueError(
- f"The variable {key} is repeated in the CombinedMemory."
- )
+ msg = f"The variable {key} is repeated in the CombinedMemory."
+ raise ValueError(msg)
memory_data[key] = value
return memory_data
diff --git a/libs/langchain/langchain/memory/entity.py b/libs/langchain/langchain/memory/entity.py
index 632c171474..8c199ccac3 100644
--- a/libs/langchain/langchain/memory/entity.py
+++ b/libs/langchain/langchain/memory/entity.py
@@ -116,10 +116,11 @@ class UpstashRedisEntityStore(BaseEntityStore):
try:
from upstash_redis import Redis
except ImportError:
- raise ImportError(
+ msg = (
"Could not import upstash_redis python package. "
"Please install it with `pip install upstash_redis`."
)
+ raise ImportError(msg)
super().__init__(*args, **kwargs)
@@ -207,20 +208,22 @@ class RedisEntityStore(BaseEntityStore):
try:
import redis
except ImportError:
- raise ImportError(
+ msg = (
"Could not import redis python package. "
"Please install it with `pip install redis`."
)
+ raise ImportError(msg)
super().__init__(*args, **kwargs)
try:
from langchain_community.utilities.redis import get_client
except ImportError:
- raise ImportError(
+ msg = (
"Could not import langchain_community.utilities.redis.get_client. "
"Please install it with `pip install langchain-community`."
)
+ raise ImportError(msg)
try:
self.redis_client = get_client(redis_url=url, decode_responses=True)
@@ -303,17 +306,17 @@ class SQLiteEntityStore(BaseEntityStore):
try:
import sqlite3
except ImportError:
- raise ImportError(
+ msg = (
"Could not import sqlite3 python package. "
"Please install it with `pip install sqlite3`."
)
+ raise ImportError(msg)
# Basic validation to prevent obviously malicious table/session names
if not table_name.isidentifier() or not session_id.isidentifier():
# Since we validate here, we can safely suppress the S608 bandit warning
- raise ValueError(
- "Table name and session ID must be valid Python identifiers."
- )
+ msg = "Table name and session ID must be valid Python identifiers."
+ raise ValueError(msg)
self.conn = sqlite3.connect(db_file)
self.session_id = session_id
diff --git a/libs/langchain/langchain/memory/summary.py b/libs/langchain/langchain/memory/summary.py
index c2bb083c8c..c604704e39 100644
--- a/libs/langchain/langchain/memory/summary.py
+++ b/libs/langchain/langchain/memory/summary.py
@@ -116,10 +116,11 @@ class ConversationSummaryMemory(BaseChatMemory, SummarizerMixin):
prompt_variables = values["prompt"].input_variables
expected_keys = {"summary", "new_lines"}
if expected_keys != set(prompt_variables):
- raise ValueError(
+ msg = (
"Got unexpected prompt input variables. The prompt expects "
f"{prompt_variables}, but it should have {expected_keys}."
)
+ raise ValueError(msg)
return values
def save_context(self, inputs: dict[str, Any], outputs: dict[str, str]) -> None:
diff --git a/libs/langchain/langchain/memory/summary_buffer.py b/libs/langchain/langchain/memory/summary_buffer.py
index ed5b79103c..5dce678f22 100644
--- a/libs/langchain/langchain/memory/summary_buffer.py
+++ b/libs/langchain/langchain/memory/summary_buffer.py
@@ -84,10 +84,11 @@ class ConversationSummaryBufferMemory(BaseChatMemory, SummarizerMixin):
prompt_variables = values["prompt"].input_variables
expected_keys = {"summary", "new_lines"}
if expected_keys != set(prompt_variables):
- raise ValueError(
+ msg = (
"Got unexpected prompt input variables. The prompt expects "
f"{prompt_variables}, but it should have {expected_keys}."
)
+ raise ValueError(msg)
return values
def save_context(self, inputs: dict[str, Any], outputs: dict[str, str]) -> None:
diff --git a/libs/langchain/langchain/memory/utils.py b/libs/langchain/langchain/memory/utils.py
index b3c8a5bb23..79b0504415 100644
--- a/libs/langchain/langchain/memory/utils.py
+++ b/libs/langchain/langchain/memory/utils.py
@@ -16,5 +16,6 @@ def get_prompt_input_key(inputs: dict[str, Any], memory_variables: list[str]) ->
# format the prompt.
prompt_input_keys = list(set(inputs).difference(memory_variables + ["stop"]))
if len(prompt_input_keys) != 1:
- raise ValueError(f"One input key expected got {prompt_input_keys}")
+ msg = f"One input key expected got {prompt_input_keys}"
+ raise ValueError(msg)
return prompt_input_keys[0]
diff --git a/libs/langchain/langchain/model_laboratory.py b/libs/langchain/langchain/model_laboratory.py
index 6ade9dbc23..30f7c6de1a 100644
--- a/libs/langchain/langchain/model_laboratory.py
+++ b/libs/langchain/langchain/model_laboratory.py
@@ -34,24 +34,28 @@ class ModelLaboratory:
"""
for chain in chains:
if not isinstance(chain, Chain):
- raise ValueError(
+ msg = (
"ModelLaboratory should now be initialized with Chains. "
"If you want to initialize with LLMs, use the `from_llms` method "
"instead (`ModelLaboratory.from_llms(...)`)"
)
+ raise ValueError(msg)
if len(chain.input_keys) != 1:
- raise ValueError(
+ msg = (
"Currently only support chains with one input variable, "
f"got {chain.input_keys}"
)
+ raise ValueError(msg)
if len(chain.output_keys) != 1:
- raise ValueError(
+ msg = (
"Currently only support chains with one output variable, "
f"got {chain.output_keys}"
)
+ raise ValueError(msg)
if names is not None:
if len(names) != len(chains):
- raise ValueError("Length of chains does not match length of names.")
+ msg = "Length of chains does not match length of names."
+ raise ValueError(msg)
self.chains = chains
chain_range = [str(i) for i in range(len(self.chains))]
self.chain_colors = get_color_mapping(chain_range)
diff --git a/libs/langchain/langchain/output_parsers/boolean.py b/libs/langchain/langchain/output_parsers/boolean.py
index 5114b975a7..740ed9c897 100644
--- a/libs/langchain/langchain/output_parsers/boolean.py
+++ b/libs/langchain/langchain/output_parsers/boolean.py
@@ -28,22 +28,25 @@ class BooleanOutputParser(BaseOutputParser[bool]):
}
if self.true_val.upper() in truthy:
if self.false_val.upper() in truthy:
- raise ValueError(
+ msg = (
f"Ambiguous response. Both {self.true_val} and {self.false_val} "
f"in received: {text}."
)
+ raise ValueError(msg)
return True
elif self.false_val.upper() in truthy:
if self.true_val.upper() in truthy:
- raise ValueError(
+ msg = (
f"Ambiguous response. Both {self.true_val} and {self.false_val} "
f"in received: {text}."
)
+ raise ValueError(msg)
return False
- raise ValueError(
+ msg = (
f"BooleanOutputParser expected output value to include either "
f"{self.true_val} or {self.false_val}. Received {text}."
)
+ raise ValueError(msg)
@property
def _type(self) -> str:
diff --git a/libs/langchain/langchain/output_parsers/combining.py b/libs/langchain/langchain/output_parsers/combining.py
index 295bd55ff2..b4fa6b4b82 100644
--- a/libs/langchain/langchain/output_parsers/combining.py
+++ b/libs/langchain/langchain/output_parsers/combining.py
@@ -20,12 +20,15 @@ class CombiningOutputParser(BaseOutputParser[dict[str, Any]]):
"""Validate the parsers."""
parsers = values["parsers"]
if len(parsers) < 2:
- raise ValueError("Must have at least two parsers")
+ msg = "Must have at least two parsers"
+ raise ValueError(msg)
for parser in parsers:
if parser._type == "combining":
- raise ValueError("Cannot nest combining parsers")
+ msg = "Cannot nest combining parsers"
+ raise ValueError(msg)
if parser._type == "list":
- raise ValueError("Cannot combine list parsers")
+ msg = "Cannot combine list parsers"
+ raise ValueError(msg)
return values
@property
diff --git a/libs/langchain/langchain/output_parsers/datetime.py b/libs/langchain/langchain/output_parsers/datetime.py
index b9602072f6..3ad2e02aec 100644
--- a/libs/langchain/langchain/output_parsers/datetime.py
+++ b/libs/langchain/langchain/output_parsers/datetime.py
@@ -50,9 +50,8 @@ class DatetimeOutputParser(BaseOutputParser[datetime]):
try:
return datetime.strptime(response.strip(), self.format)
except ValueError as e:
- raise OutputParserException(
- f"Could not parse datetime string: {response}"
- ) from e
+ msg = f"Could not parse datetime string: {response}"
+ raise OutputParserException(msg) from e
@property
def _type(self) -> str:
diff --git a/libs/langchain/langchain/output_parsers/enum.py b/libs/langchain/langchain/output_parsers/enum.py
index 7100872d6f..5ef74c2219 100644
--- a/libs/langchain/langchain/output_parsers/enum.py
+++ b/libs/langchain/langchain/output_parsers/enum.py
@@ -15,7 +15,8 @@ class EnumOutputParser(BaseOutputParser[Enum]):
def raise_deprecation(cls, values: dict) -> dict:
enum = values["enum"]
if not all(isinstance(e.value, str) for e in enum):
- raise ValueError("Enum values must be strings")
+ msg = "Enum values must be strings"
+ raise ValueError(msg)
return values
@property
@@ -26,10 +27,11 @@ class EnumOutputParser(BaseOutputParser[Enum]):
try:
return self.enum(response.strip())
except ValueError:
- raise OutputParserException(
+ msg = (
f"Response '{response}' is not one of the "
f"expected values: {self._valid_values}"
)
+ raise OutputParserException(msg)
def get_format_instructions(self) -> str:
return f"Select one of the following options: {', '.join(self._valid_values)}"
diff --git a/libs/langchain/langchain/output_parsers/fix.py b/libs/langchain/langchain/output_parsers/fix.py
index c5c3921a47..6e30ebee39 100644
--- a/libs/langchain/langchain/output_parsers/fix.py
+++ b/libs/langchain/langchain/output_parsers/fix.py
@@ -97,7 +97,8 @@ class OutputFixingParser(BaseOutputParser[T]):
)
)
- raise OutputParserException("Failed to parse")
+ msg = "Failed to parse"
+ raise OutputParserException(msg)
async def aparse(self, completion: str) -> T:
retries = 0
@@ -134,7 +135,8 @@ class OutputFixingParser(BaseOutputParser[T]):
)
)
- raise OutputParserException("Failed to parse")
+ msg = "Failed to parse"
+ raise OutputParserException(msg)
def get_format_instructions(self) -> str:
return self.parser.get_format_instructions()
diff --git a/libs/langchain/langchain/output_parsers/loading.py b/libs/langchain/langchain/output_parsers/loading.py
index b25710c123..1cb82ae0e9 100644
--- a/libs/langchain/langchain/output_parsers/loading.py
+++ b/libs/langchain/langchain/output_parsers/loading.py
@@ -17,6 +17,7 @@ def load_output_parser(config: dict) -> dict:
if output_parser_type == "regex_parser":
output_parser = RegexParser(**_config)
else:
- raise ValueError(f"Unsupported output parser {output_parser_type}")
+ msg = f"Unsupported output parser {output_parser_type}"
+ raise ValueError(msg)
config["output_parsers"] = output_parser
return config
diff --git a/libs/langchain/langchain/output_parsers/pandas_dataframe.py b/libs/langchain/langchain/output_parsers/pandas_dataframe.py
index 5afc80d646..3c0bc96c19 100644
--- a/libs/langchain/langchain/output_parsers/pandas_dataframe.py
+++ b/libs/langchain/langchain/output_parsers/pandas_dataframe.py
@@ -24,12 +24,12 @@ class PandasDataFrameOutputParser(BaseOutputParser[dict[str, Any]]):
if issubclass(type(val), pd.DataFrame):
return val
if pd.DataFrame(val).empty:
- raise ValueError("DataFrame cannot be empty.")
+ msg = "DataFrame cannot be empty."
+ raise ValueError(msg)
- raise TypeError(
- "Wrong type for 'dataframe', must be a subclass \
+ msg = "Wrong type for 'dataframe', must be a subclass \
of Pandas DataFrame (pd.DataFrame)"
- )
+ raise TypeError(msg)
def parse_array(
self, array: str, original_request_params: str
@@ -46,35 +46,31 @@ class PandasDataFrameOutputParser(BaseOutputParser[dict[str, Any]]):
start, end = map(int, match.groups())
parsed_array = list(range(start, end + 1))
else:
- raise OutputParserException(
- f"Unable to parse the array provided in {array}. \
+ msg = f"Unable to parse the array provided in {array}. \
Please check the format instructions."
- )
+ raise OutputParserException(msg)
# Check if the format is ["column_name"]
elif re.match(r"\[[a-zA-Z0-9_]+(?:,[a-zA-Z0-9_]+)*\]", array):
match = re.match(r"\[[a-zA-Z0-9_]+(?:,[a-zA-Z0-9_]+)*\]", array)
if match:
parsed_array = list(map(str, match.group().strip("[]").split(",")))
else:
- raise OutputParserException(
- f"Unable to parse the array provided in {array}. \
+ msg = f"Unable to parse the array provided in {array}. \
Please check the format instructions."
- )
+ raise OutputParserException(msg)
# Validate the array
if not parsed_array:
- raise OutputParserException(
- f"Invalid array format in '{original_request_params}'. \
+ msg = f"Invalid array format in '{original_request_params}'. \
Please check the format instructions."
- )
+ raise OutputParserException(msg)
elif (
isinstance(parsed_array[0], int)
and parsed_array[-1] > self.dataframe.index.max()
):
- raise OutputParserException(
- f"The maximum index {parsed_array[-1]} exceeds the maximum index of \
+ msg = f"The maximum index {parsed_array[-1]} exceeds the maximum index of \
the Pandas DataFrame {self.dataframe.index.max()}."
- )
+ raise OutputParserException(msg)
return parsed_array, original_request_params.split("[")[0]
@@ -82,17 +78,15 @@ class PandasDataFrameOutputParser(BaseOutputParser[dict[str, Any]]):
stripped_request_params = None
splitted_request = request.strip().split(":")
if len(splitted_request) != 2:
- raise OutputParserException(
- f"Request '{request}' is not correctly formatted. \
+ msg = f"Request '{request}' is not correctly formatted. \
Please refer to the format instructions."
- )
+ raise OutputParserException(msg)
result = {}
try:
request_type, request_params = splitted_request
if request_type in {"Invalid column", "Invalid operation"}:
- raise OutputParserException(
- f"{request}. Please check the format instructions."
- )
+ msg = f"{request}. Please check the format instructions."
+ raise OutputParserException(msg)
array_exists = re.search(r"(\[.*?\])", request_params)
if array_exists:
parsed_array, stripped_request_params = self.parse_array(
@@ -140,17 +134,15 @@ class PandasDataFrameOutputParser(BaseOutputParser[dict[str, Any]]):
)()
except (AttributeError, IndexError, KeyError):
if request_type not in {"column", "row"}:
- raise OutputParserException(
- f"Unsupported request type '{request_type}'. \
+ msg = f"Unsupported request type '{request_type}'. \
Please check the format instructions."
- )
- raise OutputParserException(
- f"""Requested index {
- request_params
- if stripped_request_params is None
- else stripped_request_params
- } is out of bounds."""
- )
+ raise OutputParserException(msg)
+ msg = f"""Requested index {
+ request_params
+ if stripped_request_params is None
+ else stripped_request_params
+ } is out of bounds."""
+ raise OutputParserException(msg)
return result
diff --git a/libs/langchain/langchain/output_parsers/regex.py b/libs/langchain/langchain/output_parsers/regex.py
index 1c469db2f7..dad22bbd22 100644
--- a/libs/langchain/langchain/output_parsers/regex.py
+++ b/libs/langchain/langchain/output_parsers/regex.py
@@ -32,7 +32,8 @@ class RegexParser(BaseOutputParser[dict[str, str]]):
return {key: match.group(i + 1) for i, key in enumerate(self.output_keys)}
else:
if self.default_output_key is None:
- raise ValueError(f"Could not parse output: {text}")
+ msg = f"Could not parse output: {text}"
+ raise ValueError(msg)
else:
return {
key: text if key == self.default_output_key else ""
diff --git a/libs/langchain/langchain/output_parsers/regex_dict.py b/libs/langchain/langchain/output_parsers/regex_dict.py
index 755de4054f..20f01e6528 100644
--- a/libs/langchain/langchain/output_parsers/regex_dict.py
+++ b/libs/langchain/langchain/output_parsers/regex_dict.py
@@ -28,15 +28,15 @@ class RegexDictParser(BaseOutputParser[dict[str, str]]):
specific_regex = self.regex_pattern.format(re.escape(expected_format))
matches = re.findall(specific_regex, text)
if not matches:
- raise ValueError(
+ msg = (
f"No match found for output key: {output_key} with expected format \
{expected_format} on text {text}"
)
+ raise ValueError(msg)
elif len(matches) > 1:
- raise ValueError(
- f"Multiple matches found for output key: {output_key} with \
+ msg = f"Multiple matches found for output key: {output_key} with \
expected format {expected_format} on text {text}"
- )
+ raise ValueError(msg)
elif (
self.no_update_value is not None and matches[0] == self.no_update_value
):
diff --git a/libs/langchain/langchain/output_parsers/retry.py b/libs/langchain/langchain/output_parsers/retry.py
index db20dd2db2..8419afc95c 100644
--- a/libs/langchain/langchain/output_parsers/retry.py
+++ b/libs/langchain/langchain/output_parsers/retry.py
@@ -122,7 +122,8 @@ class RetryOutputParser(BaseOutputParser[T]):
)
)
- raise OutputParserException("Failed to parse")
+ msg = "Failed to parse"
+ raise OutputParserException(msg)
async def aparse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:
"""Parse the output of an LLM call using a wrapped parser.
@@ -158,12 +159,12 @@ class RetryOutputParser(BaseOutputParser[T]):
)
)
- raise OutputParserException("Failed to parse")
+ msg = "Failed to parse"
+ raise OutputParserException(msg)
def parse(self, completion: str) -> T:
- raise NotImplementedError(
- "This OutputParser can only be called by the `parse_with_prompt` method."
- )
+ msg = "This OutputParser can only be called by the `parse_with_prompt` method."
+ raise NotImplementedError(msg)
def get_format_instructions(self) -> str:
return self.parser.get_format_instructions()
@@ -250,7 +251,8 @@ class RetryWithErrorOutputParser(BaseOutputParser[T]):
)
)
- raise OutputParserException("Failed to parse")
+ msg = "Failed to parse"
+ raise OutputParserException(msg)
async def aparse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:
retries = 0
@@ -278,12 +280,12 @@ class RetryWithErrorOutputParser(BaseOutputParser[T]):
)
)
- raise OutputParserException("Failed to parse")
+ msg = "Failed to parse"
+ raise OutputParserException(msg)
def parse(self, completion: str) -> T:
- raise NotImplementedError(
- "This OutputParser can only be called by the `parse_with_prompt` method."
- )
+ msg = "This OutputParser can only be called by the `parse_with_prompt` method."
+ raise NotImplementedError(msg)
def get_format_instructions(self) -> str:
return self.parser.get_format_instructions()
diff --git a/libs/langchain/langchain/retrievers/document_compressors/__init__.py b/libs/langchain/langchain/retrievers/document_compressors/__init__.py
index 2bb7a745fa..c9590d7e67 100644
--- a/libs/langchain/langchain/retrievers/document_compressors/__init__.py
+++ b/libs/langchain/langchain/retrievers/document_compressors/__init__.py
@@ -28,7 +28,8 @@ def __getattr__(name: str) -> Any:
if name in _module_lookup:
module = importlib.import_module(_module_lookup[name])
return getattr(module, name)
- raise AttributeError(f"module {__name__} has no attribute {name}")
+ msg = f"module {__name__} has no attribute {name}"
+ raise AttributeError(msg)
__all__ = [
diff --git a/libs/langchain/langchain/retrievers/document_compressors/base.py b/libs/langchain/langchain/retrievers/document_compressors/base.py
index d99b74fc7b..3613dba33a 100644
--- a/libs/langchain/langchain/retrievers/document_compressors/base.py
+++ b/libs/langchain/langchain/retrievers/document_compressors/base.py
@@ -45,7 +45,8 @@ class DocumentCompressorPipeline(BaseDocumentCompressor):
elif isinstance(_transformer, BaseDocumentTransformer):
documents = _transformer.transform_documents(documents)
else:
- raise ValueError(f"Got unexpected transformer type: {_transformer}")
+ msg = f"Got unexpected transformer type: {_transformer}"
+ raise ValueError(msg)
return documents
async def acompress_documents(
@@ -72,5 +73,6 @@ class DocumentCompressorPipeline(BaseDocumentCompressor):
elif isinstance(_transformer, BaseDocumentTransformer):
documents = await _transformer.atransform_documents(documents)
else:
- raise ValueError(f"Got unexpected transformer type: {_transformer}")
+ msg = f"Got unexpected transformer type: {_transformer}"
+ raise ValueError(msg)
return documents
diff --git a/libs/langchain/langchain/retrievers/document_compressors/cohere_rerank.py b/libs/langchain/langchain/retrievers/document_compressors/cohere_rerank.py
index d72e627f51..f878cb5096 100644
--- a/libs/langchain/langchain/retrievers/document_compressors/cohere_rerank.py
+++ b/libs/langchain/langchain/retrievers/document_compressors/cohere_rerank.py
@@ -42,10 +42,11 @@ class CohereRerank(BaseDocumentCompressor):
try:
import cohere
except ImportError:
- raise ImportError(
+ msg = (
"Could not import cohere python package. "
"Please install it with `pip install cohere`."
)
+ raise ImportError(msg)
cohere_api_key = get_from_dict_or_env(
values, "cohere_api_key", "COHERE_API_KEY"
)
diff --git a/libs/langchain/langchain/retrievers/document_compressors/embeddings_filter.py b/libs/langchain/langchain/retrievers/document_compressors/embeddings_filter.py
index 49ca22a8c2..1826d2acdb 100644
--- a/libs/langchain/langchain/retrievers/document_compressors/embeddings_filter.py
+++ b/libs/langchain/langchain/retrievers/document_compressors/embeddings_filter.py
@@ -12,10 +12,11 @@ def _get_similarity_function() -> Callable:
try:
from langchain_community.utils.math import cosine_similarity
except ImportError:
- raise ImportError(
+ msg = (
"To use please install langchain-community "
"with `pip install langchain-community`."
)
+ raise ImportError(msg)
return cosine_similarity
@@ -45,7 +46,8 @@ class EmbeddingsFilter(BaseDocumentCompressor):
def validate_params(cls, values: dict) -> dict:
"""Validate similarity parameters."""
if values["k"] is None and values["similarity_threshold"] is None:
- raise ValueError("Must specify one of `k` or `similarity_threshold`.")
+ msg = "Must specify one of `k` or `similarity_threshold`."
+ raise ValueError(msg)
return values
def compress_documents(
@@ -61,17 +63,17 @@ class EmbeddingsFilter(BaseDocumentCompressor):
get_stateful_documents,
)
except ImportError:
- raise ImportError(
+ msg = (
"To use please install langchain-community "
"with `pip install langchain-community`."
)
+ raise ImportError(msg)
try:
import numpy as np
except ImportError as e:
- raise ImportError(
- "Could not import numpy, please install with `pip install numpy`."
- ) from e
+ msg = "Could not import numpy, please install with `pip install numpy`."
+ raise ImportError(msg) from e
stateful_documents = get_stateful_documents(documents)
embedded_documents = _get_embeddings_from_stateful_docs(
self.embeddings, stateful_documents
@@ -103,17 +105,17 @@ class EmbeddingsFilter(BaseDocumentCompressor):
get_stateful_documents,
)
except ImportError:
- raise ImportError(
+ msg = (
"To use please install langchain-community "
"with `pip install langchain-community`."
)
+ raise ImportError(msg)
try:
import numpy as np
except ImportError as e:
- raise ImportError(
- "Could not import numpy, please install with `pip install numpy`."
- ) from e
+ msg = "Could not import numpy, please install with `pip install numpy`."
+ raise ImportError(msg) from e
stateful_documents = get_stateful_documents(documents)
embedded_documents = await _aget_embeddings_from_stateful_docs(
self.embeddings, stateful_documents
diff --git a/libs/langchain/langchain/retrievers/document_compressors/listwise_rerank.py b/libs/langchain/langchain/retrievers/document_compressors/listwise_rerank.py
index c489b51420..f0d9859363 100644
--- a/libs/langchain/langchain/retrievers/document_compressors/listwise_rerank.py
+++ b/libs/langchain/langchain/retrievers/document_compressors/listwise_rerank.py
@@ -117,9 +117,10 @@ class LLMListwiseRerank(BaseDocumentCompressor):
"""
if llm.with_structured_output == BaseLanguageModel.with_structured_output:
- raise ValueError(
+ msg = (
f"llm of type {type(llm)} does not implement `with_structured_output`."
)
+ raise ValueError(msg)
class RankDocuments(BaseModel):
"""Rank the documents by their relevance to the user question.
diff --git a/libs/langchain/langchain/retrievers/ensemble.py b/libs/langchain/langchain/retrievers/ensemble.py
index 1fe344c0e4..af10cd6e66 100644
--- a/libs/langchain/langchain/retrievers/ensemble.py
+++ b/libs/langchain/langchain/retrievers/ensemble.py
@@ -297,9 +297,8 @@ class EnsembleRetriever(BaseRetriever):
scores in descending order.
"""
if len(doc_lists) != len(self.weights):
- raise ValueError(
- "Number of rank lists must be equal to the number of weights."
- )
+ msg = "Number of rank lists must be equal to the number of weights."
+ raise ValueError(msg)
# Associate each doc's content with its RRF score for later sorting by it
# Duplicated contents across retrievers are collapsed & scored cumulatively
diff --git a/libs/langchain/langchain/retrievers/multi_vector.py b/libs/langchain/langchain/retrievers/multi_vector.py
index e4b491b899..b6a639cdff 100644
--- a/libs/langchain/langchain/retrievers/multi_vector.py
+++ b/libs/langchain/langchain/retrievers/multi_vector.py
@@ -49,7 +49,8 @@ class MultiVectorRetriever(BaseRetriever):
if byte_store is not None:
docstore = create_kv_docstore(byte_store)
elif docstore is None:
- raise Exception("You must pass a `byte_store` parameter.")
+ msg = "You must pass a `byte_store` parameter."
+ raise Exception(msg)
values["docstore"] = docstore
return values
diff --git a/libs/langchain/langchain/retrievers/parent_document_retriever.py b/libs/langchain/langchain/retrievers/parent_document_retriever.py
index 7143291c94..ad7f455609 100644
--- a/libs/langchain/langchain/retrievers/parent_document_retriever.py
+++ b/libs/langchain/langchain/retrievers/parent_document_retriever.py
@@ -81,15 +81,15 @@ class ParentDocumentRetriever(MultiVectorRetriever):
if ids is None:
doc_ids = [str(uuid.uuid4()) for _ in documents]
if not add_to_docstore:
- raise ValueError(
- "If ids are not passed in, `add_to_docstore` MUST be True"
- )
+ msg = "If ids are not passed in, `add_to_docstore` MUST be True"
+ raise ValueError(msg)
else:
if len(documents) != len(ids):
- raise ValueError(
+ msg = (
"Got uneven list of documents and ids. "
"If `ids` is provided, should be same length as `documents`."
)
+ raise ValueError(msg)
doc_ids = ids
docs = []
diff --git a/libs/langchain/langchain/retrievers/self_query/base.py b/libs/langchain/langchain/retrievers/self_query/base.py
index 0bcdb626c2..d5ac1cb38d 100644
--- a/libs/langchain/langchain/retrievers/self_query/base.py
+++ b/libs/langchain/langchain/retrievers/self_query/base.py
@@ -28,10 +28,11 @@ def _get_builtin_translator(vectorstore: VectorStore) -> Visitor:
try:
import langchain_community # noqa: F401
except ImportError:
- raise ImportError(
+ msg = (
"The langchain-community package must be installed to use this feature."
" Please install it using `pip install langchain-community`."
)
+ raise ImportError(msg)
from langchain_community.query_constructors.astradb import AstraDBTranslator
from langchain_community.query_constructors.chroma import ChromaTranslator
@@ -224,10 +225,11 @@ def _get_builtin_translator(vectorstore: VectorStore) -> Visitor:
if isinstance(vectorstore, WeaviateVectorStore):
return WeaviateTranslator()
- raise ValueError(
+ msg = (
f"Self query retriever with Vector Store type {vectorstore.__class__}"
f" not supported."
)
+ raise ValueError(msg)
class SelfQueryRetriever(BaseRetriever):
diff --git a/libs/langchain/langchain/runnables/openai_functions.py b/libs/langchain/langchain/runnables/openai_functions.py
index 5c24a9283c..c381ff10c1 100644
--- a/libs/langchain/langchain/runnables/openai_functions.py
+++ b/libs/langchain/langchain/runnables/openai_functions.py
@@ -38,13 +38,11 @@ class OpenAIFunctionsRouter(RunnableBindingBase[BaseMessage, Any]):
):
if functions is not None:
if len(functions) != len(runnables):
- raise ValueError(
- "The number of functions does not match the number of runnables."
- )
+ msg = "The number of functions does not match the number of runnables."
+ raise ValueError(msg)
if not all(func["name"] in runnables for func in functions):
- raise ValueError(
- "One or more function names are not found in runnables."
- )
+ msg = "One or more function names are not found in runnables."
+ raise ValueError(msg)
router = (
JsonOutputFunctionsParser(args_only=False)
| {"key": itemgetter("name"), "input": itemgetter("arguments")}
diff --git a/libs/langchain/langchain/smith/evaluation/runner_utils.py b/libs/langchain/langchain/smith/evaluation/runner_utils.py
index c86b41f512..dcd23f9da5 100644
--- a/libs/langchain/langchain/smith/evaluation/runner_utils.py
+++ b/libs/langchain/langchain/smith/evaluation/runner_utils.py
@@ -108,10 +108,11 @@ class TestResult(dict):
try:
import pandas as pd
except ImportError as e:
- raise ImportError(
+ msg = (
"Pandas is required to convert the results to a dataframe."
" to install pandas, run `pip install pandas`."
- ) from e
+ )
+ raise ImportError(msg) from e
indices = []
records = []
@@ -160,7 +161,8 @@ class EvalError(dict):
try:
return self[name]
except KeyError:
- raise AttributeError(f"'EvalError' object has no attribute '{name}'")
+ msg = f"'EvalError' object has no attribute '{name}'"
+ raise AttributeError(msg)
def _wrap_in_chain_factory(
@@ -174,7 +176,7 @@ def _wrap_in_chain_factory(
chain_class = chain.__class__.__name__
if llm_or_chain_factory.memory is not None:
memory_class = chain.memory.__class__.__name__
- raise ValueError(
+ msg = (
"Cannot directly evaluate a chain with stateful memory."
" To evaluate this chain, pass in a chain constructor"
" that initializes fresh memory each time it is called."
@@ -187,6 +189,7 @@ def _wrap_in_chain_factory(
"(memory=new_memory, ...)\n\n"
f'run_on_dataset("{dataset_name}", chain_constructor, ...)'
)
+ raise ValueError(msg)
return lambda: chain
elif isinstance(llm_or_chain_factory, BaseLanguageModel):
return llm_or_chain_factory
@@ -236,23 +239,24 @@ def _get_prompt(inputs: dict[str, Any]) -> str:
InputFormatError: If the input format is invalid.
"""
if not inputs:
- raise InputFormatError("Inputs should not be empty.")
+ msg = "Inputs should not be empty."
+ raise InputFormatError(msg)
prompts = []
if "prompt" in inputs:
if not isinstance(inputs["prompt"], str):
- raise InputFormatError(
- f"Expected string for 'prompt', got {type(inputs['prompt']).__name__}"
- )
+ msg = f"Expected string for 'prompt', got {type(inputs['prompt']).__name__}"
+ raise InputFormatError(msg)
prompts = [inputs["prompt"]]
elif "prompts" in inputs:
if not isinstance(inputs["prompts"], list) or not all(
isinstance(i, str) for i in inputs["prompts"]
):
- raise InputFormatError(
+ msg = (
"Expected list of strings for 'prompts',"
f" got {type(inputs['prompts']).__name__}"
)
+ raise InputFormatError(msg)
prompts = inputs["prompts"]
elif len(inputs) == 1:
prompt_ = next(iter(inputs.values()))
@@ -261,17 +265,16 @@ def _get_prompt(inputs: dict[str, Any]) -> str:
elif isinstance(prompt_, list) and all(isinstance(i, str) for i in prompt_):
prompts = prompt_
else:
- raise InputFormatError(f"LLM Run expects string prompt input. Got {inputs}")
+ msg = f"LLM Run expects string prompt input. Got {inputs}"
+ raise InputFormatError(msg)
else:
- raise InputFormatError(
- f"LLM Run expects 'prompt' or 'prompts' in inputs. Got {inputs}"
- )
+ msg = f"LLM Run expects 'prompt' or 'prompts' in inputs. Got {inputs}"
+ raise InputFormatError(msg)
if len(prompts) == 1:
return prompts[0]
else:
- raise InputFormatError(
- f"LLM Run expects single prompt input. Got {len(prompts)} prompts."
- )
+ msg = f"LLM Run expects single prompt input. Got {len(prompts)} prompts."
+ raise InputFormatError(msg)
class ChatModelInput(TypedDict):
@@ -296,7 +299,8 @@ def _get_messages(inputs: dict[str, Any]) -> dict:
InputFormatError: If the input format is invalid.
"""
if not inputs:
- raise InputFormatError("Inputs should not be empty.")
+ msg = "Inputs should not be empty."
+ raise InputFormatError(msg)
input_copy = inputs.copy()
if "messages" in inputs:
input_copy["input"] = input_copy.pop("messages")
@@ -311,16 +315,18 @@ def _get_messages(inputs: dict[str, Any]) -> dict:
if len(raw_messages) == 1:
input_copy["input"] = messages_from_dict(raw_messages[0])
else:
- raise InputFormatError(
+ msg = (
"Batch messages not supported. Please provide a"
" single list of messages."
)
+ raise InputFormatError(msg)
return input_copy
else:
- raise InputFormatError(
+ msg = (
f"Chat Run expects single List[dict] or List[List[dict]] 'messages'"
f" input. Got {inputs}"
)
+ raise InputFormatError(msg)
## Shared data validation utilities
@@ -334,12 +340,13 @@ def _validate_example_inputs_for_language_model(
isinstance(prompt_input, list)
and all(isinstance(msg, BaseMessage) for msg in prompt_input)
):
- raise InputFormatError(
+ msg = (
"When using an input_mapper to prepare dataset example inputs"
" for an LLM or chat model, the output must a single string or"
" a list of chat messages."
f"\nGot: {prompt_input} of type {type(prompt_input)}."
)
+ raise InputFormatError(msg)
else:
try:
_get_prompt(first_example.inputs or {})
@@ -347,7 +354,7 @@ def _validate_example_inputs_for_language_model(
try:
_get_messages(first_example.inputs or {})
except InputFormatError:
- raise InputFormatError(
+ msg = (
"Example inputs do not match language model input format. "
"Expected a dictionary with messages or a single prompt."
f" Got: {first_example.inputs}"
@@ -355,6 +362,7 @@ def _validate_example_inputs_for_language_model(
" to convert the example.inputs to a compatible format"
" for the llm or chat model you wish to evaluate."
)
+ raise InputFormatError(msg)
def _validate_example_inputs_for_chain(
@@ -367,16 +375,18 @@ def _validate_example_inputs_for_chain(
first_inputs = input_mapper(first_example.inputs or {})
missing_keys = set(chain.input_keys).difference(first_inputs)
if not isinstance(first_inputs, dict):
- raise InputFormatError(
+ msg = (
"When using an input_mapper to prepare dataset example"
" inputs for a chain, the mapped value must be a dictionary."
f"\nGot: {first_inputs} of type {type(first_inputs)}."
)
+ raise InputFormatError(msg)
if missing_keys:
- raise InputFormatError(
+ msg = (
"Missing keys after loading example using input_mapper."
f"\nExpected: {chain.input_keys}. Got: {first_inputs.keys()}"
)
+ raise InputFormatError(msg)
else:
first_inputs = first_example.inputs
missing_keys = set(chain.input_keys).difference(first_inputs)
@@ -385,13 +395,14 @@ def _validate_example_inputs_for_chain(
# Refrain from calling to validate.
pass
elif missing_keys:
- raise InputFormatError(
+ msg = (
"Example inputs missing expected chain input keys."
" Please provide an input_mapper to convert the example.inputs"
" to a compatible format for the chain you wish to evaluate."
f"Expected: {chain.input_keys}. "
f"Got: {first_inputs.keys()}"
)
+ raise InputFormatError(msg)
def _validate_example_inputs(
@@ -498,10 +509,11 @@ def _determine_reference_key(
if config.reference_key:
reference_key = config.reference_key
if example_outputs and reference_key not in example_outputs:
- raise ValueError(
+ msg = (
f"Reference key {reference_key} not in Dataset"
f" example outputs: {example_outputs}"
)
+ raise ValueError(msg)
elif example_outputs and len(example_outputs) == 1:
reference_key = list(example_outputs)[0]
else:
@@ -542,15 +554,17 @@ def _construct_run_evaluator(
# Assume we can decorate
return run_evaluator_dec(eval_config)
else:
- raise ValueError(f"Unknown evaluator type: {type(eval_config)}")
+ msg = f"Unknown evaluator type: {type(eval_config)}"
+ raise ValueError(msg)
if isinstance(evaluator_, StringEvaluator):
if evaluator_.requires_reference and reference_key is None:
- raise ValueError(
+ msg = (
f"Must specify reference_key in smith_eval.RunEvalConfig to use"
f" evaluator of type {eval_type_tag} with"
f" dataset with multiple output keys: {example_outputs}."
)
+ raise ValueError(msg)
run_evaluator = smith_eval.StringRunEvaluatorChain.from_run_and_data_type(
evaluator_,
run_type,
@@ -561,18 +575,18 @@ def _construct_run_evaluator(
tags=[eval_type_tag],
)
elif isinstance(evaluator_, PairwiseStringEvaluator):
- raise NotImplementedError(
+ msg = (
f"Run evaluator for {eval_type_tag} is not implemented."
" PairwiseStringEvaluators compare the outputs of two different models"
" rather than the output of a single model."
" Did you mean to use a StringEvaluator instead?"
"\nSee: https://python.langchain.com/docs/guides/evaluation/string/"
)
+ raise NotImplementedError(msg)
else:
- raise NotImplementedError(
- f"Run evaluator for {eval_type_tag} is not implemented"
- )
+ msg = f"Run evaluator for {eval_type_tag} is not implemented"
+ raise NotImplementedError(msg)
return run_evaluator
@@ -644,10 +658,11 @@ def _load_run_evaluators(
elif callable(custom_evaluator):
run_evaluators.append(run_evaluator_dec(custom_evaluator))
else:
- raise ValueError(
+ msg = (
f"Unsupported custom evaluator: {custom_evaluator}."
f" Expected RunEvaluator or StringEvaluator."
)
+ raise ValueError(msg)
return run_evaluators
@@ -693,11 +708,12 @@ async def _arun_llm(
),
)
else:
- raise InputFormatError(
+ msg = (
"Input mapper returned invalid format"
f" {prompt_or_messages}"
"\nExpected a single string or list of chat messages."
)
+ raise InputFormatError(msg)
else:
try:
@@ -847,11 +863,12 @@ def _run_llm(
),
)
else:
- raise InputFormatError(
+ msg = (
"Input mapper returned invalid format: "
f" {prompt_or_messages}"
"\nExpected a single string or list of chat messages."
)
+ raise InputFormatError(msg)
else:
try:
llm_prompts = _get_prompt(inputs)
@@ -972,7 +989,8 @@ def _prepare_eval_run(
examples = list(client.list_examples(dataset_id=dataset.id, as_of=dataset_version))
if not examples:
- raise ValueError(f"Dataset {dataset_name} has no example rows.")
+ msg = f"Dataset {dataset_name} has no example rows."
+ raise ValueError(msg)
modified_at = [ex.modified_at for ex in examples if ex.modified_at]
# Should always be defined in practice when fetched,
# but the typing permits None
@@ -1005,10 +1023,11 @@ run_on_dataset(
project_name="{project_name} - {uid}", # Update since {project_name} already exists
)
"""
- raise ValueError(
+ msg = (
f"Test project {project_name} already exists. Please use a different name:"
f"\n\n{example_msg}"
)
+ raise ValueError(msg)
comparison_url = dataset.url + f"/compare?selectedSessions={project.id}"
print( # noqa: T201
f"View the evaluation results for project '{project_name}'"
diff --git a/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py b/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py
index c0e56ee917..720f527128 100644
--- a/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py
+++ b/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py
@@ -47,7 +47,8 @@ class StringRunMapper(Serializable):
def __call__(self, run: Run) -> dict[str, str]:
"""Maps the Run to a dictionary."""
if not run.outputs:
- raise ValueError(f"Run {run.id} has no outputs to evaluate.")
+ msg = f"Run {run.id} has no outputs to evaluate."
+ raise ValueError(msg)
return self.map(run)
@@ -63,9 +64,11 @@ class LLMStringRunMapper(StringRunMapper):
# Runs from Tracer have messages as a list of lists of dicts
chat_messages = _get_messages_from_run_dict(messages[0])
else:
- raise ValueError(f"Could not extract messages to evaluate {messages}")
+ msg = f"Could not extract messages to evaluate {messages}"
+ raise ValueError(msg)
return get_buffer_string(chat_messages)
- raise ValueError(f"Could not extract messages to evaluate {messages}")
+ msg = f"Could not extract messages to evaluate {messages}"
+ raise ValueError(msg)
def serialize_inputs(self, inputs: dict) -> str:
if "prompts" in inputs: # Should we even accept this?
@@ -75,15 +78,18 @@ class LLMStringRunMapper(StringRunMapper):
elif "messages" in inputs:
input_ = self.serialize_chat_messages(inputs["messages"])
else:
- raise ValueError("LLM Run must have either messages or prompts as inputs.")
+ msg = "LLM Run must have either messages or prompts as inputs."
+ raise ValueError(msg)
return input_
def serialize_outputs(self, outputs: dict) -> str:
if not outputs.get("generations"):
- raise ValueError("Cannot evaluate LLM Run without generations.")
+ msg = "Cannot evaluate LLM Run without generations."
+ raise ValueError(msg)
generations: list[dict] = outputs["generations"]
if not generations:
- raise ValueError("Cannot evaluate LLM run with empty generations.")
+ msg = "Cannot evaluate LLM run with empty generations."
+ raise ValueError(msg)
first_generation: dict = generations[0]
if isinstance(first_generation, list):
# Runs from Tracer have generations as a list of lists of dicts
@@ -98,29 +104,26 @@ class LLMStringRunMapper(StringRunMapper):
def map(self, run: Run) -> dict[str, str]:
"""Maps the Run to a dictionary."""
if run.run_type != "llm":
- raise ValueError("LLM RunMapper only supports LLM runs.")
+ msg = "LLM RunMapper only supports LLM runs."
+ raise ValueError(msg)
elif not run.outputs:
if run.error:
- raise ValueError(
- f"Cannot evaluate errored LLM run {run.id}: {run.error}"
- )
+ msg = f"Cannot evaluate errored LLM run {run.id}: {run.error}"
+ raise ValueError(msg)
else:
- raise ValueError(
- f"Run {run.id} has no outputs. Cannot evaluate this run."
- )
+ msg = f"Run {run.id} has no outputs. Cannot evaluate this run."
+ raise ValueError(msg)
else:
try:
inputs = self.serialize_inputs(run.inputs)
except Exception as e:
- raise ValueError(
- f"Could not parse LM input from run inputs {run.inputs}"
- ) from e
+ msg = f"Could not parse LM input from run inputs {run.inputs}"
+ raise ValueError(msg) from e
try:
output_ = self.serialize_outputs(run.outputs)
except Exception as e:
- raise ValueError(
- f"Could not parse LM prediction from run outputs {run.outputs}"
- ) from e
+ msg = f"Could not parse LM prediction from run outputs {run.outputs}"
+ raise ValueError(msg) from e
return {"input": inputs, "prediction": output_}
@@ -142,34 +145,38 @@ class ChainStringRunMapper(StringRunMapper):
elif len(source) == 1:
return next(iter(source.values()))
else:
- raise ValueError(
+ msg = (
f"Could not map run {which} with multiple keys: "
f"{source}\nPlease manually specify a {which}_key"
)
+ raise ValueError(msg)
def map(self, run: Run) -> dict[str, str]:
"""Maps the Run to a dictionary."""
if not run.outputs:
- raise ValueError(
+ msg = (
f"Run with ID {run.id} lacks outputs required for evaluation."
" Ensure the Run has valid outputs."
)
+ raise ValueError(msg)
if self.input_key is not None and self.input_key not in run.inputs:
- raise ValueError(
+ msg = (
f"Run with ID {run.id} is missing the expected input key"
f" '{self.input_key}'.\nAvailable input keys in this Run"
f" are: {run.inputs.keys()}.\nAdjust the evaluator's"
f" input_key or ensure your input data includes key"
f" '{self.input_key}'."
)
+ raise ValueError(msg)
elif self.prediction_key is not None and self.prediction_key not in run.outputs:
available_keys = ", ".join(run.outputs.keys())
- raise ValueError(
+ msg = (
f"Run with ID {run.id} doesn't have the expected prediction key"
f" '{self.prediction_key}'. Available prediction keys in this Run are:"
f" {available_keys}. Adjust the evaluator's prediction_key or"
" ensure the Run object's outputs the expected key."
)
+ raise ValueError(msg)
else:
input_ = self._get_key(run.inputs, self.input_key, "input")
@@ -185,7 +192,8 @@ class ToolStringRunMapper(StringRunMapper):
def map(self, run: Run) -> dict[str, str]:
if not run.outputs:
- raise ValueError(f"Run {run.id} has no outputs to evaluate.")
+ msg = f"Run {run.id} has no outputs to evaluate."
+ raise ValueError(msg)
return {"input": run.inputs["input"], "prediction": run.outputs["output"]}
@@ -207,22 +215,23 @@ class StringExampleMapper(Serializable):
def map(self, example: Example) -> dict[str, str]:
"""Maps the Example, or dataset row to a dictionary."""
if not example.outputs:
- raise ValueError(
- f"Example {example.id} has no outputs to use as a reference."
- )
+ msg = f"Example {example.id} has no outputs to use as a reference."
+ raise ValueError(msg)
if self.reference_key is None:
if len(example.outputs) > 1:
- raise ValueError(
+ msg = (
f"Example {example.id} has multiple outputs, so you must"
" specify a reference_key."
)
+ raise ValueError(msg)
else:
output = list(example.outputs.values())[0]
elif self.reference_key not in example.outputs:
- raise ValueError(
+ msg = (
f"Example {example.id} does not have reference key"
f" {self.reference_key}."
)
+ raise ValueError(msg)
else:
output = example.outputs[self.reference_key]
return {
@@ -234,9 +243,8 @@ class StringExampleMapper(Serializable):
def __call__(self, example: Example) -> dict[str, str]:
"""Maps the Run and Example to a dictionary."""
if not example.outputs:
- raise ValueError(
- f"Example {example.id} has no outputs to use as areference label."
- )
+ msg = f"Example {example.id} has no outputs to use as areference label."
+ raise ValueError(msg)
return self.map(example)
@@ -271,11 +279,12 @@ class StringRunEvaluatorChain(Chain, RunEvaluator):
if example and self.example_mapper and self.string_evaluator.requires_reference:
evaluate_strings_inputs.update(self.example_mapper(example))
elif self.string_evaluator.requires_reference:
- raise ValueError(
+ msg = (
f"Evaluator {self.name} requires an reference"
" example from the dataset,"
f" but none was provided for run {run.id}."
)
+ raise ValueError(msg)
return evaluate_strings_inputs
def _prepare_output(self, output: dict[str, Any]) -> dict[str, Any]:
@@ -405,9 +414,8 @@ class StringRunEvaluatorChain(Chain, RunEvaluator):
input_key=input_key, prediction_key=prediction_key
)
else:
- raise ValueError(
- f"Unsupported run type {run_type}. Expected one of 'llm' or 'chain'."
- )
+ msg = f"Unsupported run type {run_type}. Expected one of 'llm' or 'chain'."
+ raise ValueError(msg)
# Configure how example rows are fed as a reference string to the evaluator
if (
@@ -417,11 +425,12 @@ class StringRunEvaluatorChain(Chain, RunEvaluator):
):
example_mapper = StringExampleMapper(reference_key=reference_key)
elif evaluator.requires_reference:
- raise ValueError(
+ msg = (
f"Evaluator {evaluator.evaluation_name} requires a reference"
" example from the dataset. Please specify the reference key from"
" amongst the dataset outputs keys."
)
+ raise ValueError(msg)
else:
example_mapper = None
return cls(
diff --git a/libs/langchain/langchain/storage/_lc_store.py b/libs/langchain/langchain/storage/_lc_store.py
index a2ebf691e5..30403b09c8 100644
--- a/libs/langchain/langchain/storage/_lc_store.py
+++ b/libs/langchain/langchain/storage/_lc_store.py
@@ -17,7 +17,8 @@ def _dump_as_bytes(obj: Serializable) -> bytes:
def _dump_document_as_bytes(obj: Document) -> bytes:
"""Return a bytes representation of a document."""
if not isinstance(obj, Document):
- raise TypeError("Expected a Document instance")
+ msg = "Expected a Document instance"
+ raise TypeError(msg)
return dumps(obj).encode("utf-8")
@@ -25,7 +26,8 @@ def _load_document_from_bytes(serialized: bytes) -> Document:
"""Return a document from a bytes representation."""
obj = loads(serialized.decode("utf-8"))
if not isinstance(obj, Document):
- raise TypeError(f"Expected a Document instance. Got {type(obj)}")
+ msg = f"Expected a Document instance. Got {type(obj)}"
+ raise TypeError(msg)
return obj
diff --git a/libs/langchain/langchain/storage/file_system.py b/libs/langchain/langchain/storage/file_system.py
index ef07f81cb0..beb3032550 100644
--- a/libs/langchain/langchain/storage/file_system.py
+++ b/libs/langchain/langchain/storage/file_system.py
@@ -75,14 +75,16 @@ class LocalFileStore(ByteStore):
Path: The full path for the given key.
"""
if not re.match(r"^[a-zA-Z0-9_.\-/]+$", key):
- raise InvalidKeyException(f"Invalid characters in key: {key}")
+ msg = f"Invalid characters in key: {key}"
+ raise InvalidKeyException(msg)
full_path = os.path.abspath(self.root_path / key)
common_path = os.path.commonpath([str(self.root_path), full_path])
if common_path != str(self.root_path):
- raise InvalidKeyException(
+ msg = (
f"Invalid key: {key}. Key should be relative to the full path."
f"{self.root_path} vs. {common_path} and full path of {full_path}"
)
+ raise InvalidKeyException(msg)
return Path(full_path)
diff --git a/libs/langchain/langchain/tools/__init__.py b/libs/langchain/langchain/tools/__init__.py
index b6b2b0ae29..1126065407 100644
--- a/libs/langchain/langchain/tools/__init__.py
+++ b/libs/langchain/langchain/tools/__init__.py
@@ -39,7 +39,7 @@ _DEPRECATED_TOOLS = {"PythonAstREPLTool", "PythonREPLTool"}
def _import_python_tool_PythonAstREPLTool() -> Any:
- raise ImportError(
+ msg = (
"This tool has been moved to langchain experiment. "
"This tool has access to a python REPL. "
"For best practices make sure to sandbox this tool. "
@@ -47,10 +47,11 @@ def _import_python_tool_PythonAstREPLTool() -> Any:
"To keep using this code as is, install langchain experimental and "
"update relevant imports replacing 'langchain' with 'langchain_experimental'"
)
+ raise ImportError(msg)
def _import_python_tool_PythonREPLTool() -> Any:
- raise ImportError(
+ msg = (
"This tool has been moved to langchain experiment. "
"This tool has access to a python REPL. "
"For best practices make sure to sandbox this tool. "
@@ -58,6 +59,7 @@ def _import_python_tool_PythonREPLTool() -> Any:
"To keep using this code as is, install langchain experimental and "
"update relevant imports replacing 'langchain' with 'langchain_experimental'"
)
+ raise ImportError(msg)
def __getattr__(name: str) -> Any:
diff --git a/libs/langchain/langchain/tools/python/__init__.py b/libs/langchain/langchain/tools/python/__init__.py
index 9c60cf9c94..c92bc153fd 100644
--- a/libs/langchain/langchain/tools/python/__init__.py
+++ b/libs/langchain/langchain/tools/python/__init__.py
@@ -2,7 +2,7 @@ from typing import Any
def __getattr__(name: str = "") -> Any:
- raise AttributeError(
+ msg = (
"This tool has been moved to langchain experiment. "
"This tool has access to a python REPL. "
"For best practices make sure to sandbox this tool. "
@@ -10,3 +10,4 @@ def __getattr__(name: str = "") -> Any:
"To keep using this code as is, install langchain experimental and "
"update relevant imports replacing 'langchain' with 'langchain_experimental'"
)
+ raise AttributeError(msg)
diff --git a/libs/langchain/pyproject.toml b/libs/langchain/pyproject.toml
index 39dea93142..60fb33f569 100644
--- a/libs/langchain/pyproject.toml
+++ b/libs/langchain/pyproject.toml
@@ -143,7 +143,7 @@ ignore-regex = ".*(Stati Uniti|Tense=Pres).*"
ignore-words-list = "momento,collison,ned,foor,reworkd,parth,whats,aapply,mysogyny,unsecure,damon,crate,aadd,symbl,precesses,accademia,nin"
[tool.ruff.lint]
-select = ["E", "F", "I", "PGH003", "PIE", "T201", "D", "UP", "S", "W"]
+select = ["E", "F", "I", "EM", "PGH003", "PIE", "T201", "D", "UP", "S", "W"]
pydocstyle.convention = "google"
pyupgrade.keep-runtime-typing = true
diff --git a/libs/langchain/tests/unit_tests/agents/test_agent.py b/libs/langchain/tests/unit_tests/agents/test_agent.py
index 4706d1470f..257fc8e346 100644
--- a/libs/langchain/tests/unit_tests/agents/test_agent.py
+++ b/libs/langchain/tests/unit_tests/agents/test_agent.py
@@ -579,7 +579,8 @@ async def test_runnable_agent_with_function_calls() -> None:
def find_pet(pet: str) -> str:
"""Find the given pet."""
if pet != "cat":
- raise ValueError("Only cats allowed")
+ msg = "Only cats allowed"
+ raise ValueError(msg)
return "Spying from under the bed."
agent = template | model | fake_parse
@@ -690,14 +691,16 @@ async def test_runnable_with_multi_action_per_step() -> None:
def find_pet(pet: str) -> str:
"""Find the given pet."""
if pet != "cat":
- raise ValueError("Only cats allowed")
+ msg = "Only cats allowed"
+ raise ValueError(msg)
return "Spying from under the bed."
@tool
def pet_pet(pet: str) -> str:
"""Pet the given pet."""
if pet != "cat":
- raise ValueError("Only cats should be petted.")
+ msg = "Only cats should be petted."
+ raise ValueError(msg)
return "purrrr"
agent = template | model | fake_parse
@@ -835,7 +838,8 @@ async def test_openai_agent_with_streaming() -> None:
def find_pet(pet: str) -> str:
"""Find the given pet."""
if pet != "cat":
- raise ValueError("Only cats allowed")
+ msg = "Only cats allowed"
+ raise ValueError(msg)
return "Spying from under the bed."
template = ChatPromptTemplate.from_messages(
@@ -1031,7 +1035,8 @@ async def test_openai_agent_tools_agent() -> None:
def find_pet(pet: str) -> str:
"""Find the given pet."""
if pet != "cat":
- raise ValueError("Only cats allowed")
+ msg = "Only cats allowed"
+ raise ValueError(msg)
return "Spying from under the bed."
@tool
diff --git a/libs/langchain/tests/unit_tests/agents/test_structured_chat.py b/libs/langchain/tests/unit_tests/agents/test_structured_chat.py
index 6b6079fa66..2c583bc978 100644
--- a/libs/langchain/tests/unit_tests/agents/test_structured_chat.py
+++ b/libs/langchain/tests/unit_tests/agents/test_structured_chat.py
@@ -24,7 +24,8 @@ def get_action_and_input(text: str) -> tuple[str, str]:
elif isinstance(output, AgentFinish):
return output.return_values["output"], output.log
else:
- raise ValueError("Unexpected output type")
+ msg = "Unexpected output type"
+ raise ValueError(msg)
def test_parse_with_language() -> None:
diff --git a/libs/langchain/tests/unit_tests/conftest.py b/libs/langchain/tests/unit_tests/conftest.py
index 0e79aca39c..e9bf5a2651 100644
--- a/libs/langchain/tests/unit_tests/conftest.py
+++ b/libs/langchain/tests/unit_tests/conftest.py
@@ -88,7 +88,8 @@ def pytest_collection_modifyitems(config: Config, items: Sequence[Function]) ->
item.add_marker(skip_community)
if only_extended and only_core:
- raise ValueError("Cannot specify both `--only-extended` and `--only-core`.")
+ msg = "Cannot specify both `--only-extended` and `--only-core`."
+ raise ValueError(msg)
for item in items:
requires_marker = item.get_closest_marker("requires")
diff --git a/libs/langchain/tests/unit_tests/embeddings/test_caching.py b/libs/langchain/tests/unit_tests/embeddings/test_caching.py
index 131e78797c..a3d189209c 100644
--- a/libs/langchain/tests/unit_tests/embeddings/test_caching.py
+++ b/libs/langchain/tests/unit_tests/embeddings/test_caching.py
@@ -17,7 +17,8 @@ class MockEmbeddings(Embeddings):
embeddings: list[list[float]] = []
for text in texts:
if text == "RAISE_EXCEPTION":
- raise ValueError("Simulated embedding failure")
+ msg = "Simulated embedding failure"
+ raise ValueError(msg)
embeddings.append([len(text), len(text) + 1])
return embeddings
diff --git a/libs/langchain/tests/unit_tests/indexes/test_indexing.py b/libs/langchain/tests/unit_tests/indexes/test_indexing.py
index b7695d5125..a5280c8aa2 100644
--- a/libs/langchain/tests/unit_tests/indexes/test_indexing.py
+++ b/libs/langchain/tests/unit_tests/indexes/test_indexing.py
@@ -66,18 +66,17 @@ class InMemoryVectorStore(VectorStore):
) -> list[str]:
"""Add the given documents to the store (insert behavior)."""
if ids and len(ids) != len(documents):
- raise ValueError(
- f"Expected {len(ids)} ids, got {len(documents)} documents."
- )
+ msg = f"Expected {len(ids)} ids, got {len(documents)} documents."
+ raise ValueError(msg)
if not ids:
- raise NotImplementedError("This is not implemented yet.")
+ msg = "This is not implemented yet."
+ raise NotImplementedError(msg)
for _id, document in zip(ids, documents):
if _id in self.store and not self.permit_upserts:
- raise ValueError(
- f"Document with uid {_id} already exists in the store."
- )
+ msg = f"Document with uid {_id} already exists in the store."
+ raise ValueError(msg)
self.store[_id] = document
return list(ids)
@@ -90,18 +89,17 @@ class InMemoryVectorStore(VectorStore):
**kwargs: Any,
) -> list[str]:
if ids and len(ids) != len(documents):
- raise ValueError(
- f"Expected {len(ids)} ids, got {len(documents)} documents."
- )
+ msg = f"Expected {len(ids)} ids, got {len(documents)} documents."
+ raise ValueError(msg)
if not ids:
- raise NotImplementedError("This is not implemented yet.")
+ msg = "This is not implemented yet."
+ raise NotImplementedError(msg)
for _id, document in zip(ids, documents):
if _id in self.store and not self.permit_upserts:
- raise ValueError(
- f"Document with uid {_id} already exists in the store."
- )
+ msg = f"Document with uid {_id} already exists in the store."
+ raise ValueError(msg)
self.store[_id] = document
return list(ids)
diff --git a/libs/langchain/tests/unit_tests/llms/fake_chat_model.py b/libs/langchain/tests/unit_tests/llms/fake_chat_model.py
index e3923260f3..957aaabedb 100644
--- a/libs/langchain/tests/unit_tests/llms/fake_chat_model.py
+++ b/libs/langchain/tests/unit_tests/llms/fake_chat_model.py
@@ -98,18 +98,20 @@ class GenericFakeChatModel(BaseChatModel):
messages, stop=stop, run_manager=run_manager, **kwargs
)
if not isinstance(chat_result, ChatResult):
- raise ValueError(
+ msg = (
f"Expected generate to return a ChatResult, "
f"but got {type(chat_result)} instead."
)
+ raise ValueError(msg)
message = chat_result.generations[0].message
if not isinstance(message, AIMessage):
- raise ValueError(
+ msg = (
f"Expected invoke to return an AIMessage, "
f"but got {type(message)} instead."
)
+ raise ValueError(msg)
content = message.content
diff --git a/libs/langchain/tests/unit_tests/llms/fake_llm.py b/libs/langchain/tests/unit_tests/llms/fake_llm.py
index ce46983c47..6b4ec98b71 100644
--- a/libs/langchain/tests/unit_tests/llms/fake_llm.py
+++ b/libs/langchain/tests/unit_tests/llms/fake_llm.py
@@ -19,9 +19,8 @@ class FakeLLM(LLM):
@classmethod
def check_queries_required(cls, values: dict) -> dict:
if values.get("sequential_response") and not values.get("queries"):
- raise ValueError(
- "queries is required when sequential_response is set to True"
- )
+ msg = "queries is required when sequential_response is set to True"
+ raise ValueError(msg)
return values
def get_num_tokens(self, text: str) -> int:
diff --git a/libs/langchain/tests/unit_tests/output_parsers/test_fix.py b/libs/langchain/tests/unit_tests/output_parsers/test_fix.py
index 07daf0ba64..f083bcbb8d 100644
--- a/libs/langchain/tests/unit_tests/output_parsers/test_fix.py
+++ b/libs/langchain/tests/unit_tests/output_parsers/test_fix.py
@@ -25,7 +25,8 @@ class SuccessfulParseAfterRetries(BaseOutputParser[str]):
def parse(self, *args: Any, **kwargs: Any) -> str:
self.parse_count += 1
if self.parse_count <= self.attemp_count_before_success:
- raise OutputParserException("error")
+ msg = "error"
+ raise OutputParserException(msg)
return "parsed"
diff --git a/libs/langchain/tests/unit_tests/test_imports.py b/libs/langchain/tests/unit_tests/test_imports.py
index 8c17cf7251..aa465fa538 100644
--- a/libs/langchain/tests/unit_tests/test_imports.py
+++ b/libs/langchain/tests/unit_tests/test_imports.py
@@ -41,9 +41,8 @@ def test_import_all() -> None:
):
pass
except Exception as e:
- raise AssertionError(
- f"Could not import {module_name}.{name}"
- ) from e
+ msg = f"Could not import {module_name}.{name}"
+ raise AssertionError(msg) from e
def test_import_all_using_dir() -> None:
@@ -64,7 +63,8 @@ def test_import_all_using_dir() -> None:
try:
mod = importlib.import_module(module_name)
except ModuleNotFoundError as e:
- raise ModuleNotFoundError(f"Could not import {module_name}") from e
+ msg = f"Could not import {module_name}"
+ raise ModuleNotFoundError(msg) from e
all = dir(mod)
for name in all:
@@ -159,6 +159,5 @@ def _literal_eval_str(node: ast.AST) -> str:
if isinstance(node, ast.Constant): # Python 3.8+
if isinstance(node.value, str):
return node.value
- raise AssertionError(
- f"Invalid DEPRECATED_LOOKUP format: expected str, got {type(node).__name__}"
- )
+ msg = f"Invalid DEPRECATED_LOOKUP format: expected str, got {type(node).__name__}"
+ raise AssertionError(msg)