Skip to content

Commit a0c2281

Browse files
authored
infra: update mypy 1.10, ruff 0.5 (langchain-ai#23721)
```python """python scripts/update_mypy_ruff.py""" import glob import tomllib from pathlib import Path import toml import subprocess import re ROOT_DIR = Path(__file__).parents[1] def main(): for path in glob.glob(str(ROOT_DIR / "libs/**/pyproject.toml"), recursive=True): print(path) with open(path, "rb") as f: pyproject = tomllib.load(f) try: pyproject["tool"]["poetry"]["group"]["typing"]["dependencies"]["mypy"] = ( "^1.10" ) pyproject["tool"]["poetry"]["group"]["lint"]["dependencies"]["ruff"] = ( "^0.5" ) except KeyError: continue with open(path, "w") as f: toml.dump(pyproject, f) cwd = "/".join(path.split("/")[:-1]) completed = subprocess.run( "poetry lock --no-update; poetry install --with typing; poetry run mypy . --no-color", cwd=cwd, shell=True, capture_output=True, text=True, ) logs = completed.stdout.split("\n") to_ignore = {} for l in logs: if re.match("^(.*)\:(\d+)\: error:.*\[(.*)\]", l): path, line_no, error_type = re.match( "^(.*)\:(\d+)\: error:.*\[(.*)\]", l ).groups() if (path, line_no) in to_ignore: to_ignore[(path, line_no)].append(error_type) else: to_ignore[(path, line_no)] = [error_type] print(len(to_ignore)) for (error_path, line_no), error_types in to_ignore.items(): all_errors = ", ".join(error_types) full_path = f"{cwd}/{error_path}" try: with open(full_path, "r") as f: file_lines = f.readlines() except FileNotFoundError: continue file_lines[int(line_no) - 1] = ( file_lines[int(line_no) - 1][:-1] + f" # type: ignore[{all_errors}]\n" ) with open(full_path, "w") as f: f.write("".join(file_lines)) subprocess.run( "poetry run ruff format .; poetry run ruff --select I --fix .", cwd=cwd, shell=True, capture_output=True, text=True, ) if __name__ == "__main__": main() ```
1 parent 6cd5682 commit a0c2281

File tree

915 files changed

+4750
-4038
lines changed

Some content is hidden

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

915 files changed

+4750
-4038
lines changed

.github/actions/people/app/main.py

+20-18
Original file line numberDiff line numberDiff line change
@@ -350,11 +350,7 @@ def get_graphql_pr_edges(*, settings: Settings, after: Union[str, None] = None):
350350
print("Querying PRs...")
351351
else:
352352
print(f"Querying PRs with cursor {after}...")
353-
data = get_graphql_response(
354-
settings=settings,
355-
query=prs_query,
356-
after=after
357-
)
353+
data = get_graphql_response(settings=settings, query=prs_query, after=after)
358354
graphql_response = PRsResponse.model_validate(data)
359355
return graphql_response.data.repository.pullRequests.edges
360356

@@ -484,10 +480,16 @@ def get_contributors(settings: Settings):
484480
lines_changed = pr.additions + pr.deletions
485481
score = _logistic(files_changed, 20) + _logistic(lines_changed, 100)
486482
contributor_scores[pr.author.login] += score
487-
three_months_ago = (datetime.now(timezone.utc) - timedelta(days=3*30))
483+
three_months_ago = datetime.now(timezone.utc) - timedelta(days=3 * 30)
488484
if pr.createdAt > three_months_ago:
489485
recent_contributor_scores[pr.author.login] += score
490-
return contributors, contributor_scores, recent_contributor_scores, reviewers, authors
486+
return (
487+
contributors,
488+
contributor_scores,
489+
recent_contributor_scores,
490+
reviewers,
491+
authors,
492+
)
491493

492494

493495
def get_top_users(
@@ -524,9 +526,13 @@ def get_top_users(
524526
# question_commentors, question_last_month_commentors, question_authors = get_experts(
525527
# settings=settings
526528
# )
527-
contributors, contributor_scores, recent_contributor_scores, reviewers, pr_authors = get_contributors(
528-
settings=settings
529-
)
529+
(
530+
contributors,
531+
contributor_scores,
532+
recent_contributor_scores,
533+
reviewers,
534+
pr_authors,
535+
) = get_contributors(settings=settings)
530536
# authors = {**question_authors, **pr_authors}
531537
authors = {**pr_authors}
532538
maintainers_logins = {
@@ -559,7 +565,7 @@ def get_top_users(
559565
maintainers.append(
560566
{
561567
"login": login,
562-
"count": contributors[login], #+ question_commentors[login],
568+
"count": contributors[login], # + question_commentors[login],
563569
"avatarUrl": user.avatarUrl,
564570
"twitterUsername": user.twitterUsername,
565571
"url": user.url,
@@ -615,9 +621,7 @@ def get_top_users(
615621
new_people_content = yaml.dump(
616622
people, sort_keys=False, width=200, allow_unicode=True
617623
)
618-
if (
619-
people_old_content == new_people_content
620-
):
624+
if people_old_content == new_people_content:
621625
logging.info("The LangChain People data hasn't changed, finishing.")
622626
sys.exit(0)
623627
people_path.write_text(new_people_content, encoding="utf-8")
@@ -630,9 +634,7 @@ def get_top_users(
630634
logging.info(f"Creating a new branch {branch_name}")
631635
subprocess.run(["git", "checkout", "-B", branch_name], check=True)
632636
logging.info("Adding updated file")
633-
subprocess.run(
634-
["git", "add", str(people_path)], check=True
635-
)
637+
subprocess.run(["git", "add", str(people_path)], check=True)
636638
logging.info("Committing updated file")
637639
message = "👥 Update LangChain people data"
638640
result = subprocess.run(["git", "commit", "-m", message], check=True)
@@ -641,4 +643,4 @@ def get_top_users(
641643
logging.info("Creating PR")
642644
pr = repo.create_pull(title=message, body=message, base="master", head=branch_name)
643645
logging.info(f"Created PR: {pr.number}")
644-
logging.info("Finished")
646+
logging.info("Finished")

.github/scripts/check_diff.py

+18-9
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1+
import glob
12
import json
2-
import sys
33
import os
4-
from typing import Dict, List, Set
5-
4+
import re
5+
import sys
66
import tomllib
77
from collections import defaultdict
8-
import glob
8+
from typing import Dict, List, Set
9+
910

1011
LANGCHAIN_DIRS = [
1112
"libs/core",
@@ -15,8 +16,13 @@
1516
"libs/experimental",
1617
]
1718

19+
1820
def all_package_dirs() -> Set[str]:
19-
return {"/".join(path.split("/")[:-1]) for path in glob.glob("./libs/**/pyproject.toml", recursive=True)}
21+
return {
22+
"/".join(path.split("/")[:-1]).lstrip("./")
23+
for path in glob.glob("./libs/**/pyproject.toml", recursive=True)
24+
if "libs/cli" not in path and "libs/standard-tests" not in path
25+
}
2026

2127

2228
def dependents_graph() -> dict:
@@ -26,9 +32,9 @@ def dependents_graph() -> dict:
2632
if "template" in path:
2733
continue
2834
with open(path, "rb") as f:
29-
pyproject = tomllib.load(f)['tool']['poetry']
35+
pyproject = tomllib.load(f)["tool"]["poetry"]
3036
pkg_dir = "libs" + "/".join(path.split("libs")[1].split("/")[:-1])
31-
for dep in pyproject['dependencies']:
37+
for dep in pyproject["dependencies"]:
3238
if "langchain" in dep:
3339
dependents[dep].add(pkg_dir)
3440
return dependents
@@ -122,9 +128,12 @@ def add_dependents(dirs_to_eval: Set[str], dependents: dict) -> List[str]:
122128

123129
outputs = {
124130
"dirs-to-lint": add_dependents(
125-
dirs_to_run["lint"] | dirs_to_run["test"] | dirs_to_run["extended-test"], dependents
131+
dirs_to_run["lint"] | dirs_to_run["test"] | dirs_to_run["extended-test"],
132+
dependents,
133+
),
134+
"dirs-to-test": add_dependents(
135+
dirs_to_run["test"] | dirs_to_run["extended-test"], dependents
126136
),
127-
"dirs-to-test": add_dependents(dirs_to_run["test"] | dirs_to_run["extended-test"], dependents),
128137
"dirs-to-extended-test": list(dirs_to_run["extended-test"]),
129138
"docs-edited": "true" if docs_edited else "",
130139
}

.github/scripts/get_min_versions.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,4 @@ def get_min_version_from_toml(toml_path: str):
7474
# Call the function to get the minimum versions
7575
min_versions = get_min_version_from_toml(toml_file)
7676

77-
print(
78-
" ".join([f"{lib}=={version}" for lib, version in min_versions.items()])
79-
)
77+
print(" ".join([f"{lib}=={version}" for lib, version in min_versions.items()]))

libs/community/Makefile

+3-3
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,14 @@ lint lint_diff lint_package lint_tests:
4848
./scripts/check_pydantic.sh .
4949
./scripts/lint_imports.sh
5050
./scripts/check_pickle.sh .
51-
poetry run ruff .
51+
poetry run ruff check .
5252
[ "$(PYTHON_FILES)" = "" ] || poetry run ruff format $(PYTHON_FILES) --diff
53-
[ "$(PYTHON_FILES)" = "" ] || poetry run ruff --select I $(PYTHON_FILES)
53+
[ "$(PYTHON_FILES)" = "" ] || poetry run ruff check --select I $(PYTHON_FILES)
5454
[ "$(PYTHON_FILES)" = "" ] || mkdir -p $(MYPY_CACHE) && poetry run mypy $(PYTHON_FILES) --cache-dir $(MYPY_CACHE)
5555

5656
format format_diff:
5757
poetry run ruff format $(PYTHON_FILES)
58-
poetry run ruff --select I --fix $(PYTHON_FILES)
58+
poetry run ruff check --select I --fix $(PYTHON_FILES)
5959

6060
spell_check:
6161
poetry run codespell --toml pyproject.toml

libs/community/langchain_community/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Main entrypoint into package."""
2+
23
from importlib import metadata
34

45
try:

libs/community/langchain_community/adapters/openai.py

+8-16
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,7 @@ def create(
206206
provider: str = "ChatOpenAI",
207207
stream: Literal[False] = False,
208208
**kwargs: Any,
209-
) -> dict:
210-
...
209+
) -> dict: ...
211210

212211
@overload
213212
@staticmethod
@@ -217,8 +216,7 @@ def create(
217216
provider: str = "ChatOpenAI",
218217
stream: Literal[True],
219218
**kwargs: Any,
220-
) -> Iterable:
221-
...
219+
) -> Iterable: ...
222220

223221
@staticmethod
224222
def create(
@@ -249,8 +247,7 @@ async def acreate(
249247
provider: str = "ChatOpenAI",
250248
stream: Literal[False] = False,
251249
**kwargs: Any,
252-
) -> dict:
253-
...
250+
) -> dict: ...
254251

255252
@overload
256253
@staticmethod
@@ -260,8 +257,7 @@ async def acreate(
260257
provider: str = "ChatOpenAI",
261258
stream: Literal[True],
262259
**kwargs: Any,
263-
) -> AsyncIterator:
264-
...
260+
) -> AsyncIterator: ...
265261

266262
@staticmethod
267263
async def acreate(
@@ -319,8 +315,7 @@ def create(
319315
provider: str = "ChatOpenAI",
320316
stream: Literal[False] = False,
321317
**kwargs: Any,
322-
) -> ChatCompletions:
323-
...
318+
) -> ChatCompletions: ...
324319

325320
@overload
326321
@staticmethod
@@ -330,8 +325,7 @@ def create(
330325
provider: str = "ChatOpenAI",
331326
stream: Literal[True],
332327
**kwargs: Any,
333-
) -> Iterable:
334-
...
328+
) -> Iterable: ...
335329

336330
@staticmethod
337331
def create(
@@ -366,8 +360,7 @@ async def acreate(
366360
provider: str = "ChatOpenAI",
367361
stream: Literal[False] = False,
368362
**kwargs: Any,
369-
) -> ChatCompletions:
370-
...
363+
) -> ChatCompletions: ...
371364

372365
@overload
373366
@staticmethod
@@ -377,8 +370,7 @@ async def acreate(
377370
provider: str = "ChatOpenAI",
378371
stream: Literal[True],
379372
**kwargs: Any,
380-
) -> AsyncIterator:
381-
...
373+
) -> AsyncIterator: ...
382374

383375
@staticmethod
384376
async def acreate(

libs/community/langchain_community/cache.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -2189,14 +2189,14 @@ def _get_llm_cache(self, llm_string: str) -> AzureCosmosDBVectorSearch:
21892189
index_name=index_name,
21902190
)
21912191
else:
2192-
self._cache_dict[
2193-
index_name
2194-
] = AzureCosmosDBVectorSearch.from_connection_string(
2195-
connection_string=self.cosmosdb_connection_string,
2196-
namespace=namespace,
2197-
embedding=self.embedding,
2198-
index_name=index_name,
2199-
application_name=self.application_name,
2192+
self._cache_dict[index_name] = (
2193+
AzureCosmosDBVectorSearch.from_connection_string(
2194+
connection_string=self.cosmosdb_connection_string,
2195+
namespace=namespace,
2196+
embedding=self.embedding,
2197+
index_name=index_name,
2198+
application_name=self.application_name,
2199+
)
22002200
)
22012201

22022202
# create index for the vectorstore

libs/community/langchain_community/callbacks/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
77
BaseCallbackHandler --> <name>CallbackHandler # Example: AimCallbackHandler
88
"""
9+
910
import importlib
1011
from typing import TYPE_CHECKING, Any
1112

libs/community/langchain_community/callbacks/arize_callback.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,9 @@ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
8282
"completion_tokens", 0
8383
)
8484
else:
85-
self.prompt_tokens = (
86-
self.total_tokens
87-
) = self.completion_tokens = 0 # assign default value
85+
self.prompt_tokens = self.total_tokens = self.completion_tokens = (
86+
0 # assign default value
87+
)
8888

8989
for generations in response.generations:
9090
for generation in generations:

libs/community/langchain_community/callbacks/arthur_callback.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""ArthurAI's Callback Handler."""
2+
23
from __future__ import annotations
34

45
import os

libs/community/langchain_community/callbacks/promptlayer_callback.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Callback handler for promptlayer."""
2+
23
from __future__ import annotations
34

45
import datetime

libs/community/langchain_community/callbacks/tracers/wandb.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""A Tracer Implementation that records activity to Weights & Biases."""
2+
23
from __future__ import annotations
34

45
import json
@@ -234,9 +235,9 @@ def build_tree(runs: List[Dict[str, Any]]) -> Dict[str, Any]:
234235

235236
for child_id, parent_id in child_to_parent.items():
236237
parent_dict = id_to_data[parent_id]
237-
parent_dict[next(iter(parent_dict))][
238-
next(iter(id_to_data[child_id]))
239-
] = id_to_data[child_id][next(iter(id_to_data[child_id]))]
238+
parent_dict[next(iter(parent_dict))][next(iter(id_to_data[child_id]))] = (
239+
id_to_data[child_id][next(iter(id_to_data[child_id]))]
240+
)
240241

241242
root_dict = next(
242243
data for id_val, data in id_to_data.items() if id_val not in child_to_parent

libs/community/langchain_community/chains/ernie_functions/base.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Methods for creating chains that use Ernie function-calling APIs."""
2+
23
import inspect
34
from typing import (
45
Any,
@@ -191,9 +192,9 @@ def get_ernie_output_parser(
191192
}
192193
else:
193194
pydantic_schema = functions[0]
194-
output_parser: Union[
195-
BaseOutputParser, BaseGenerationOutputParser
196-
] = PydanticOutputFunctionsParser(pydantic_schema=pydantic_schema)
195+
output_parser: Union[BaseOutputParser, BaseGenerationOutputParser] = (
196+
PydanticOutputFunctionsParser(pydantic_schema=pydantic_schema)
197+
)
197198
else:
198199
output_parser = JsonOutputFunctionsParser(args_only=len(functions) <= 1)
199200
return output_parser

libs/community/langchain_community/chains/graph_qa/arangodb.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Question answering over a graph."""
2+
23
from __future__ import annotations
34

45
import re

libs/community/langchain_community/chains/graph_qa/base.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Question answering over a graph."""
2+
23
from __future__ import annotations
34

45
from typing import Any, Dict, List, Optional

libs/community/langchain_community/chains/graph_qa/cypher.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Question answering over a graph."""
2+
23
from __future__ import annotations
34

45
import re

libs/community/langchain_community/chains/graph_qa/falkordb.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Question answering over a graph."""
2+
23
from __future__ import annotations
34

45
import re

libs/community/langchain_community/chains/graph_qa/gremlin.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Question answering over a graph."""
2+
23
from __future__ import annotations
34

45
from typing import Any, Dict, List, Optional

libs/community/langchain_community/chains/graph_qa/hugegraph.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Question answering over a graph."""
2+
23
from __future__ import annotations
34

45
from typing import Any, Dict, List, Optional

libs/community/langchain_community/chains/graph_qa/kuzu.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Question answering over a graph."""
2+
23
from __future__ import annotations
34

45
import re

libs/community/langchain_community/chains/graph_qa/nebulagraph.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Question answering over a graph."""
2+
23
from __future__ import annotations
34

45
from typing import Any, Dict, List, Optional

0 commit comments

Comments
 (0)