Skip to content

Commit 01fdeed

Browse files
cbornetmdrxy
andauthored
chore(core): fix some ruff preview rules (#32785)
Co-authored-by: Mason Daugherty <mason@langchain.dev>
1 parent f4e83e0 commit 01fdeed

File tree

33 files changed

+172
-120
lines changed

33 files changed

+172
-120
lines changed

libs/core/langchain_core/_api/deprecation.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -361,16 +361,17 @@ def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
361361
# Modify the docstring to include a deprecation notice.
362362
if (
363363
_alternative
364-
and _alternative.split(".")[-1].lower() == _alternative.split(".")[-1]
364+
and _alternative.rsplit(".", maxsplit=1)[-1].lower()
365+
== _alternative.rsplit(".", maxsplit=1)[-1]
365366
):
366367
_alternative = f":meth:`~{_alternative}`"
367368
elif _alternative:
368369
_alternative = f":class:`~{_alternative}`"
369370

370371
if (
371372
_alternative_import
372-
and _alternative_import.split(".")[-1].lower()
373-
== _alternative_import.split(".")[-1]
373+
and _alternative_import.rsplit(".", maxsplit=1)[-1].lower()
374+
== _alternative_import.rsplit(".", maxsplit=1)[-1]
374375
):
375376
_alternative_import = f":meth:`~{_alternative_import}`"
376377
elif _alternative_import:
@@ -474,7 +475,7 @@ def warn_deprecated(
474475
if not message:
475476
message = ""
476477
package_ = (
477-
package or name.split(".")[0].replace("_", "-")
478+
package or name.split(".", maxsplit=1)[0].replace("_", "-")
478479
if "." in name
479480
else "LangChain"
480481
)
@@ -493,7 +494,7 @@ def warn_deprecated(
493494
message += f" and will be removed {removal}"
494495

495496
if alternative_import:
496-
alt_package = alternative_import.split(".")[0].replace("_", "-")
497+
alt_package = alternative_import.split(".", maxsplit=1)[0].replace("_", "-")
497498
if alt_package == package_:
498499
message += f". Use {alternative_import} instead."
499500
else:

libs/core/langchain_core/embeddings/fake.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,8 @@ def _get_embedding(self, seed: int) -> list[float]:
119119
rng = np.random.default_rng(seed)
120120
return list(rng.normal(size=self.size))
121121

122-
def _get_seed(self, text: str) -> int:
122+
@staticmethod
123+
def _get_seed(text: str) -> int:
123124
"""Get a seed for the random generator, using the hash of the text."""
124125
return int(hashlib.sha256(text.encode("utf-8")).hexdigest(), 16) % 10**8
125126

libs/core/langchain_core/language_models/chat_models.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,8 +148,6 @@ def _format_for_tracing(messages: list[BaseMessage]) -> list[BaseMessage]:
148148
"type": key,
149149
key: block[key],
150150
}
151-
else:
152-
pass
153151
messages_to_trace.append(message_to_trace)
154152

155153
return messages_to_trace

libs/core/langchain_core/messages/ai.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -352,10 +352,7 @@ def add_chunk_to_invalid_tool_calls(chunk: ToolCallChunk) -> None:
352352

353353
for chunk in self.tool_call_chunks:
354354
try:
355-
if chunk["args"] is not None and chunk["args"] != "":
356-
args_ = parse_partial_json(chunk["args"])
357-
else:
358-
args_ = {}
355+
args_ = parse_partial_json(chunk["args"]) if chunk["args"] else {}
359356
if isinstance(args_, dict):
360357
tool_calls.append(
361358
create_tool_call(

libs/core/langchain_core/messages/base.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -179,9 +179,7 @@ def merge_content(
179179
elif merged and isinstance(merged[-1], str):
180180
merged[-1] += content
181181
# If second content is an empty string, treat as a no-op
182-
elif content == "":
183-
pass
184-
else:
182+
elif content:
185183
# Otherwise, add the second content as a new element of the list
186184
merged.append(content)
187185
return merged

libs/core/langchain_core/output_parsers/json.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,13 @@ class JsonOutputParser(BaseCumulativeTransformOutputParser[Any]):
4646
def _diff(self, prev: Optional[Any], next: Any) -> Any:
4747
return jsonpatch.make_patch(prev, next).patch
4848

49-
def _get_schema(self, pydantic_object: type[TBaseModel]) -> dict[str, Any]:
49+
@staticmethod
50+
def _get_schema(pydantic_object: type[TBaseModel]) -> dict[str, Any]:
5051
if issubclass(pydantic_object, pydantic.BaseModel):
5152
return pydantic_object.model_json_schema()
5253
return pydantic_object.schema()
5354

55+
@override
5456
def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
5557
"""Parse the result of an LLM call to a JSON object.
5658

libs/core/langchain_core/output_parsers/list.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,13 +155,15 @@ def get_lc_namespace(cls) -> list[str]:
155155
"""
156156
return ["langchain", "output_parsers", "list"]
157157

158+
@override
158159
def get_format_instructions(self) -> str:
159160
"""Return the format instructions for the comma-separated list output."""
160161
return (
161162
"Your response should be a list of comma separated values, "
162163
"eg: `foo, bar, baz` or `foo,bar,baz`"
163164
)
164165

166+
@override
165167
def parse(self, text: str) -> list[str]:
166168
"""Parse the output of an LLM call.
167169
@@ -224,6 +226,7 @@ class MarkdownListOutputParser(ListOutputParser):
224226
pattern: str = r"^\s*[-*]\s([^\n]+)$"
225227
"""The pattern to match a Markdown list item."""
226228

229+
@override
227230
def get_format_instructions(self) -> str:
228231
"""Return the format instructions for the Markdown list output."""
229232
return "Your response should be a markdown list, eg: `- foo\n- bar\n- baz`"

libs/core/langchain_core/output_parsers/string.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""String output parser."""
22

3+
from typing_extensions import override
4+
35
from langchain_core.output_parsers.transform import BaseTransformOutputParser
46

57

@@ -29,6 +31,7 @@ def _type(self) -> str:
2931
"""Return the output parser type for serialization."""
3032
return "default"
3133

34+
@override
3235
def parse(self, text: str) -> str:
3336
"""Returns the input text with no changes."""
3437
return text

libs/core/langchain_core/prompts/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ def invoke(
210210
if self.metadata:
211211
config["metadata"] = {**config["metadata"], **self.metadata}
212212
if self.tags:
213-
config["tags"] = config["tags"] + self.tags
213+
config["tags"] += self.tags
214214
return self._call_with_config(
215215
self._format_prompt_with_error_handling,
216216
input,

libs/core/langchain_core/prompts/string.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def mustache_schema(
166166
prefix = section_stack.pop()
167167
elif type_ in {"section", "inverted section"}:
168168
section_stack.append(prefix)
169-
prefix = prefix + tuple(key.split("."))
169+
prefix += tuple(key.split("."))
170170
fields[prefix] = False
171171
elif type_ in {"variable", "no escape"}:
172172
fields[prefix + tuple(key.split("."))] = True

0 commit comments

Comments
 (0)