Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

community: Bump ruff version to 0.9 #29206

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
16 changes: 13 additions & 3 deletions libs/community/langchain_community/chat_models/premai.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,10 @@ def _messages_to_prompt_dict(
elif isinstance(input_msg, HumanMessage):
if template_id is None:
examples_and_messages.append(
{"role": "user", "content": str(input_msg.content)}
{
"role": "user",
"content": str(input_msg.content),
}
)
else:
params: Dict[str, str] = {}
Expand All @@ -206,12 +209,19 @@ def _messages_to_prompt_dict(
)
params[str(input_msg.id)] = str(input_msg.content)
examples_and_messages.append(
{"role": "user", "template_id": template_id, "params": params}
{
"role": "user",
"template_id": template_id,
"params": params,
}
)
elif isinstance(input_msg, AIMessage):
if input_msg.tool_calls is None or len(input_msg.tool_calls) == 0:
examples_and_messages.append(
{"role": "assistant", "content": str(input_msg.content)}
{
"role": "assistant",
"content": str(input_msg.content),
}
)
else:
ai_msg_to_json = {
Expand Down
10 changes: 8 additions & 2 deletions libs/community/langchain_community/chat_models/writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,10 @@ def _stream(
if not delta or not delta.content:
continue
chunk = self._convert_writer_to_langchain(
{"role": "assistant", "content": delta.content}
{
"role": "assistant",
"content": delta.content,
}
)
chunk = ChatGenerationChunk(message=chunk)

Expand All @@ -303,7 +306,10 @@ async def _astream(
if not delta or not delta.content:
continue
chunk = self._convert_writer_to_langchain(
{"role": "assistant", "content": delta.content}
{
"role": "assistant",
"content": delta.content,
}
)
chunk = ChatGenerationChunk(message=chunk)

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 @@ -89,7 +89,10 @@ def rerank(
result_dicts = []
for res in results.output.results:
result_dicts.append(
{"index": res.index, "relevance_score": res.relevance_score}
{
"index": res.index,
"relevance_score": res.relevance_score,
}
)
return result_dicts

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,10 @@ def rerank(
result_dicts = []
for res in results:
result_dicts.append(
{"index": res.index, "relevance_score": res.relevance_score}
{
"index": res.index,
"relevance_score": res.relevance_score,
}
)

result_dicts.sort(key=lambda x: x["relevance_score"], reverse=True)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,10 @@ def rerank(
result_dicts = []
for res in results:
result_dicts.append(
{"index": res["index"], "relevance_score": res["relevance_score"]}
{
"index": res["index"],
"relevance_score": res["relevance_score"],
}
)
return result_dicts

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
6 changes: 5 additions & 1 deletion libs/community/langchain_community/document_loaders/chm.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ def load_all(self) -> List[Dict[str, str]]:
for item in index:
content = self.load(item["local"])
res.append(
{"name": item["name"], "local": item["local"], "content": content}
{
"name": item["name"],
"local": item["local"],
"content": content,
}
)
return res
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 @@ -98,7 +98,10 @@ async def aload(self) -> List[Document]:
# Optionally add database and collection names to metadata
if self.include_db_collection_in_metadata:
metadata.update(
{"database": self.db_name, "collection": self.collection_name}
{
"database": self.db_name,
"collection": self.collection_name,
}
)

# Extract text content from filtered fields or use the entire document
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 @@ -19,7 +19,12 @@ def __init__(self, path: str, nuclia_tool: NucliaUnderstandingAPI):
def load(self) -> List[Document]:
"""Load documents."""
data = self.nua.run(
{"action": "pull", "id": self.id, "path": None, "text": None}
{
"action": "pull",
"id": self.id,
"path": None,
"text": None,
}
)
if not data:
return []
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
Loading
Loading