id stringlengths 14 16 | source stringlengths 49 117 | text stringlengths 16 2.73k |
|---|---|---|
f332fa29cf90-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html | Source code for langchain.vectorstores.sklearn
""" Wrapper around scikit-learn NearestNeighbors implementation.
The vector store can be persisted in json, bson or parquet format.
"""
import json
import math
import os
from abc import ABC, abstractmethod
from typing import Any, Dict, Iterable, List, Literal, Optional, Tu... |
f332fa29cf90-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html | return json.load(fp)
class BsonSerializer(BaseSerializer):
"""Serializes data in binary json using the bson python package."""
def __init__(self, persist_path: str) -> None:
super().__init__(persist_path)
self.bson = guard_import("bson")
@classmethod
def extension(cls) -> str:
re... |
f332fa29cf90-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html | self.pq.write_table(table, self.persist_path)
def load(self) -> Any:
table = self.pq.read_table(self.persist_path)
df = table.to_pandas()
return {col: series.tolist() for col, series in df.items()}
SERIALIZER_MAP: Dict[str, Type[BaseSerializer]] = {
"json": JsonSerializer,
"bson": Bs... |
f332fa29cf90-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html | self._metadatas: List[dict] = []
self._ids: List[str] = []
# cache properties
self._embeddings_np: Any = np.asarray([])
if self._persist_path is not None and os.path.isfile(self._persist_path):
self._load()
[docs] def persist(self) -> None:
if self._serializer is N... |
f332fa29cf90-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html | self._embeddings.extend(self._embedding_function.embed_documents(_texts))
self._metadatas.extend(metadatas or ([{}] * len(_texts)))
self._ids.extend(_ids)
self._update_neighbors()
return _ids
def _update_neighbors(self) -> None:
if len(self._embeddings) == 0:
rais... |
f332fa29cf90-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html | metadata={"id": self._ids[idx], **self._metadatas[idx]},
),
dist,
)
for idx, dist in indices_dists
]
[docs] def similarity_search(
self, query: str, k: int = DEFAULT_K, **kwargs: Any
) -> List[Document]:
docs_scores = self.similarity... |
f332fa29cf90-6 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html | to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal marginal relevance.
"""
indices_dists = self._similarity_index_search_with_score(
embedding, k=fetch_k, **kwargs
)
indi... |
f332fa29cf90-7 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html | Defaults to 0.5.
Returns:
List of Documents selected by maximal marginal relevance.
"""
if self._embedding_function is None:
raise ValueError(
"For MMR search, you must specify an embedding function on creation."
)
embedding = self._emb... |
c7b047a55bb1-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html | Source code for langchain.vectorstores.vectara
"""Wrapper around Vectara vector database."""
from __future__ import annotations
import json
import logging
import os
from hashlib import md5
from typing import Any, Iterable, List, Optional, Tuple, Type
import requests
from pydantic import Field
from langchain.embeddings.... |
c7b047a55bb1-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html | "Cant find Vectara credentials, customer_id or corpus_id in "
"environment."
)
else:
logging.debug(f"Using corpus id {self._vectara_corpus_id}")
self._session = requests.Session() # to reuse connections
def _get_post_headers(self) -> dict:
"""Returns ... |
c7b047a55bb1-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html | request: dict[str, Any] = {}
request["customer_id"] = self._vectara_customer_id
request["corpus_id"] = self._vectara_corpus_id
request["document"] = {
"document_id": doc_id,
"metadataJson": json.dumps(metadata),
"section": [{"text": text, "metadataJson": json.... |
c7b047a55bb1-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html | if not succeeded:
self._delete_doc(doc_id)
self._index_doc(doc_id, doc, metadata)
return ids
[docs] def similarity_search_with_score(
self,
query: str,
k: int = 5,
alpha: float = 0.025,
filter: Optional[str] = None,
**kwargs: Any... |
c7b047a55bb1-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html | "metadataFilter": filter,
"lexical_interpolation_config": {"lambda": alpha},
}
],
}
]
}
),
timeout=10,
)
if response.status_... |
c7b047a55bb1-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html | List of Documents most similar to the query
"""
docs_and_scores = self.similarity_search_with_score(
query, k=k, alpha=alpha, filter=filter, **kwargs
)
return [doc for doc, _ in docs_and_scores]
[docs] @classmethod
def from_texts(
cls: Type[Vectara],
te... |
c7b047a55bb1-6 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html | documentation).
filter: Dictionary of argument(s) to filter on metadata. For example a
filter can be "doc.rating > 3.0 and part.lang = 'deu'"} see
https://docs.vectara.com/docs/search-apis/sql/filter-overview
for more details.
"""
def add_texts(
self, texts: L... |
65b41c193012-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html | Source code for langchain.vectorstores.zilliz
from __future__ import annotations
import logging
from typing import Any, List, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.milvus import Milvus
logger = logging.getLogger(__name__)
[docs]class Zilliz(Milvus):
def _create_index(... |
65b41c193012-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html | )
raise e
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
collection_name: str = "LangChainCollection",
connection_args: dict[str, Any] = {},
consistency_level: str = ... |
65b41c193012-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html | connection_args=connection_args,
consistency_level=consistency_level,
index_params=index_params,
search_params=search_params,
drop_old=drop_old,
**kwargs,
)
vector_db.add_texts(texts=texts, metadatas=metadatas)
return vector_db
By Harri... |
b2ac379c34ee-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html | Source code for langchain.vectorstores.base
"""Interface for vector stores."""
from __future__ import annotations
import asyncio
import warnings
from abc import ABC, abstractmethod
from functools import partial
from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, TypeVar
from pydantic import BaseModel, ... |
b2ac379c34ee-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html | Returns:
List[str]: List of IDs of the added texts.
"""
# TODO: Handle the case where the user doesn't provide ids on the Collection
texts = [doc.page_content for doc in documents]
metadatas = [doc.metadata for doc in documents]
return self.add_texts(texts, metadatas,... |
b2ac379c34ee-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html | if search_type == "similarity":
return await self.asimilarity_search(query, **kwargs)
elif search_type == "mmr":
return await self.amax_marginal_relevance_search(query, **kwargs)
else:
raise ValueError(
f"search_type of {search_type} not allowed. Expec... |
b2ac379c34ee-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html | f" 0 and 1, got {docs_and_similarities}"
)
score_threshold = kwargs.get("score_threshold")
if score_threshold is not None:
docs_and_similarities = [
(doc, similarity)
for doc, similarity in docs_and_similarities
if similarity >= sco... |
b2ac379c34ee-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html | """Return docs most similar to query."""
# This is a temporary workaround to make the similarity search
# asynchronous. The proper solution is to make the similarity search
# asynchronous in the vector store implementations.
func = partial(self.similarity_search, query, k, **kwargs)
... |
b2ac379c34ee-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html | Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
... |
b2ac379c34ee-6 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html | Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algor... |
b2ac379c34ee-7 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html | """Return VectorStore initialized from documents and embeddings."""
texts = [d.page_content for d in documents]
metadatas = [d.metadata for d in documents]
return await cls.afrom_texts(texts, embedding, metadatas=metadatas, **kwargs)
[docs] @classmethod
@abstractmethod
def from_texts(... |
b2ac379c34ee-8 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html | raise ValueError(f"search_type of {search_type} not allowed.")
if search_type == "similarity_score_threshold":
score_threshold = values["search_kwargs"].get("score_threshold")
if (score_threshold is None) or (
not isinstance(score_threshold, float)
... |
b2ac379c34ee-9 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html | docs = [doc for doc, _ in docs_and_similarities]
elif self.search_type == "mmr":
docs = await self.vectorstore.amax_marginal_relevance_search(
query, **self.search_kwargs
)
else:
raise ValueError(f"search_type of {self.search_type} not allowed.")
... |
bc8f21f09e0c-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html | Source code for langchain.vectorstores.lancedb
"""Wrapper around LanceDB vector database"""
from __future__ import annotations
import uuid
from typing import Any, Iterable, List, Optional
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.base i... |
bc8f21f09e0c-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html | [docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Turn texts into embedding and add it to the database
Args:
texts: Iterable of strings to... |
bc8f21f09e0c-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html | page_content=row[self._text_key],
metadata=row[docs.columns != self._text_key],
)
for _, row in docs.iterrows()
]
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = Non... |
bde007beda6b-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html | Source code for langchain.vectorstores.annoy
"""Wrapper around Annoy vector database."""
from __future__ import annotations
import os
import pickle
import uuid
from configparser import ConfigParser
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
from l... |
bde007beda6b-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html | self.index = index
self.metric = metric
self.docstore = docstore
self.index_to_docstore_id = index_to_docstore_id
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
raise NotImple... |
bde007beda6b-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html | to n_trees * n if not provided
Returns:
List of Documents most similar to the query and score for each
"""
idxs, dists = self.index.get_nns_by_vector(
embedding, k, search_k=search_k, include_distances=True
)
return self.process_index_results(idxs, dists)
... |
bde007beda6b-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html | docs = self.similarity_search_with_score_by_vector(embedding, k, search_k)
return docs
[docs] def similarity_search_by_vector(
self, embedding: List[float], k: int = 4, search_k: int = -1, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to embedding vector.
Args:
... |
bde007beda6b-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html | self, query: str, k: int = 4, search_k: int = -1, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
search_k: inspect up to search_k nodes wh... |
bde007beda6b-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html | )
embeddings = [self.index.get_item_vector(i) for i in idxs]
mmr_selected = maximal_marginal_relevance(
np.array([embedding], dtype=np.float32),
embeddings,
k=k,
lambda_mult=lambda_mult,
)
# ignore the -1's if not enough docs are returned/i... |
bde007beda6b-6 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html | embedding = self.embedding_function(query)
docs = self.max_marginal_relevance_search_by_vector(
embedding, k, fetch_k, lambda_mult=lambda_mult
)
return docs
@classmethod
def __from(
cls,
texts: List[str],
embeddings: List[List[float]],
embeddin... |
bde007beda6b-7 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html | [docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
metric: str = DEFAULT_METRIC,
trees: int = 100,
n_jobs: int = -1,
**kwargs: Any,
) -> Annoy:
"""Construct Annoy wra... |
bde007beda6b-8 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html | metric: str = DEFAULT_METRIC,
trees: int = 100,
n_jobs: int = -1,
**kwargs: Any,
) -> Annoy:
"""Construct Annoy wrapper from embeddings.
Args:
text_embeddings: List of tuples of (text, embedding)
embedding: Embedding function to use.
metada... |
bde007beda6b-9 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html | folder_path: folder path to save index, docstore,
and index_to_docstore_id to.
prefault: Whether to pre-load the index into memory.
"""
path = Path(folder_path)
os.makedirs(path, exist_ok=True)
# save index, index config, docstore and index_to_docstore_id
... |
bde007beda6b-10 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html | index.load(str(path / "index.annoy"))
return cls(
embeddings.embed_query, index, metric, docstore, index_to_docstore_id
)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
aa5b1e44ea00-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | Source code for langchain.vectorstores.redis
"""Wrapper around Redis vector database."""
from __future__ import annotations
import json
import logging
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,... |
aa5b1e44ea00-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | "Please head to https://redis.io/docs/stack/search/quick_start/"
"to know more about installing the RediSearch module within Redis Stack."
)
logging.error(error_message)
raise ValueError(error_message)
def _check_index_exists(client: RedisType, index_name: str) -> bool:
"""Check if Redis index e... |
aa5b1e44ea00-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | vector_key: str = "content_vector",
relevance_score_fn: Optional[
Callable[[float], float]
] = _default_relevance_score,
**kwargs: Any,
):
"""Initialize with necessary components."""
try:
import redis
except ImportError:
raise Value... |
aa5b1e44ea00-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | self.vector_key,
"FLAT",
{
"TYPE": "FLOAT32",
"DIM": dim,
"DISTANCE_METRIC": distance_metric,
},
),
)
prefix = _redis_prefix(self.index_name)
... |
aa5b1e44ea00-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | key = keys[i] if keys else _redis_key(prefix)
metadata = metadatas[i] if metadatas else {}
embedding = embeddings[i] if embeddings else self.embedding_function(text)
pipeline.hset(
key,
mapping={
self.content_key: text,
... |
aa5b1e44ea00-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | k (int): The number of documents to return. Default is 4.
score_threshold (float): The minimum matching score required for a document
to be considered a match. Defaults to 0.2.
Because the similarity calculation algorithm is based on cosine similarity,
the smaller the ang... |
aa5b1e44ea00-6 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most similar to the query and score for each
"""
# Creates embedding vector from user query
embedding = self.embedding_functi... |
aa5b1e44ea00-7 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
index_name: Optional[str] = None,
content_key: str = "content",
metadata_key: str = "metadata",
vector_key: str = "content_vector",
distance_metric: REDIS_DISTANCE_METRIC... |
aa5b1e44ea00-8 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | embeddings = embedding.embed_documents(texts)
# Create the search index
instance._create_index(dim=len(embeddings[0]), distance_metric=distance_metric)
# Add data to Redis
keys = instance.add_texts(texts, metadatas, embeddings)
return instance, keys
[docs] @classmethod
def... |
aa5b1e44ea00-9 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | [docs] @staticmethod
def drop_index(
index_name: str,
delete_documents: bool,
**kwargs: Any,
) -> bool:
"""
Drop a Redis search index.
Args:
index_name (str): Name of the index to drop.
delete_documents (bool): Whether to drop the associ... |
aa5b1e44ea00-10 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL")
try:
import redis
except ImportError:
raise ValueError(
"Could not import redis python package. "
"Please install it with `pip install redis`."
)
try:
... |
aa5b1e44ea00-11 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html | def validate_search_type(cls, values: Dict) -> Dict:
"""Validate search type."""
if "search_type" in values:
search_type = values["search_type"]
if search_type not in ("similarity", "similarity_limit"):
raise ValueError(f"search_type of {search_type} not allowed."... |
e19d338338cf-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html | Source code for langchain.vectorstores.supabase
from __future__ import annotations
from itertools import repeat
from typing import (
TYPE_CHECKING,
Any,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import numpy as np
from langchain.docstore.document import Document
from langchain.embe... |
e19d338338cf-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html | query_name: Union[str, None] = None,
) -> None:
"""Initialize with supabase client."""
try:
import supabase # noqa: F401
except ImportError:
raise ValueError(
"Could not import supabase python package. "
"Please install it with `pip in... |
e19d338338cf-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html | docs = cls._texts_to_documents(texts, metadatas)
_ids = cls._add_vectors(client, table_name, embeddings, docs)
return cls(
client=client,
embedding=embedding,
table_name=table_name,
query_name=query_name,
)
[docs] def add_vectors(
self, ... |
e19d338338cf-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html | res = self._client.rpc(self.query_name, match_documents_params).execute()
match_result = [
(
Document(
metadata=search.get("metadata", {}), # type: ignore
page_content=search.get("content", ""),
),
search.get("s... |
e19d338338cf-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html | docs = [
Document(page_content=text, metadata=metadata)
for text, metadata in zip(texts, metadatas)
]
return docs
@staticmethod
def _add_vectors(
client: supabase.client.Client,
table_name: str,
vectors: List[List[float]],
documents: List[D... |
e19d338338cf-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html | """Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
... |
e19d338338cf-6 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html | k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity... |
3f6ed0b707ea-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | Source code for langchain.vectorstores.qdrant
"""Wrapper around Qdrant vector database."""
from __future__ import annotations
import uuid
import warnings
from itertools import islice
from operator import itemgetter
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Opti... |
3f6ed0b707ea-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | embedding_function: Optional[Callable] = None, # deprecated
):
"""Initialize with necessary components."""
try:
import qdrant_client
except ImportError:
raise ValueError(
"Could not import qdrant-client python package. "
"Please instal... |
3f6ed0b707ea-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | self.embeddings = None
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[Sequence[str]] = None,
batch_size: int = 64,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to th... |
3f6ed0b707ea-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | ),
),
)
added_ids.extend(batch_ids)
return added_ids
[docs] def similarity_search(
self,
query: str,
k: int = 4,
filter: Optional[MetadataFilter] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar... |
3f6ed0b707ea-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | results = self.client.search(
collection_name=self.collection_name,
query_vector=self._embed_query(query),
query_filter=qdrant_filter,
with_payload=True,
limit=k,
)
return [
(
self._document_from_scored_point(
... |
3f6ed0b707ea-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | mmr_selected = maximal_marginal_relevance(
np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult
)
return [
self._document_from_scored_point(
results[i], self.content_payload_key, self.metadata_payload_key
)
for i in mmr_selected
... |
3f6ed0b707ea-6 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | length as a list of texts.
ids:
Optional list of ids to associate with the texts. Ids have to be
uuid-like strings.
location:
If `:memory:` - use in-memory Qdrant instance.
If `str` - use it as a `url` parameter.
If ... |
3f6ed0b707ea-7 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | Distance function. One of: "Cosine" / "Euclid" / "Dot".
Default: "Cosine"
content_payload_key:
A payload key used to store the content of the document.
Default: "page_content"
metadata_payload_key:
A payload key used to store the me... |
3f6ed0b707ea-8 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | client = qdrant_client.QdrantClient(
location=location,
url=url,
port=port,
grpc_port=grpc_port,
prefer_grpc=prefer_grpc,
https=https,
api_key=api_key,
prefix=prefix,
timeout=timeout,
host=host,
... |
3f6ed0b707ea-9 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | @classmethod
def _build_payloads(
cls,
texts: Iterable[str],
metadatas: Optional[List[dict]],
content_payload_key: str,
metadata_payload_key: str,
) -> List[dict]:
payloads = []
for i, text in enumerate(texts):
if text is None:
... |
3f6ed0b707ea-10 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | out.append(
rest.FieldCondition(
key=f"{self.metadata_payload_key}.{key}",
match=rest.MatchValue(value=value),
)
)
return out
def _qdrant_filter_from_dict(
self, filter: Optional[DictFilter]
) -> Optional[rest.Fi... |
3f6ed0b707ea-11 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html | elif self._embeddings_function is not None:
embeddings = []
for text in texts:
embedding = self._embeddings_function(text)
if hasattr(embeddings, "tolist"):
embedding = embedding.tolist()
embeddings.append(embedding)
els... |
9595540463dd-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | Source code for langchain.vectorstores.milvus
"""Wrapper around the Milvus vector database."""
from __future__ import annotations
import logging
from typing import Any, Iterable, List, Optional, Tuple, Union
from uuid import uuid4
import numpy as np
from langchain.docstore.document import Document
from langchain.embedd... |
9595540463dd-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | The connection args used for this class comes in the form of a dict,
here are a few of the options:
address (str): The actual address of Milvus
instance. Example address: "localhost:19530"
uri (str): The uri of Milvus instance. Example uri:
"http://randomw... |
9595540463dd-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | embedding_function (Embeddings): Function used to embed the text.
collection_name (str): Which Milvus collection to use. Defaults to
"LangChainCollection".
connection_args (Optional[dict[str, any]]): The arguments for connection to
Milvus/Zilliz instance. Defaults... |
9595540463dd-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | "RHNSW_SQ": {"metric_type": "L2", "params": {"ef": 10}},
"RHNSW_PQ": {"metric_type": "L2", "params": {"ef": 10}},
"IVF_HNSW": {"metric_type": "L2", "params": {"nprobe": 10, "ef": 10}},
"ANNOY": {"metric_type": "L2", "params": {"search_k": 10}},
"AUTOINDEX": {"metric_type"... |
9595540463dd-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | self.col.drop()
self.col = None
# Initialize the vector store
self._init()
def _create_connection_alias(self, connection_args: dict) -> str:
"""Create the connection to the Milvus server."""
from pymilvus import MilvusException, connections
# Grab the connection a... |
9595540463dd-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | logger.debug("Using previous connection: %s", con[0])
return con[0]
# Generate a new connection if one doesnt exist
alias = uuid4().hex
try:
connections.connect(alias=alias, **connection_args)
logger.debug("Created new connection using: %s", alias)
... |
9595540463dd-6 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | key,
)
raise ValueError(f"Unrecognized datatype for {key}.")
# Dataype is a string/varchar equivalent
elif dtype == DataType.VARCHAR:
fields.append(FieldSchema(key, DataType.VARCHAR, max_length=65_535))
else:
... |
9595540463dd-7 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | def _get_index(self) -> Optional[dict[str, Any]]:
"""Return the vector index information if it exists"""
from pymilvus import Collection
if isinstance(self.col, Collection):
for x in self.col.indexes:
if x.field_name == self._vector_field:
return x... |
9595540463dd-8 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | "Failed to create an index on collection: %s", self.collection_name
)
raise e
def _create_search_params(self) -> None:
"""Generate search params based on the current index type"""
from pymilvus import Collection
if isinstance(self.col, Collection) and self.sea... |
9595540463dd-9 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | metadatas (Optional[List[dict]]): Metadata dicts attached to each of
the texts. Defaults to None.
timeout (Optional[int]): Timeout for each batch insert. Defaults
to None.
batch_size (int, optional): Batch size to use for insertion.
Defaults to 100... |
9595540463dd-10 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | end = min(i + batch_size, total_count)
# Convert dict to list of lists batch for insertion
insert_list = [insert_dict[x][i:end] for x in self.fields]
# Insert into the collection.
try:
res: Collection
res = self.col.insert(insert_list, time... |
9595540463dd-11 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | return [doc for doc, _ in res]
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform ... |
9595540463dd-12 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | For more information about the search parameters, take a look at the pymilvus
documentation found here:
https://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md
Args:
query (str): The text being searched.
k (int, optional): The amount of results ot return. D... |
9595540463dd-13 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | https://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md
Args:
embedding (List[float]): The embedding vector being searched.
k (int, optional): The amount of results ot return. Defaults to 4.
param (dict): The search params for the specified index.
... |
9595540463dd-14 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | fetch_k: int = 20,
lambda_mult: float = 0.5,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a search and return results that are reordered by MMR.
Args:
query ... |
9595540463dd-15 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | embedding: list[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
param: Optional[dict] = None,
expr: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a search and return results that ar... |
9595540463dd-16 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | expr=expr,
output_fields=output_fields,
timeout=timeout,
**kwargs,
)
# Organize results.
ids = []
documents = []
scores = []
for result in res[0]:
meta = {x: result.entity.get(x) for x in output_fields}
doc = Doc... |
9595540463dd-17 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | consistency_level: str = "Session",
index_params: Optional[dict] = None,
search_params: Optional[dict] = None,
drop_old: bool = False,
**kwargs: Any,
) -> Milvus:
"""Create a Milvus collection, indexes it with HNSW, and insert data.
Args:
texts (List[str])... |
9595540463dd-18 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html | © Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
4cc62cbdecea-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html | Source code for langchain.vectorstores.mongodb_atlas
from __future__ import annotations
import logging
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from langchain.docstore.document import Document
from langchain.embe... |
4cc62cbdecea-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html | embedding: Text embedding model to use.
text_key: MongoDB field that will contain the text for each
document.
embedding_key: MongoDB field that will contain the embedding for
each document.
"""
self._collection = collection
self._embedding ... |
4cc62cbdecea-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html | texts_batch = []
metadatas_batch = []
result_ids = []
for i, (text, metadata) in enumerate(zip(texts, _metadatas)):
texts_batch.append(text)
metadatas_batch.append(metadata)
if (i + 1) % batch_size == 0:
result_ids.extend(self._insert_texts(tex... |
4cc62cbdecea-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html | early access users. It is not recommended for production deployments as we
may introduce breaking changes.
For more: https://www.mongodb.com/docs/atlas/atlas-search/knn-beta
Args:
query: Text to look up documents similar to.
k: Optional Number of Documents to return. Defa... |
4cc62cbdecea-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html | **kwargs: Any,
) -> List[Document]:
"""Return MongoDB documents most similar to query.
Use the knnBeta Operator available in MongoDB Atlas Search
This feature is in early access and available only for evaluation purposes, to
validate functionality, and to gather feedback from a small... |
4cc62cbdecea-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html | This is intended to be a quick way to get started.
Example:
.. code-block:: python
from pymongo import MongoClient
from langchain.vectorstores import MongoDBAtlasVectorSearch
from langchain.embeddings import OpenAIEmbeddings
client = Mo... |
824167dadd07-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html | Source code for langchain.vectorstores.chroma
"""Wrapper around ChromaDB embeddings platform."""
from __future__ import annotations
import logging
import uuid
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type
import numpy as np
from langchain.docstore.document import Document
from langc... |
824167dadd07-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html | _LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain"
def __init__(
self,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
embedding_function: Optional[Embeddings] = None,
persist_directory: Optional[str] = None,
client_settings: Optional[chromadb.config.Settings] = None... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.