Skip to content

Commit 3f839d5

Browse files
cbornetmdrxy
andauthored
langchain: Add ruff rules B (#31908)
See https://docs.astral.sh/ruff/rules/#flake8-bugbear-b Co-authored-by: Mason Daugherty <[email protected]>
1 parent 65b0983 commit 3f839d5

File tree

56 files changed

+168
-130
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+168
-130
lines changed

libs/langchain/langchain/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,12 @@ def _warn_on_import(name: str, replacement: Optional[str] = None) -> None:
2929
warnings.warn(
3030
f"Importing {name} from langchain root module is no longer supported. "
3131
f"Please use {replacement} instead.",
32+
stacklevel=3,
3233
)
3334
else:
3435
warnings.warn(
3536
f"Importing {name} from langchain root module is no longer supported.",
37+
stacklevel=3,
3638
)
3739

3840

libs/langchain/langchain/agents/agent.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1366,7 +1366,7 @@ def _iter_next_step(
13661366
"again, pass `handle_parsing_errors=True` to the AgentExecutor. "
13671367
f"This is the error: {e!s}"
13681368
)
1369-
raise ValueError(msg)
1369+
raise ValueError(msg) from e
13701370
text = str(e)
13711371
if isinstance(self.handle_parsing_errors, bool):
13721372
if e.send_to_llm:
@@ -1380,7 +1380,7 @@ def _iter_next_step(
13801380
observation = self.handle_parsing_errors(e)
13811381
else:
13821382
msg = "Got unexpected type of `handle_parsing_errors`"
1383-
raise ValueError(msg)
1383+
raise ValueError(msg) from e
13841384
output = AgentAction("_Exception", observation, text)
13851385
if run_manager:
13861386
run_manager.on_agent_action(output, color="green")
@@ -1505,7 +1505,7 @@ async def _aiter_next_step(
15051505
"again, pass `handle_parsing_errors=True` to the AgentExecutor. "
15061506
f"This is the error: {e!s}"
15071507
)
1508-
raise ValueError(msg)
1508+
raise ValueError(msg) from e
15091509
text = str(e)
15101510
if isinstance(self.handle_parsing_errors, bool):
15111511
if e.send_to_llm:
@@ -1519,7 +1519,7 @@ async def _aiter_next_step(
15191519
observation = self.handle_parsing_errors(e)
15201520
else:
15211521
msg = "Got unexpected type of `handle_parsing_errors`"
1522-
raise ValueError(msg)
1522+
raise ValueError(msg) from e
15231523
output = AgentAction("_Exception", observation, text)
15241524
tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()
15251525
observation = await ExceptionTool().arun(

libs/langchain/langchain/agents/agent_toolkits/vectorstore/toolkit.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@ def get_tools(self) -> list[BaseTool]:
3636
VectorStoreQATool,
3737
VectorStoreQAWithSourcesTool,
3838
)
39-
except ImportError:
39+
except ImportError as e:
4040
msg = "You need to install langchain-community to use this toolkit."
41-
raise ImportError(msg)
41+
raise ImportError(msg) from e
4242
description = VectorStoreQATool.get_description(
4343
self.vectorstore_info.name,
4444
self.vectorstore_info.description,
@@ -79,9 +79,9 @@ def get_tools(self) -> list[BaseTool]:
7979
from langchain_community.tools.vectorstore.tool import (
8080
VectorStoreQATool,
8181
)
82-
except ImportError:
82+
except ImportError as e:
8383
msg = "You need to install langchain-community to use this toolkit."
84-
raise ImportError(msg)
84+
raise ImportError(msg) from e
8585
for vectorstore_info in self.vectorstores:
8686
description = VectorStoreQATool.get_description(
8787
vectorstore_info.name,

libs/langchain/langchain/agents/openai_functions_agent/base.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232
OpenAIFunctionsAgentOutputParser,
3333
)
3434

35+
_NOT_SET = object()
36+
3537

3638
@deprecated("0.1.0", alternative="create_openai_functions_agent", removal="1.0")
3739
class OpenAIFunctionsAgent(BaseSingleActionAgent):
@@ -213,9 +215,7 @@ def return_stopped_response(
213215
@classmethod
214216
def create_prompt(
215217
cls,
216-
system_message: Optional[SystemMessage] = SystemMessage(
217-
content="You are a helpful AI assistant.",
218-
),
218+
system_message: Optional[SystemMessage] = _NOT_SET, # type: ignore[assignment]
219219
extra_prompt_messages: Optional[list[BaseMessagePromptTemplate]] = None,
220220
) -> ChatPromptTemplate:
221221
"""Create prompt for this agent.
@@ -230,8 +230,13 @@ def create_prompt(
230230
A prompt template to pass into this agent.
231231
"""
232232
_prompts = extra_prompt_messages or []
233+
system_message_ = (
234+
system_message
235+
if system_message is not _NOT_SET
236+
else SystemMessage(content="You are a helpful AI assistant.")
237+
)
233238
messages: list[Union[BaseMessagePromptTemplate, BaseMessage]]
234-
messages = [system_message] if system_message else []
239+
messages = [system_message_] if system_message_ else []
235240

236241
messages.extend(
237242
[
@@ -249,9 +254,7 @@ def from_llm_and_tools(
249254
tools: Sequence[BaseTool],
250255
callback_manager: Optional[BaseCallbackManager] = None,
251256
extra_prompt_messages: Optional[list[BaseMessagePromptTemplate]] = None,
252-
system_message: Optional[SystemMessage] = SystemMessage(
253-
content="You are a helpful AI assistant.",
254-
),
257+
system_message: Optional[SystemMessage] = _NOT_SET, # type: ignore[assignment]
255258
**kwargs: Any,
256259
) -> BaseSingleActionAgent:
257260
"""Construct an agent from an LLM and tools.
@@ -265,9 +268,14 @@ def from_llm_and_tools(
265268
Defaults to a default system message.
266269
kwargs: Additional parameters to pass to the agent.
267270
"""
271+
system_message_ = (
272+
system_message
273+
if system_message is not _NOT_SET
274+
else SystemMessage(content="You are a helpful AI assistant.")
275+
)
268276
prompt = cls.create_prompt(
269277
extra_prompt_messages=extra_prompt_messages,
270-
system_message=system_message,
278+
system_message=system_message_,
271279
)
272280
return cls( # type: ignore[call-arg]
273281
llm=llm,

libs/langchain/langchain/agents/openai_functions_multi_agent/base.py

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -46,21 +46,21 @@ def _parse_ai_message(message: BaseMessage) -> Union[list[AgentAction], AgentFin
4646
if function_call:
4747
try:
4848
arguments = json.loads(function_call["arguments"], strict=False)
49-
except JSONDecodeError:
49+
except JSONDecodeError as e:
5050
msg = (
5151
f"Could not parse tool input: {function_call} because "
5252
f"the `arguments` is not valid JSON."
5353
)
54-
raise OutputParserException(msg)
54+
raise OutputParserException(msg) from e
5555

5656
try:
5757
tools = arguments["actions"]
58-
except (TypeError, KeyError):
58+
except (TypeError, KeyError) as e:
5959
msg = (
6060
f"Could not parse tool input: {function_call} because "
6161
f"the `arguments` JSON does not contain `actions` key."
6262
)
63-
raise OutputParserException(msg)
63+
raise OutputParserException(msg) from e
6464

6565
final_tools: list[AgentAction] = []
6666
for tool_schema in tools:
@@ -100,6 +100,9 @@ def _parse_ai_message(message: BaseMessage) -> Union[list[AgentAction], AgentFin
100100
)
101101

102102

103+
_NOT_SET = object()
104+
105+
103106
@deprecated("0.1.0", alternative="create_openai_tools_agent", removal="1.0")
104107
class OpenAIMultiFunctionsAgent(BaseMultiActionAgent):
105108
"""Agent driven by OpenAIs function powered API.
@@ -263,9 +266,7 @@ async def aplan(
263266
@classmethod
264267
def create_prompt(
265268
cls,
266-
system_message: Optional[SystemMessage] = SystemMessage(
267-
content="You are a helpful AI assistant.",
268-
),
269+
system_message: Optional[SystemMessage] = _NOT_SET, # type: ignore[assignment]
269270
extra_prompt_messages: Optional[list[BaseMessagePromptTemplate]] = None,
270271
) -> BasePromptTemplate:
271272
"""Create prompt for this agent.
@@ -280,8 +281,13 @@ def create_prompt(
280281
A prompt template to pass into this agent.
281282
"""
282283
_prompts = extra_prompt_messages or []
284+
system_message_ = (
285+
system_message
286+
if system_message is not _NOT_SET
287+
else SystemMessage(content="You are a helpful AI assistant.")
288+
)
283289
messages: list[Union[BaseMessagePromptTemplate, BaseMessage]]
284-
messages = [system_message] if system_message else []
290+
messages = [system_message_] if system_message_ else []
285291

286292
messages.extend(
287293
[
@@ -299,9 +305,7 @@ def from_llm_and_tools(
299305
tools: Sequence[BaseTool],
300306
callback_manager: Optional[BaseCallbackManager] = None,
301307
extra_prompt_messages: Optional[list[BaseMessagePromptTemplate]] = None,
302-
system_message: Optional[SystemMessage] = SystemMessage(
303-
content="You are a helpful AI assistant.",
304-
),
308+
system_message: Optional[SystemMessage] = _NOT_SET, # type: ignore[assignment]
305309
**kwargs: Any,
306310
) -> BaseMultiActionAgent:
307311
"""Construct an agent from an LLM and tools.
@@ -315,9 +319,14 @@ def from_llm_and_tools(
315319
Default is a default system message.
316320
kwargs: Additional arguments.
317321
"""
322+
system_message_ = (
323+
system_message
324+
if system_message is not _NOT_SET
325+
else SystemMessage(content="You are a helpful AI assistant.")
326+
)
318327
prompt = cls.create_prompt(
319328
extra_prompt_messages=extra_prompt_messages,
320-
system_message=system_message,
329+
system_message=system_message_,
321330
)
322331
return cls( # type: ignore[call-arg]
323332
llm=llm,

libs/langchain/langchain/agents/output_parsers/openai_functions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,12 @@ def _parse_ai_message(message: BaseMessage) -> Union[AgentAction, AgentFinish]:
4747
else:
4848
# otherwise it returns a json object
4949
_tool_input = json.loads(function_call["arguments"], strict=False)
50-
except JSONDecodeError:
50+
except JSONDecodeError as e:
5151
msg = (
5252
f"Could not parse tool input: {function_call} because "
5353
f"the `arguments` is not valid JSON."
5454
)
55-
raise OutputParserException(msg)
55+
raise OutputParserException(msg) from e
5656

5757
# HACK HACK HACK:
5858
# The code that encodes tool input into Open AI uses a special variable

libs/langchain/langchain/agents/output_parsers/react_json_single_input.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,10 @@ def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
7272
text,
7373
)
7474

75-
except Exception:
75+
except Exception as e:
7676
if not includes_answer:
7777
msg = f"Could not parse LLM output: {text}"
78-
raise OutputParserException(msg)
78+
raise OutputParserException(msg) from e
7979
output = text.split(FINAL_ANSWER_ACTION)[-1].strip()
8080
return AgentFinish({"output": output}, text)
8181

libs/langchain/langchain/agents/output_parsers/tools.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,12 @@ def parse_ai_message_to_tool_action(
4646
tool_calls.append(
4747
ToolCall(name=function_name, args=args, id=tool_call["id"]),
4848
)
49-
except JSONDecodeError:
49+
except JSONDecodeError as e:
5050
msg = (
5151
f"Could not parse tool input: {function} because "
5252
f"the `arguments` is not valid JSON."
5353
)
54-
raise OutputParserException(msg)
54+
raise OutputParserException(msg) from e
5555
for tool_call in tool_calls:
5656
# HACK HACK HACK:
5757
# The code that encodes tool input into Open AI uses a special variable

libs/langchain/langchain/callbacks/streamlit/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,12 +70,12 @@ def StreamlitCallbackHandler(
7070
from langchain_community.callbacks.streamlit.streamlit_callback_handler import ( # noqa: E501
7171
StreamlitCallbackHandler as _InternalStreamlitCallbackHandler,
7272
)
73-
except ImportError:
73+
except ImportError as e:
7474
msg = (
7575
"To use the StreamlitCallbackHandler, please install "
7676
"langchain-community with `pip install langchain-community`."
7777
)
78-
raise ImportError(msg)
78+
raise ImportError(msg) from e
7979

8080
return _InternalStreamlitCallbackHandler(
8181
parent_container,

libs/langchain/langchain/chains/base.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@ def raise_callback_manager_deprecation(cls, values: dict) -> Any:
255255
warnings.warn(
256256
"callback_manager is deprecated. Please use callbacks instead.",
257257
DeprecationWarning,
258+
stacklevel=4,
258259
)
259260
values["callbacks"] = values.pop("callback_manager", None)
260261
return values

0 commit comments

Comments
 (0)