Skip to content

Commit

Permalink
community: Bump ruff version to 0.9
Browse files Browse the repository at this point in the history
  • Loading branch information
cbornet committed Jan 14, 2025
1 parent d9b856a commit 01a121a
Show file tree
Hide file tree
Showing 128 changed files with 436 additions and 474 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def from_open_api_endpoint_chain(
The API endpoint tool.
"""
expanded_name = (
f'{api_title.replace(" ", "_")}.{chain.api_operation.operation_id}'
f"{api_title.replace(' ', '_')}.{chain.api_operation.operation_id}"
)
description = (
f"I'm an AI from {api_title}. Instruct what you want,"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def __init__(

if self.project not in self.fiddler_client.get_project_names():
print( # noqa: T201
f"adding project {self.project}." "This only has to be done once."
f"adding project {self.project}.This only has to be done once."
)
try:
self.fiddler_client.add_project(self.project)
Expand Down
6 changes: 3 additions & 3 deletions libs/community/langchain_community/callbacks/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ def get_openai_callback() -> Generator[OpenAICallbackHandler, None, None]:


@contextmanager
def get_bedrock_anthropic_callback() -> (
Generator[BedrockAnthropicTokenUsageCallbackHandler, None, None]
):
def get_bedrock_anthropic_callback() -> Generator[
BedrockAnthropicTokenUsageCallbackHandler, None, None
]:
"""Get the Bedrock anthropic callback handler in a context manager.
which conveniently exposes token and cost information.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,9 @@ def on_agent_action(
def complete(self, final_label: Optional[str] = None) -> None:
"""Finish the thought."""
if final_label is None and self._state == LLMThoughtState.RUNNING_TOOL:
assert (
self._last_tool is not None
), "_last_tool should never be null when _state == RUNNING_TOOL"
assert self._last_tool is not None, (
"_last_tool should never be null when _state == RUNNING_TOOL"
)
final_label = self._labeler.get_tool_label(
self._last_tool, is_complete=True
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ async def amake_request(
logger.warning(f"Pebblo Server: Error {response.status}")
elif response.status >= HTTPStatus.BAD_REQUEST:
logger.warning(
f"Pebblo received an invalid payload: " f"{response.text}"
f"Pebblo received an invalid payload: {response.text}"
)
elif response.status != HTTPStatus.OK:
logger.warning(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def lazy_load(self) -> Iterator[ChatSession]:
if "content" not in m:
logger.info(
f"""Skipping Message No.
{index+1} as no content is present in the message"""
{index + 1} as no content is present in the message"""
)
continue
messages.append(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def messages(self) -> List[BaseMessage]:
query = (
f"MATCH (s:`{self._node_label}`)-[:LAST_MESSAGE]->(last_message) "
"WHERE s.id = $session_id MATCH p=(last_message)<-[:NEXT*0.."
f"{self._window*2}]-() WITH p, length(p) AS length "
f"{self._window * 2}]-() WITH p, length(p) AS length "
"ORDER BY length DESC LIMIT 1 UNWIND reverse(nodes(p)) AS node "
"RETURN {data:{content: node.content}, type:node.type} AS result"
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,9 @@ def __init__(
engine_args: Additional configuration for creating database engines.
async_mode: Whether it is an asynchronous connection.
"""
assert not (
connection_string and connection
), "connection_string and connection are mutually exclusive"
assert not (connection_string and connection), (
"connection_string and connection are mutually exclusive"
)
if connection_string:
global _warned_once_already
if not _warned_once_already:
Expand Down
6 changes: 3 additions & 3 deletions libs/community/langchain_community/chat_models/bedrock.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ def _format_anthropic_messages(

if not isinstance(message.content, str):
# parse as dict
assert isinstance(
message.content, list
), "Anthropic message content must be str or list of dicts"
assert isinstance(message.content, list), (
"Anthropic message content must be str or list of dicts"
)

# populate content
content = []
Expand Down
3 changes: 1 addition & 2 deletions libs/community/langchain_community/chat_models/deepinfra.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,8 +468,7 @@ def _handle_status(self, code: int, text: Any) -> None:
raise ValueError(f"DeepInfra received an invalid payload: {text}")
elif code != 200:
raise Exception(
f"DeepInfra returned an unexpected response with status "
f"{code}: {text}"
f"DeepInfra returned an unexpected response with status {code}: {text}"
)

def _url(self) -> str:
Expand Down
3 changes: 1 addition & 2 deletions libs/community/langchain_community/chat_models/konko.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,7 @@ def get_available_models(

if models_response.status_code != 200:
raise ValueError(
f"Error getting models from {models_url}: "
f"{models_response.status_code}"
f"Error getting models from {models_url}: {models_response.status_code}"
)

return {model["id"] for model in models_response.json()["data"]}
Expand Down
2 changes: 1 addition & 1 deletion libs/community/langchain_community/chat_models/zhipuai.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def _get_jwt_token(api_key: str) -> str:
import jwt
except ImportError:
raise ImportError(
"jwt package not found, please install it with" "`pip install pyjwt`"
"jwt package not found, please install it with`pip install pyjwt`"
)

try:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ def yield_blobs(self) -> Iterable[Blob]:
import yt_dlp
except ImportError:
raise ImportError(
"yt_dlp package not found, please install it with "
"`pip install yt_dlp`"
"yt_dlp package not found, please install it with `pip install yt_dlp`"
)

# Use yt_dlp to download audio given a YouTube url
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ def process_attachment(
from PIL import Image # noqa: F401
except ImportError:
raise ImportError(
"`Pillow` package not found, " "please run `pip install Pillow`"
"`Pillow` package not found, please run `pip install Pillow`"
)

# depending on setup you may also need to set the correct path for
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,13 @@ def __read_file(self, csvfile: TextIOWrapper) -> Iterator[Document]:
f"Source column '{self.source_column}' not found in CSV file."
)
content = "\n".join(
f"""{k.strip() if k is not None else k}: {v.strip()
if isinstance(v, str) else ','.join(map(str.strip, v))
if isinstance(v, list) else v}"""
f"""{k.strip() if k is not None else k}: {
v.strip()
if isinstance(v, str)
else ",".join(map(str.strip, v))
if isinstance(v, list)
else v
}"""
for k, v in row.items()
if (
k in self.content_columns
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def _create_dropbox_client(self) -> Any:
try:
from dropbox import Dropbox, exceptions
except ImportError:
raise ImportError("You must run " "`pip install dropbox")
raise ImportError("You must run `pip install dropbox")

try:
dbx = Dropbox(self.dropbox_access_token)
Expand All @@ -73,7 +73,7 @@ def _load_documents_from_folder(self, folder_path: str) -> List[Document]:
from dropbox import exceptions
from dropbox.files import FileMetadata
except ImportError:
raise ImportError("You must run " "`pip install dropbox")
raise ImportError("You must run `pip install dropbox")

try:
results = dbx.files_list_folder(folder_path, recursive=self.recursive)
Expand All @@ -98,7 +98,7 @@ def _load_file_from_path(self, file_path: str) -> Optional[Document]:
try:
from dropbox import exceptions
except ImportError:
raise ImportError("You must run " "`pip install dropbox")
raise ImportError("You must run `pip install dropbox")

try:
file_metadata = dbx.files_get_metadata(file_path)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def _load_dump_file(self): # type: ignore[no-untyped-def]
import mwxml
except ImportError as e:
raise ImportError(
"Unable to import 'mwxml'. Please install with" " `pip install mwxml`."
"Unable to import 'mwxml'. Please install with `pip install mwxml`."
) from e

return mwxml.Dump.from_file(open(self.file_path, encoding=self.encoding))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def load_page(self, page_summary: Dict[str, Any]) -> Document:
value = prop_data["url"]
elif prop_type == "unique_id":
value = (
f'{prop_data["unique_id"]["prefix"]}-{prop_data["unique_id"]["number"]}'
f"{prop_data['unique_id']['prefix']}-{prop_data['unique_id']['number']}"
if prop_data["unique_id"]
else None
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,7 @@ def _run_query(self) -> List[Dict[str, Any]]:
import oracledb
except ImportError as e:
raise ImportError(
"Could not import oracledb, "
"please install with 'pip install oracledb'"
"Could not import oracledb, please install with 'pip install oracledb'"
) from e
connect_param = {"user": self.user, "password": self.password, "dsn": self.dsn}
if self.dsn == self.tns_name:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,7 @@ def __init__(
import openai
except ImportError:
raise ImportError(
"openai package not found, please install it with "
"`pip install openai`"
"openai package not found, please install it with `pip install openai`"
)

if is_openai_v1():
Expand Down Expand Up @@ -278,14 +277,13 @@ def lazy_parse(self, blob: Blob) -> Iterator[Document]:
import openai
except ImportError:
raise ImportError(
"openai package not found, please install it with "
"`pip install openai`"
"openai package not found, please install it with `pip install openai`"
)
try:
from pydub import AudioSegment
except ImportError:
raise ImportError(
"pydub package not found, please install it with " "`pip install pydub`"
"pydub package not found, please install it with `pip install pydub`"
)

if is_openai_v1():
Expand Down Expand Up @@ -402,7 +400,7 @@ def __init__(
import torch
except ImportError:
raise ImportError(
"torch package not found, please install it with " "`pip install torch`"
"torch package not found, please install it with `pip install torch`"
)

# Determine the device to use
Expand Down Expand Up @@ -533,7 +531,7 @@ def lazy_parse(self, blob: Blob) -> Iterator[Document]:
from pydub import AudioSegment
except ImportError:
raise ImportError(
"pydub package not found, please install it with " "`pip install pydub`"
"pydub package not found, please install it with `pip install pydub`"
)

if self.api_key:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def batch_parse(
time_elapsed += check_in_interval_sec
if time_elapsed > timeout_sec:
raise TimeoutError(
"Timeout exceeded! Check operations " f"{operation_names} later!"
f"Timeout exceeded! Check operations {operation_names} later!"
)
logger.debug(".")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def process_xml(
from bs4 import BeautifulSoup
except ImportError:
raise ImportError(
"`bs4` package not found, please install it with " "`pip install bs4`"
"`bs4` package not found, please install it with `pip install bs4`"
)
soup = BeautifulSoup(xml_data, "xml")
sections = soup.find_all("div")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,7 @@ def lazy_parse(self, blob: Blob) -> Iterator[Document]: # type: ignore[valid-ty
import pypdf
except ImportError:
raise ImportError(
"`pypdf` package not found, please install it with "
"`pip install pypdf`"
"`pypdf` package not found, please install it with `pip install pypdf`"
)

def _extract_text_from_page(page: pypdf.PageObject) -> str:
Expand Down Expand Up @@ -425,8 +424,7 @@ def __init__(
import PIL # noqa:F401
except ImportError:
raise ImportError(
"pillow package not found, please install it with"
" `pip install pillow`"
"pillow package not found, please install it with `pip install pillow`"
)
self.text_kwargs = text_kwargs or {}
self.dedupe = dedupe
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ def __init__(
from pyspark.sql import DataFrame, SparkSession
except ImportError:
raise ImportError(
"pyspark is not installed. "
"Please install it with `pip install pyspark`"
"pyspark is not installed. Please install it with `pip install pyspark`"
)

self.spark = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __init__(
from quip_api.quip import QuipClient
except ImportError:
raise ImportError(
"`quip_api` package not found, please run " "`pip install quip_api`"
"`quip_api` package not found, please run `pip install quip_api`"
)

self.quip_client = QuipClient(
Expand Down
5 changes: 2 additions & 3 deletions libs/community/langchain_community/document_loaders/rspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,15 @@ def _create_rspace_client(self) -> Any:
from rspace_client.eln import eln, field_content

except ImportError:
raise ImportError("You must run " "`pip install rspace_client`")
raise ImportError("You must run `pip install rspace_client`")

try:
eln = eln.ELNClient(self.url, self.api_key)
eln.get_status()

except Exception:
raise Exception(
f"Unable to initialize client - is url {self.url} or "
f"api key correct?"
f"Unable to initialize client - is url {self.url} or api key correct?"
)

return eln, field_content.FieldContent
Expand Down
4 changes: 2 additions & 2 deletions libs/community/langchain_community/embeddings/ascend.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def encode(self, sentences: Any) -> Any:
import torch
except ImportError as e:
raise ImportError(
"Unable to import torch, please install with " "`pip install -U torch`."
"Unable to import torch, please install with `pip install -U torch`."
) from e
last_hidden_state = self.model(
inputs.input_ids.npu(), inputs.attention_mask.npu(), return_dict=True
Expand All @@ -103,7 +103,7 @@ def pooling(self, last_hidden_state: Any, attention_mask: Any = None) -> Any:
import torch
except ImportError as e:
raise ImportError(
"Unable to import torch, please install with " "`pip install -U torch`."
"Unable to import torch, please install with `pip install -U torch`."
) from e
if self.pooling_method == "cls":
return last_hidden_state[:, 0]
Expand Down
6 changes: 3 additions & 3 deletions libs/community/langchain_community/embeddings/openvino.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,19 +166,19 @@ def encode(
import numpy as np
except ImportError as e:
raise ImportError(
"Unable to import numpy, please install with " "`pip install -U numpy`."
"Unable to import numpy, please install with `pip install -U numpy`."
) from e
try:
from tqdm import trange
except ImportError as e:
raise ImportError(
"Unable to import tqdm, please install with " "`pip install -U tqdm`."
"Unable to import tqdm, please install with `pip install -U tqdm`."
) from e
try:
import torch
except ImportError as e:
raise ImportError(
"Unable to import torch, please install with " "`pip install -U torch`."
"Unable to import torch, please install with `pip install -U torch`."
) from e

def run_mean_pooling(model_output: Any, attention_mask: Any) -> Any:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,7 @@ def validate_environment(cls, values: Dict) -> Any:
# Check if the spaCy package is installed
if importlib.util.find_spec("spacy") is None:
raise ValueError(
"SpaCy package not found. "
"Please install it with `pip install spacy`."
"SpaCy package not found. Please install it with `pip install spacy`."
)
try:
# Try to load the spaCy model
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]:
data = self._graph.query(query, params)
return data.result_set
except Exception as e:
raise ValueError("Generated Cypher Statement is not valid\n" f"{e}")
raise ValueError(f"Generated Cypher Statement is not valid\n{e}")

def add_graph_documents(
self, graph_documents: List[GraphDocument], include_source: bool = False
Expand Down
Loading

0 comments on commit 01a121a

Please sign in to comment.