Skip to content

Commit 693ca27

Browse files
authored
Fix some ruff preview rules (#153)
1 parent f061432 commit 693ca27

File tree

10 files changed

+100
-25
lines changed

10 files changed

+100
-25
lines changed

libs/astradb/langchain_astradb/cache.py

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,12 @@ def lookup_with_id(
503503
) -> tuple[str, RETURN_VAL_TYPE] | None:
504504
"""Look up based on prompt and llm_string.
505505
506-
If there are hits, return (document_id, cached_entry) for the top hit
506+
Args:
507+
prompt: the prompt string to look up
508+
llm_string: the str representation of the model parameters
509+
510+
Returns:
511+
If there are hits, (document_id, cached_entry) for the top hit
507512
"""
508513
self.astra_env.ensure_db_setup()
509514
prompt_embedding: list[float] = self._get_embedding(text=prompt)
@@ -533,7 +538,12 @@ async def alookup_with_id(
533538
) -> tuple[str, RETURN_VAL_TYPE] | None:
534539
"""Look up based on prompt and llm_string.
535540
536-
If there are hits, return (document_id, cached_entry) for the top hit
541+
Args:
542+
prompt: the prompt string to look up
543+
llm_string: the str representation of the model parameters
544+
545+
Returns:
546+
If there are hits, (document_id, cached_entry) for the top hit
537547
"""
538548
await self.astra_env.aensure_db_setup()
539549
prompt_embedding: list[float] = await self._aget_embedding(text=prompt)
@@ -563,7 +573,13 @@ def lookup_with_id_through_llm(
563573
) -> tuple[str, RETURN_VAL_TYPE] | None:
564574
"""Look up based on prompt and LLM.
565575
566-
If there are hits, return (document_id, cached_entry) for the top hit
576+
Args:
577+
prompt: the prompt string to look up
578+
llm: the LLM instance whose parameters are used in the lookup
579+
stop: optional list of stop words passed to the LLM calls
580+
581+
Returns:
582+
If there are hits, (document_id, cached_entry) for the top hit.
567583
"""
568584
llm_string = get_prompts(
569585
{**llm.dict(), "stop": stop},
@@ -576,7 +592,13 @@ async def alookup_with_id_through_llm(
576592
) -> tuple[str, RETURN_VAL_TYPE] | None:
577593
"""Look up based on prompt and LLM.
578594
579-
If there are hits, return (document_id, cached_entry) for the top hit
595+
Args:
596+
prompt: the prompt string to look up
597+
llm: the LLM instance whose parameters are used in the lookup
598+
stop: optional list of stop words passed to the LLM calls
599+
600+
Returns:
601+
If there are hits, (document_id, cached_entry) for the top hit.
580602
"""
581603
llm_string = (
582604
await aget_prompts(

libs/astradb/langchain_astradb/document_loaders.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,8 @@ def lazy_load(self) -> Iterator[Document]:
145145
):
146146
yield self._to_langchain_doc(doc)
147147

148+
@override
148149
async def aload(self) -> list[Document]:
149-
"""Load data into Document objects."""
150150
return [doc async for doc in self.alazy_load()]
151151

152152
@override

libs/astradb/langchain_astradb/storage.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,12 @@
3838

3939
class AstraDBBaseStore(BaseStore[str, V], Generic[V]):
4040
def __init__(self, *args: Any, **kwargs: Any) -> None:
41-
"""Base class for the DataStax Astra DB data store."""
41+
"""Base class for the DataStax Astra DB data store.
42+
43+
Raises:
44+
ValueError: if 'requested_indexing_policy' or
45+
'default_indexing_policy' are passed in kwargs.
46+
"""
4247
if "requested_indexing_policy" in kwargs:
4348
msg = "Do not pass 'requested_indexing_policy' to AstraDBBaseStore init"
4449
raise ValueError(msg)

libs/astradb/langchain_astradb/utils/astradb.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,10 @@ def copy(
505505
feature and a required secret is not stored with the database.
506506
In order to suppress the API Key in the copy, explicitly pass
507507
``astrapy.authentication.RerankingAPIKeyHeaderProvider(None)``.
508+
509+
Returns:
510+
A shallow copy of this environment, with the possibly updated
511+
attributes.
508512
"""
509513
return _AstraDBCollectionEnvironment(
510514
collection_name=self.collection_name,

libs/astradb/langchain_astradb/utils/vector_store_codecs.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,14 @@ def encode_filter(self, filter_dict: dict[str, Any]) -> dict[str, Any]:
216216

217217
@abstractmethod
218218
def metadata_key_to_field_identifier(self, md_key: str) -> str:
219-
"""Express an 'abstract' metadata key as a full Data API field identifier."""
219+
"""Express an 'abstract' metadata key as a full Data API field identifier.
220+
221+
Args:
222+
md_key: the metadata key.
223+
224+
Returns:
225+
the full Data API field identifier.
226+
"""
220227

221228
@abstractmethod
222229
def encode_vectorize_sort(self, query_text: str) -> dict[str, Any]:

libs/astradb/langchain_astradb/vectorstores.py

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -245,9 +245,9 @@ def _decide_hybrid_search_setting(
245245

246246

247247
def _make_hybrid_limits(
248-
hlf: None | float | dict[str, float],
248+
hlf: float | dict[str, float] | None,
249249
k: int,
250-
) -> None | int | dict[str, int]:
250+
) -> int | dict[str, int] | None:
251251
if hlf is None:
252252
return None
253253
if isinstance(hlf, float):
@@ -258,9 +258,9 @@ def _make_hybrid_limits(
258258

259259
def _normalize_hybrid_limit_factor(
260260
hybrid_limit_factor: float
261-
| None
262261
| dict[str, float]
263-
| HybridLimitFactorPrescription,
262+
| HybridLimitFactorPrescription
263+
| None,
264264
) -> float | dict[str, float] | None:
265265
"""Bring `hybrid_limit_factor` to a normal form."""
266266
if hybrid_limit_factor is None:
@@ -740,9 +740,9 @@ def __init__(
740740
| None = None,
741741
hybrid_search: HybridSearchMode | None = None,
742742
hybrid_limit_factor: float
743-
| None
744743
| dict[str, float]
745-
| HybridLimitFactorPrescription = None,
744+
| HybridLimitFactorPrescription
745+
| None = None,
746746
) -> None:
747747
"""A vector store which uses DataStax Astra DB as backend.
748748
@@ -891,6 +891,9 @@ def __init__(
891891
and the lexical subsearches. Alternatively, a simple dictionary
892892
with keys "$lexical" and "$vector" achieves the same effect.
893893
894+
Raises:
895+
ValueError: if the parameters are inconsistent or invalid.
896+
894897
Note:
895898
For concurrency in synchronous :meth:`~add_texts`:, as a rule of thumb,
896899
on a typical client machine it is suggested to keep the quantity
@@ -941,7 +944,7 @@ def __init__(
941944
self.has_lexical: bool
942945
self.has_hybrid: bool
943946
self.hybrid_search: bool # affecting the actual behaviour when running searches
944-
self.hybrid_limit_factor: None | float | dict[str, float]
947+
self.hybrid_limit_factor: float | dict[str, float] | None
945948
self.collection_reranking_api_key = collection_reranking_api_key
946949

947950
if not self.autodetect_collection:
@@ -1178,7 +1181,7 @@ def copy(
11781181
In those cases, one should create a new instance of ``AstraDBVectorStore``
11791182
from scratch.
11801183
1181-
Attributes:
1184+
Args:
11821185
token: API token for Astra DB usage, either in the form of a string
11831186
or a subclass of ``astrapy.authentication.TokenProvider``.
11841187
In order to suppress token usage in the copy, explicitly pass
@@ -1200,6 +1203,10 @@ def copy(
12001203
This is useful when the service is configured for the collection,
12011204
but no corresponding secret is stored within
12021205
Astra's key management system.
1206+
1207+
Returns:
1208+
a shallow copy of this vector store, possibly with some changed
1209+
attributes.
12031210
"""
12041211
copy = AstraDBVectorStore(
12051212
collection_name="moot",
@@ -1310,6 +1317,9 @@ def delete(
13101317
13111318
Returns:
13121319
True if deletion is (entirely) successful, False otherwise.
1320+
1321+
Raises:
1322+
ValueError: if no ids are provided.
13131323
"""
13141324
if kwargs:
13151325
warnings.warn(
@@ -1350,6 +1360,9 @@ async def adelete(
13501360
13511361
Returns:
13521362
True if deletion is (entirely) successful, False otherwise.
1363+
1364+
Raises:
1365+
ValueError: if no ids are provided.
13531366
"""
13541367
if kwargs:
13551368
warnings.warn(
@@ -1383,6 +1396,9 @@ def delete_by_metadata_filter(
13831396
13841397
Returns:
13851398
A number expressing the amount of deleted documents.
1399+
1400+
Raises:
1401+
ValueError: if the provided filter is empty.
13861402
"""
13871403
if not filter:
13881404
msg = (
@@ -1412,6 +1428,9 @@ async def adelete_by_metadata_filter(
14121428
14131429
Returns:
14141430
A number expressing the amount of deleted documents.
1431+
1432+
Raises:
1433+
ValueError: if the provided filter is empty.
14151434
"""
14161435
if not filter:
14171436
msg = (
@@ -1524,6 +1543,9 @@ def add_texts(
15241543
15251544
Returns:
15261545
The list of ids of the added texts.
1546+
1547+
Raises:
1548+
AstraDBVectorStoreError: if not all documents could be inserted.
15271549
"""
15281550
if kwargs:
15291551
warnings.warn(
@@ -1665,6 +1687,9 @@ async def aadd_texts(
16651687
16661688
Returns:
16671689
The list of ids of the added texts.
1690+
1691+
Raises:
1692+
AstraDBVectorStoreError: if not all documents could be inserted.
16681693
"""
16691694
if kwargs:
16701695
warnings.warn(
@@ -2473,6 +2498,9 @@ def metadata_search(
24732498
Args:
24742499
filter: the metadata to query for.
24752500
n: the maximum number of documents to return.
2501+
2502+
Returns:
2503+
The documents found.
24762504
"""
24772505
docs_ite = self.run_query(n=n, filter=filter)
24782506
return [doc for doc, _, _, _ in docs_ite]
@@ -2487,6 +2515,9 @@ async def ametadata_search(
24872515
Args:
24882516
filter: the metadata to query for.
24892517
n: the maximum number of documents to return.
2518+
2519+
Returns:
2520+
The documents found.
24902521
"""
24912522
docs_ite = await self.arun_query(n=n, filter=filter)
24922523
return [doc async for doc, _, _, _ in docs_ite]
@@ -2933,6 +2964,9 @@ def similarity_search_with_score_id_by_vector(
29332964
29342965
Returns:
29352966
The list of (Document, score, id), the most similar to the query vector.
2967+
2968+
Raises:
2969+
ValueError: if the vector store uses server-side embeddings.
29362970
"""
29372971
if self.document_codec.server_side_embeddings:
29382972
msg = (
@@ -3232,6 +3266,9 @@ async def asimilarity_search_with_score_id_by_vector(
32323266
32333267
Returns:
32343268
The list of (Document, score, id), the most similar to the query vector.
3269+
3270+
Raises:
3271+
ValueError: If the vector store uses server-side embeddings.
32353272
"""
32363273
if self.document_codec.server_side_embeddings:
32373274
msg = (
@@ -3559,8 +3596,8 @@ async def _arun_mmr_find_by_sort(
35593596
prefetch_hit_pairs=prefetch_hit_pairs,
35603597
)
35613598

3599+
@staticmethod
35623600
def _get_mmr_hits(
3563-
self,
35643601
embedding: list[float],
35653602
k: int,
35663603
lambda_mult: float,

libs/astradb/tests/integration_tests/test_chat_message_histories.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def history2(
5555

5656

5757
@pytest.fixture
58-
async def async_history1(
58+
def async_history1(
5959
astra_db_credentials: AstraDBCredentials,
6060
history1: AstraDBChatMessageHistory,
6161
) -> AstraDBChatMessageHistory:
@@ -71,7 +71,7 @@ async def async_history1(
7171

7272

7373
@pytest.fixture
74-
async def async_history2(
74+
def async_history2(
7575
astra_db_credentials: AstraDBCredentials,
7676
history1: AstraDBChatMessageHistory,
7777
) -> AstraDBChatMessageHistory:

libs/astradb/tests/integration_tests/test_document_loaders.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def document_loader_collection(
3232

3333

3434
@pytest.fixture
35-
async def async_document_loader_collection(
35+
def async_document_loader_collection(
3636
collection_idxall: Collection,
3737
) -> AsyncCollection:
3838
return collection_idxall.to_async()
@@ -257,7 +257,7 @@ async def test_page_content_mapper_async(
257257
page_content_mapper=itemgetter("foo"),
258258
filter_criteria={"foo": "bar"},
259259
)
260-
doc = await loader.alazy_load().__anext__()
260+
doc = await anext(loader.alazy_load())
261261
assert doc.page_content == "bar"
262262

263263
async def test_metadata_mapper_async(
@@ -275,5 +275,5 @@ async def test_metadata_mapper_async(
275275
metadata_mapper=lambda x: {"a": x["foo"]},
276276
filter_criteria={"foo": "bar"},
277277
)
278-
doc = await loader.alazy_load().__anext__()
278+
doc = await anext(loader.alazy_load())
279279
assert doc.metadata == {"a": "bar"}

libs/astradb/tests/integration_tests/test_vectorstore_hybrid.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ def test_astradb_vectorstore_explicit_hybrid_lifecycle_vectorize_sync(
235235
assert rscore < 100
236236
assert isinstance(rid, str)
237237
# run other search methods
238-
with pytest.raises(ValueError, match="not allowed."):
238+
with pytest.raises(ValueError, match="not allowed"):
239239
store2_ad.similarity_search_by_vector([1, 2, 3])
240240
mmr_hits_docs = store2_ad.max_marginal_relevance_search(
241241
query=QUERY_TEXT,
@@ -349,7 +349,7 @@ def test_astradb_vectorstore_explicit_hybrid_lifecycle_vectorize_sync(
349349
assert rscore < 100
350350
assert isinstance(rid, str)
351351
# run other search methods
352-
with pytest.raises(ValueError, match="not allowed."):
352+
with pytest.raises(ValueError, match="not allowed"):
353353
store4.similarity_search_by_vector([1, 2, 3])
354354
mmr_hits_docs = store4.max_marginal_relevance_search(
355355
query=QUERY_TEXT,
@@ -615,7 +615,7 @@ async def test_astradb_vectorstore_explicit_hybrid_lifecycle_vectorize_async(
615615
assert rscore < 100
616616
assert isinstance(rid, str)
617617
# run other search methods
618-
with pytest.raises(ValueError, match="not allowed."):
618+
with pytest.raises(ValueError, match="not allowed"):
619619
await store4.asimilarity_search_by_vector([1, 2, 3])
620620
mmr_hits_docs = await store4.amax_marginal_relevance_search(
621621
query=QUERY_TEXT,

libs/astradb/tests/unit_tests/test_astra_db_environment.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def test_initialization(self) -> None:
5959

6060
# just tokenn, no endpoint
6161
with pytest.raises(
62-
ValueError, match="API endpoint for Data API not provided."
62+
ValueError, match="API endpoint for Data API not provided"
6363
):
6464
_AstraDBEnvironment(
6565
token=FAKE_TOKEN,

0 commit comments

Comments
 (0)