mirror of
https://github.com/hwchase17/langchain.git
synced 2025-08-20 09:57:32 +00:00
```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() ```
285 lines
9.5 KiB
Python
285 lines
9.5 KiB
Python
from typing import Optional
|
|
|
|
import numpy as np
|
|
import pytest # type: ignore[import-not-found]
|
|
from langchain_core.documents import Document
|
|
|
|
from langchain_qdrant import Qdrant
|
|
from tests.integration_tests.common import (
|
|
ConsistentFakeEmbeddings,
|
|
assert_documents_equals,
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("batch_size", [1, 64])
|
|
@pytest.mark.parametrize("content_payload_key", [Qdrant.CONTENT_KEY, "foo"])
|
|
@pytest.mark.parametrize("metadata_payload_key", [Qdrant.METADATA_KEY, "bar"])
|
|
@pytest.mark.parametrize("vector_name", [None, "my-vector"])
|
|
def test_qdrant_similarity_search(
|
|
batch_size: int,
|
|
content_payload_key: str,
|
|
metadata_payload_key: str,
|
|
vector_name: Optional[str],
|
|
) -> None:
|
|
"""Test end to end construction and search."""
|
|
texts = ["foo", "bar", "baz"]
|
|
docsearch = Qdrant.from_texts(
|
|
texts,
|
|
ConsistentFakeEmbeddings(),
|
|
location=":memory:",
|
|
content_payload_key=content_payload_key,
|
|
metadata_payload_key=metadata_payload_key,
|
|
batch_size=batch_size,
|
|
vector_name=vector_name,
|
|
)
|
|
output = docsearch.similarity_search("foo", k=1)
|
|
assert_documents_equals(actual=output, expected=[Document(page_content="foo")])
|
|
|
|
|
|
@pytest.mark.parametrize("batch_size", [1, 64])
|
|
@pytest.mark.parametrize("content_payload_key", [Qdrant.CONTENT_KEY, "foo"])
|
|
@pytest.mark.parametrize("metadata_payload_key", [Qdrant.METADATA_KEY, "bar"])
|
|
@pytest.mark.parametrize("vector_name", [None, "my-vector"])
|
|
def test_qdrant_similarity_search_by_vector(
|
|
batch_size: int,
|
|
content_payload_key: str,
|
|
metadata_payload_key: str,
|
|
vector_name: Optional[str],
|
|
) -> None:
|
|
"""Test end to end construction and search."""
|
|
texts = ["foo", "bar", "baz"]
|
|
docsearch = Qdrant.from_texts(
|
|
texts,
|
|
ConsistentFakeEmbeddings(),
|
|
location=":memory:",
|
|
content_payload_key=content_payload_key,
|
|
metadata_payload_key=metadata_payload_key,
|
|
batch_size=batch_size,
|
|
vector_name=vector_name,
|
|
)
|
|
embeddings = ConsistentFakeEmbeddings().embed_query("foo")
|
|
output = docsearch.similarity_search_by_vector(embeddings, k=1)
|
|
assert_documents_equals(output, [Document(page_content="foo")])
|
|
|
|
|
|
@pytest.mark.parametrize("batch_size", [1, 64])
|
|
@pytest.mark.parametrize("content_payload_key", [Qdrant.CONTENT_KEY, "foo"])
|
|
@pytest.mark.parametrize("metadata_payload_key", [Qdrant.METADATA_KEY, "bar"])
|
|
@pytest.mark.parametrize("vector_name", [None, "my-vector"])
|
|
def test_qdrant_similarity_search_with_score_by_vector(
|
|
batch_size: int,
|
|
content_payload_key: str,
|
|
metadata_payload_key: str,
|
|
vector_name: Optional[str],
|
|
) -> None:
|
|
"""Test end to end construction and search."""
|
|
texts = ["foo", "bar", "baz"]
|
|
docsearch = Qdrant.from_texts(
|
|
texts,
|
|
ConsistentFakeEmbeddings(),
|
|
location=":memory:",
|
|
content_payload_key=content_payload_key,
|
|
metadata_payload_key=metadata_payload_key,
|
|
batch_size=batch_size,
|
|
vector_name=vector_name,
|
|
)
|
|
embeddings = ConsistentFakeEmbeddings().embed_query("foo")
|
|
output = docsearch.similarity_search_with_score_by_vector(embeddings, k=1)
|
|
assert len(output) == 1
|
|
document, score = output[0]
|
|
assert_documents_equals(actual=[document], expected=[Document(page_content="foo")])
|
|
assert score >= 0
|
|
|
|
|
|
@pytest.mark.parametrize("batch_size", [1, 64])
|
|
@pytest.mark.parametrize("vector_name", [None, "my-vector"])
|
|
def test_qdrant_similarity_search_filters(
|
|
batch_size: int, vector_name: Optional[str]
|
|
) -> None:
|
|
"""Test end to end construction and search."""
|
|
texts = ["foo", "bar", "baz"]
|
|
metadatas = [
|
|
{"page": i, "metadata": {"page": i + 1, "pages": [i + 2, -1]}}
|
|
for i in range(len(texts))
|
|
]
|
|
docsearch = Qdrant.from_texts(
|
|
texts,
|
|
ConsistentFakeEmbeddings(),
|
|
metadatas=metadatas,
|
|
location=":memory:",
|
|
batch_size=batch_size,
|
|
vector_name=vector_name,
|
|
)
|
|
|
|
output = docsearch.similarity_search(
|
|
"foo", k=1, filter={"page": 1, "metadata": {"page": 2, "pages": [3]}}
|
|
)
|
|
|
|
assert_documents_equals(
|
|
actual=output,
|
|
expected=[
|
|
Document(
|
|
page_content="bar",
|
|
metadata={"page": 1, "metadata": {"page": 2, "pages": [3, -1]}},
|
|
)
|
|
],
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("vector_name", [None, "my-vector"])
|
|
def test_qdrant_similarity_search_with_relevance_score_no_threshold(
|
|
vector_name: Optional[str],
|
|
) -> None:
|
|
"""Test end to end construction and search."""
|
|
texts = ["foo", "bar", "baz"]
|
|
metadatas = [
|
|
{"page": i, "metadata": {"page": i + 1, "pages": [i + 2, -1]}}
|
|
for i in range(len(texts))
|
|
]
|
|
docsearch = Qdrant.from_texts(
|
|
texts,
|
|
ConsistentFakeEmbeddings(),
|
|
metadatas=metadatas,
|
|
location=":memory:",
|
|
vector_name=vector_name,
|
|
)
|
|
output = docsearch.similarity_search_with_relevance_scores(
|
|
"foo", k=3, score_threshold=None
|
|
)
|
|
assert len(output) == 3
|
|
for i in range(len(output)):
|
|
assert round(output[i][1], 2) >= 0
|
|
assert round(output[i][1], 2) <= 1
|
|
|
|
|
|
@pytest.mark.parametrize("vector_name", [None, "my-vector"])
|
|
def test_qdrant_similarity_search_with_relevance_score_with_threshold(
|
|
vector_name: Optional[str],
|
|
) -> None:
|
|
"""Test end to end construction and search."""
|
|
texts = ["foo", "bar", "baz"]
|
|
metadatas = [
|
|
{"page": i, "metadata": {"page": i + 1, "pages": [i + 2, -1]}}
|
|
for i in range(len(texts))
|
|
]
|
|
docsearch = Qdrant.from_texts(
|
|
texts,
|
|
ConsistentFakeEmbeddings(),
|
|
metadatas=metadatas,
|
|
location=":memory:",
|
|
vector_name=vector_name,
|
|
)
|
|
|
|
score_threshold = 0.98
|
|
kwargs = {"score_threshold": score_threshold}
|
|
output = docsearch.similarity_search_with_relevance_scores("foo", k=3, **kwargs)
|
|
assert len(output) == 1
|
|
assert all([score >= score_threshold for _, score in output])
|
|
|
|
|
|
@pytest.mark.parametrize("vector_name", [None, "my-vector"])
|
|
def test_qdrant_similarity_search_with_relevance_score_with_threshold_and_filter(
|
|
vector_name: Optional[str],
|
|
) -> None:
|
|
"""Test end to end construction and search."""
|
|
texts = ["foo", "bar", "baz"]
|
|
metadatas = [
|
|
{"page": i, "metadata": {"page": i + 1, "pages": [i + 2, -1]}}
|
|
for i in range(len(texts))
|
|
]
|
|
docsearch = Qdrant.from_texts(
|
|
texts,
|
|
ConsistentFakeEmbeddings(),
|
|
metadatas=metadatas,
|
|
location=":memory:",
|
|
vector_name=vector_name,
|
|
)
|
|
score_threshold = 0.99 # for almost exact match
|
|
# test negative filter condition
|
|
negative_filter = {"page": 1, "metadata": {"page": 2, "pages": [3]}}
|
|
kwargs = {"filter": negative_filter, "score_threshold": score_threshold}
|
|
output = docsearch.similarity_search_with_relevance_scores("foo", k=3, **kwargs)
|
|
assert len(output) == 0
|
|
# test positive filter condition
|
|
positive_filter = {"page": 0, "metadata": {"page": 1, "pages": [2]}}
|
|
kwargs = {"filter": positive_filter, "score_threshold": score_threshold}
|
|
output = docsearch.similarity_search_with_relevance_scores("foo", k=3, **kwargs)
|
|
assert len(output) == 1
|
|
assert all([score >= score_threshold for _, score in output])
|
|
|
|
|
|
@pytest.mark.parametrize("vector_name", [None, "my-vector"])
|
|
def test_qdrant_similarity_search_filters_with_qdrant_filters(
|
|
vector_name: Optional[str],
|
|
) -> None:
|
|
"""Test end to end construction and search."""
|
|
from qdrant_client.http import models as rest
|
|
|
|
texts = ["foo", "bar", "baz"]
|
|
metadatas = [
|
|
{"page": i, "details": {"page": i + 1, "pages": [i + 2, -1]}}
|
|
for i in range(len(texts))
|
|
]
|
|
docsearch = Qdrant.from_texts(
|
|
texts,
|
|
ConsistentFakeEmbeddings(),
|
|
metadatas=metadatas,
|
|
location=":memory:",
|
|
vector_name=vector_name,
|
|
)
|
|
|
|
qdrant_filter = rest.Filter(
|
|
must=[
|
|
rest.FieldCondition(
|
|
key="metadata.page",
|
|
match=rest.MatchValue(value=1),
|
|
),
|
|
rest.FieldCondition(
|
|
key="metadata.details.page",
|
|
match=rest.MatchValue(value=2),
|
|
),
|
|
rest.FieldCondition(
|
|
key="metadata.details.pages",
|
|
match=rest.MatchAny(any=[3]),
|
|
),
|
|
]
|
|
)
|
|
output = docsearch.similarity_search("foo", k=1, filter=qdrant_filter)
|
|
assert_documents_equals(
|
|
actual=output,
|
|
expected=[
|
|
Document(
|
|
page_content="bar",
|
|
metadata={"page": 1, "details": {"page": 2, "pages": [3, -1]}},
|
|
)
|
|
],
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("batch_size", [1, 64])
|
|
@pytest.mark.parametrize("content_payload_key", [Qdrant.CONTENT_KEY, "foo"])
|
|
@pytest.mark.parametrize("metadata_payload_key", [Qdrant.METADATA_KEY, "bar"])
|
|
@pytest.mark.parametrize("vector_name", [None, "my-vector"])
|
|
def test_qdrant_similarity_search_with_relevance_scores(
|
|
batch_size: int,
|
|
content_payload_key: str,
|
|
metadata_payload_key: str,
|
|
vector_name: Optional[str],
|
|
) -> None:
|
|
"""Test end to end construction and search."""
|
|
texts = ["foo", "bar", "baz"]
|
|
docsearch = Qdrant.from_texts(
|
|
texts,
|
|
ConsistentFakeEmbeddings(),
|
|
location=":memory:",
|
|
content_payload_key=content_payload_key,
|
|
metadata_payload_key=metadata_payload_key,
|
|
batch_size=batch_size,
|
|
vector_name=vector_name,
|
|
)
|
|
output = docsearch.similarity_search_with_relevance_scores("foo", k=3)
|
|
|
|
assert all(
|
|
(1 >= score or np.isclose(score, 1)) and score >= 0 for _, score in output
|
|
)
|