Skip to content

Commit 0ef54ad

Browse files
committed
chore(core): fix some ruff preview rules
1 parent bc91a48 commit 0ef54ad

File tree

36 files changed

+167
-138
lines changed

36 files changed

+167
-138
lines changed

libs/core/langchain_core/_api/deprecation.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -358,16 +358,17 @@ def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
358358
# Modify the docstring to include a deprecation notice.
359359
if (
360360
_alternative
361-
and _alternative.split(".")[-1].lower() == _alternative.split(".")[-1]
361+
and _alternative.rsplit(".", maxsplit=1)[-1].lower()
362+
== _alternative.rsplit(".", maxsplit=1)[-1]
362363
):
363364
_alternative = f":meth:`~{_alternative}`"
364365
elif _alternative:
365366
_alternative = f":class:`~{_alternative}`"
366367

367368
if (
368369
_alternative_import
369-
and _alternative_import.split(".")[-1].lower()
370-
== _alternative_import.split(".")[-1]
370+
and _alternative_import.rsplit(".", maxsplit=1)[-1].lower()
371+
== _alternative_import.rsplit(".", maxsplit=1)[-1]
371372
):
372373
_alternative_import = f":meth:`~{_alternative_import}`"
373374
elif _alternative_import:
@@ -471,7 +472,7 @@ def warn_deprecated(
471472
if not message:
472473
message = ""
473474
package_ = (
474-
package or name.split(".")[0].replace("_", "-")
475+
package or name.split(".", maxsplit=1)[0].replace("_", "-")
475476
if "." in name
476477
else "LangChain"
477478
)
@@ -490,7 +491,7 @@ def warn_deprecated(
490491
message += f" and will be removed {removal}"
491492

492493
if alternative_import:
493-
alt_package = alternative_import.split(".")[0].replace("_", "-")
494+
alt_package = alternative_import.split(".", maxsplit=1)[0].replace("_", "-")
494495
if alt_package == package_:
495496
message += f". Use {alternative_import} instead."
496497
else:

libs/core/langchain_core/embeddings/fake.py

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

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

libs/core/langchain_core/indexing/base.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
from abc import ABC, abstractmethod
88
from typing import TYPE_CHECKING, Any, Optional, TypedDict
99

10+
from typing_extensions import override
11+
1012
from langchain_core._api import beta
1113
from langchain_core.retrievers import BaseRetriever
1214
from langchain_core.runnables import run_in_executor
@@ -256,6 +258,7 @@ def create_schema(self) -> None:
256258
async def acreate_schema(self) -> None:
257259
"""Async in-memory schema creation is simply ensuring the structure is initialized.""" # noqa: E501
258260

261+
@override
259262
def get_time(self) -> float:
260263
"""Get the current server time as a high resolution timestamp!"""
261264
return time.time()

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
@@ -358,10 +358,7 @@ def add_chunk_to_invalid_tool_calls(chunk: ToolCallChunk) -> None:
358358

359359
for chunk in self.tool_call_chunks:
360360
try:
361-
if chunk["args"] is not None and chunk["args"] != "":
362-
args_ = parse_partial_json(chunk["args"])
363-
else:
364-
args_ = {}
361+
args_ = parse_partial_json(chunk["args"]) if chunk["args"] else {}
365362
if isinstance(args_, dict):
366363
tool_calls.append(
367364
create_tool_call(

libs/core/langchain_core/messages/base.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -171,9 +171,7 @@ def merge_content(
171171
elif merged and isinstance(merged[-1], str):
172172
merged[-1] += content
173173
# If second content is an empty string, treat as a no-op
174-
elif content == "":
175-
pass
176-
else:
174+
elif content:
177175
# Otherwise, add the second content as a new element of the list
178176
merged.append(content)
179177
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,13 +46,15 @@ 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
if issubclass(pydantic_object, pydantic.v1.BaseModel):
5354
return pydantic_object.schema()
5455
return None
5556

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

libs/core/langchain_core/output_parsers/list.py

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

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

170+
@override
169171
def parse(self, text: str) -> list[str]:
170172
"""Parse the output of an LLM call.
171173
@@ -235,6 +237,7 @@ class MarkdownListOutputParser(ListOutputParser):
235237
pattern: str = r"^\s*[-*]\s([^\n]+)$"
236238
"""The pattern to match a Markdown list item."""
237239

240+
@override
238241
def get_format_instructions(self) -> str:
239242
"""Return the format instructions for the Markdown list output."""
240243
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

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

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

libs/core/langchain_core/prompts/base.py

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

0 commit comments

Comments
 (0)