Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions libs/langchain/langchain/_api/module_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,12 @@ def import_by_name(name: str) -> Any:
"<https://python.langchain.com/docs/versions/v0_2/>"
),
)
return result
except Exception as e:
msg = f"module {new_module} has no attribute {name}"
raise AttributeError(msg) from e

return result

if fallback_module:
try:
module = importlib.import_module(fallback_module)
Expand Down Expand Up @@ -139,12 +140,13 @@ def import_by_name(name: str) -> Any:
"<https://python.langchain.com/docs/versions/v0_2/>"
),
)
return result

except Exception as e:
msg = f"module {fallback_module} has no attribute {name}"
raise AttributeError(msg) from e

return result

msg = f"module {package} has no attribute {name}"
raise AttributeError(msg)

Expand Down
4 changes: 2 additions & 2 deletions libs/langchain/langchain/agents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -1380,7 +1380,7 @@ def _iter_next_step(
observation = self.handle_parsing_errors(e)
else:
msg = "Got unexpected type of `handle_parsing_errors`"
raise ValueError(msg) from e
raise ValueError(msg) from e # noqa: TRY004
output = AgentAction("_Exception", observation, text)
if run_manager:
run_manager.on_agent_action(output, color="green")
Expand Down Expand Up @@ -1519,7 +1519,7 @@ async def _aiter_next_step(
observation = self.handle_parsing_errors(e)
else:
msg = "Got unexpected type of `handle_parsing_errors`"
raise ValueError(msg) from e
raise ValueError(msg) from e # noqa: TRY004
output = AgentAction("_Exception", observation, text)
tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()
observation = await ExceptionTool().arun(
Expand Down
2 changes: 1 addition & 1 deletion libs/langchain/langchain/agents/chat/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def _construct_scratchpad(
agent_scratchpad = super()._construct_scratchpad(intermediate_steps)
if not isinstance(agent_scratchpad, str):
msg = "agent_scratchpad should be of type string."
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
if agent_scratchpad:
return (
f"This was your previous work "
Expand Down
8 changes: 4 additions & 4 deletions libs/langchain/langchain/agents/openai_assistant/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,12 +358,12 @@ def invoke(
run = self._wait_for_run(run.id, run.thread_id)
except BaseException as e:
run_manager.on_chain_error(e)
raise e
raise
try:
response = self._get_response(run)
except BaseException as e:
run_manager.on_chain_error(e, metadata=run.dict())
raise e
raise
else:
run_manager.on_chain_end(response)
return response
Expand Down Expand Up @@ -494,12 +494,12 @@ async def ainvoke(
run = await self._await_for_run(run.id, run.thread_id)
except BaseException as e:
run_manager.on_chain_error(e)
raise e
raise
try:
response = self._get_response(run)
except BaseException as e:
run_manager.on_chain_error(e, metadata=run.dict())
raise e
raise
else:
run_manager.on_chain_end(response)
return response
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def parse_result(
) -> Union[AgentAction, AgentFinish]:
if not isinstance(result[0], ChatGeneration):
msg = "This output parser only works on ChatGeneration output"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
message = result[0].message
return self._parse_ai_message(message)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def parse_result(
) -> Union[list[AgentAction], AgentFinish]:
if not isinstance(result[0], ChatGeneration):
msg = "This output parser only works on ChatGeneration output"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
message = result[0].message
return parse_ai_message_to_openai_tool_action(message)

Expand Down
2 changes: 1 addition & 1 deletion libs/langchain/langchain/agents/output_parsers/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def parse_result(
) -> Union[list[AgentAction], AgentFinish]:
if not isinstance(result[0], ChatGeneration):
msg = "This output parser only works on ChatGeneration output"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
message = result[0].message
return parse_ai_message_to_tool_action(message)

Expand Down
2 changes: 1 addition & 1 deletion libs/langchain/langchain/agents/structured_chat/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def _construct_scratchpad(
agent_scratchpad = super()._construct_scratchpad(intermediate_steps)
if not isinstance(agent_scratchpad, str):
msg = "agent_scratchpad should be of type string."
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
if agent_scratchpad:
return (
f"This was your previous work "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,8 @@ def get_format_instructions(self) -> str:
def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
try:
if self.output_fixing_parser is not None:
parsed_obj: Union[AgentAction, AgentFinish] = (
self.output_fixing_parser.parse(text)
)
else:
parsed_obj = self.base_parser.parse(text)
return parsed_obj
return self.output_fixing_parser.parse(text)
return self.base_parser.parse(text)
except Exception as e:
msg = f"Could not parse LLM output: {text}"
raise OutputParserException(msg) from e
Expand Down
4 changes: 2 additions & 2 deletions libs/langchain/langchain/chains/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def invoke(
)
except BaseException as e:
run_manager.on_chain_error(e)
raise e
raise
run_manager.on_chain_end(outputs)

if include_run_info:
Expand Down Expand Up @@ -228,7 +228,7 @@ async def ainvoke(
)
except BaseException as e:
await run_manager.on_chain_error(e)
raise e
raise
await run_manager.on_chain_end(outputs)

if include_run_info:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def validate_llm_output(self) -> Self:
"Output parser of llm_chain should be a RegexParser,"
f" got {output_parser}"
)
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
output_keys = output_parser.output_keys
if self.rank_key not in output_keys:
msg = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def _get_chat_history(chat_history: list[CHAT_TURN_TYPE]) -> str:
f"Unsupported chat history format: {type(dialogue_turn)}."
f" Full chat history: {chat_history} "
)
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
return buffer


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,13 @@ def _call(
chain_result: dict[str, Any] = {self.output_key: final_result}
if self.return_intermediate_steps:
chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps
return chain_result
except Exception as exc:
# Append intermediate steps to exception, to aid in logging and later
# improvement of few shot prompt seeds
exc.intermediate_steps = intermediate_steps # type: ignore[attr-defined]
raise exc
raise

return chain_result

@property
def _chain_type(self) -> str:
Expand Down
4 changes: 2 additions & 2 deletions libs/langchain/langchain/chains/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def apply(
response = self.generate(input_list, run_manager=run_manager)
except BaseException as e:
run_manager.on_chain_error(e)
raise e
raise
outputs = self.create_outputs(response)
run_manager.on_chain_end({"outputs": outputs})
return outputs
Expand All @@ -276,7 +276,7 @@ async def aapply(
response = await self.agenerate(input_list, run_manager=run_manager)
except BaseException as e:
await run_manager.on_chain_error(e)
raise e
raise
outputs = self.create_outputs(response)
await run_manager.on_chain_end({"outputs": outputs})
return outputs
Expand Down
4 changes: 2 additions & 2 deletions libs/langchain/langchain/chains/loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def _load_stuff_documents_chain(config: dict, **kwargs: Any) -> StuffDocumentsCh

if not isinstance(llm_chain, LLMChain):
msg = f"Expected LLMChain, got {llm_chain}"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004

if "document_prompt" in config:
prompt_config = config.pop("document_prompt")
Expand Down Expand Up @@ -150,7 +150,7 @@ def _load_map_reduce_documents_chain(

if not isinstance(llm_chain, LLMChain):
msg = f"Expected LLMChain, got {llm_chain}"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004

if "reduce_documents_chain" in config:
reduce_documents_chain = load_chain_from_config(
Expand Down
6 changes: 3 additions & 3 deletions libs/langchain/langchain/chains/openai_functions/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,13 +361,13 @@ def _execute_tool(message) -> Any:
try:
spec = conversion(spec)
break
except ImportError as e:
raise e
except ImportError:
raise
except Exception: # noqa: S110
pass
if isinstance(spec, str):
msg = f"Unable to parse spec from source {spec}"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
openai_fns, call_api_fn = openapi_spec_to_openai_fn(spec)
if not llm:
msg = (
Expand Down
8 changes: 4 additions & 4 deletions libs/langchain/langchain/chains/router/llm_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def input_keys(self) -> list[str]:
def _validate_outputs(self, outputs: dict[str, Any]) -> None:
super()._validate_outputs(outputs)
if not isinstance(outputs["next_inputs"], dict):
raise ValueError
raise ValueError # noqa: TRY004

def _call(
self,
Expand Down Expand Up @@ -178,10 +178,10 @@ def parse(self, text: str) -> dict[str, Any]:
parsed = parse_and_check_json_markdown(text, expected_keys)
if not isinstance(parsed["destination"], str):
msg = "Expected 'destination' to be a string."
raise ValueError(msg)
raise TypeError(msg)
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think here we can replace with TypeError without breaking compatibility since it's wrapped later in a OutputParserException

if not isinstance(parsed["next_inputs"], self.next_inputs_type):
msg = f"Expected 'next_inputs' to be {self.next_inputs_type}."
raise ValueError(msg)
raise TypeError(msg)
parsed["next_inputs"] = {self.next_inputs_inner_key: parsed["next_inputs"]}
if (
parsed["destination"].strip().lower()
Expand All @@ -190,7 +190,7 @@ def parse(self, text: str) -> dict[str, Any]:
parsed["destination"] = None
else:
parsed["destination"] = parsed["destination"].strip()
return parsed
except Exception as e:
msg = f"Parsing text\n{text}\n raised following error:\n{e}"
raise OutputParserException(msg) from e
return parsed
2 changes: 1 addition & 1 deletion libs/langchain/langchain/embeddings/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ def from_bytes_store(
"key_encoder must be either 'blake2b', 'sha1', 'sha256', 'sha512' "
"or a callable that encodes keys."
)
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004

document_embedding_store = EncoderBackedStore[str, list[float]](
document_embedding_cache,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,10 @@
def _import_numpy() -> Any:
try:
import numpy as np

return np
except ImportError as e:
msg = "Could not import numpy, please install with `pip install numpy`."
raise ImportError(msg) from e
return np


logger = logging.getLogger(__name__)
Expand Down
2 changes: 1 addition & 1 deletion libs/langchain/langchain/evaluation/parsing/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ def _evaluate_strings(
"""
try:
parse_json_markdown(prediction, parser=json.loads)
return {"score": 1}
except Exception as e:
return {"score": 0, "reasoning": str(e)}
return {"score": 1}


class JsonEqualityEvaluator(StringEvaluator):
Expand Down
4 changes: 1 addition & 3 deletions libs/langchain/langchain/evaluation/parsing/json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,9 @@ def _validate(self, prediction: Any, schema: Any) -> dict:

try:
validate(instance=prediction, schema=schema)
return {
"score": True,
}
except ValidationError as e:
return {"score": False, "reasoning": repr(e)}
return {"score": True}

@override
def _evaluate_strings(
Expand Down
12 changes: 6 additions & 6 deletions libs/langchain/langchain/indexes/_sql_record_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def create_schema(self) -> None:
"""Create the database schema."""
if isinstance(self.engine, AsyncEngine):
msg = "This method is not supported for async engines."
raise AssertionError(msg)
raise AssertionError(msg) # noqa: TRY004

Base.metadata.create_all(self.engine)

Expand All @@ -162,7 +162,7 @@ async def acreate_schema(self) -> None:

if not isinstance(self.engine, AsyncEngine):
msg = "This method is not supported for sync engines."
raise AssertionError(msg)
raise AssertionError(msg) # noqa: TRY004

async with self.engine.begin() as session:
await session.run_sync(Base.metadata.create_all)
Expand All @@ -173,7 +173,7 @@ def _make_session(self) -> Generator[Session, None, None]:

if isinstance(self.session_factory, async_sessionmaker):
msg = "This method is not supported for async engines."
raise AssertionError(msg)
raise AssertionError(msg) # noqa: TRY004

session = self.session_factory()
try:
Expand All @@ -187,7 +187,7 @@ async def _amake_session(self) -> AsyncGenerator[AsyncSession, None]:

if not isinstance(self.session_factory, async_sessionmaker):
msg = "This method is not supported for sync engines."
raise AssertionError(msg)
raise AssertionError(msg) # noqa: TRY004

async with self.session_factory() as session:
yield session
Expand Down Expand Up @@ -221,7 +221,7 @@ def get_time(self) -> float:
dt = float(dt)
if not isinstance(dt, float):
msg = f"Unexpected type for datetime: {type(dt)}"
raise AssertionError(msg)
raise AssertionError(msg) # noqa: TRY004
return dt

async def aget_time(self) -> float:
Expand Down Expand Up @@ -254,7 +254,7 @@ async def aget_time(self) -> float:
dt = float(dt)
if not isinstance(dt, float):
msg = f"Unexpected type for datetime: {type(dt)}"
raise AssertionError(msg)
raise AssertionError(msg) # noqa: TRY004
return dt

def update(
Expand Down
6 changes: 3 additions & 3 deletions libs/langchain/langchain/memory/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def __init__(
self.redis_client = Redis(url=url, token=token)
except Exception as exc:
error_msg = "Upstash Redis instance could not be initiated"
logger.error(error_msg)
logger.exception(error_msg)
raise RuntimeError(error_msg) from exc

self.session_id = session_id
Expand Down Expand Up @@ -237,8 +237,8 @@ def __init__(

try:
self.redis_client = get_client(redis_url=url, decode_responses=True)
except redis.exceptions.ConnectionError as error:
logger.error(error)
except redis.exceptions.ConnectionError:
logger.exception("Redis client could not connect")

self.session_id = session_id
self.key_prefix = key_prefix
Expand Down
Loading
Loading