id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
efb92b8561a3-1 | self._text_key = text_key
@property
def embeddings(self) -> Embeddings:
return self._embedding
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
efb92b8561a3-2 | Returns:
List of documents most similar to the query.
"""
embedding = self._embedding.embed_query(query)
docs = self._connection.search(embedding).limit(k).to_df()
return [
Document(
page_content=row[self._text_key],
metadata=row[do... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
5fec310b6df0-0 | Source code for langchain.vectorstores.pgvector
from __future__ import annotations
import asyncio
import contextlib
import enum
import logging
import uuid
from functools import partial
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-1 | [docs]class PGVector(VectorStore):
"""`Postgres`/`PGVector` vector store.
To use, you should have the ``pgvector`` python package installed.
Args:
connection_string: Postgres connection string.
embedding_function: Any embedding function implementing
`langchain.embeddings.base.Emb... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-2 | distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
pre_delete_collection: bool = False,
logger: Optional[logging.Logger] = None,
relevance_score_fn: Optional[Callable[[float], float]] = None,
*,
connection: Optional[sqlalchemy.engine.Connection] = None,
engi... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-3 | conn = engine.connect()
return conn
[docs] def create_vector_extension(self) -> None:
try:
with Session(self._conn) as session:
# The advisor lock fixes issue arising from concurrent
# creation of the vector extension.
# https://github.com/l... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-4 | return
session.delete(collection)
session.commit()
@contextlib.contextmanager
def _make_session(self) -> Generator[Session, None, None]:
"""Create a context manager for the session, bind to _conn string."""
yield Session(self._conn)
[docs] def delete(
self,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-5 | ids = [str(uuid.uuid1()) for _ in texts]
if not metadatas:
metadatas = [{} for _ in texts]
if connection_string is None:
connection_string = cls.get_connection_string(kwargs)
store = cls(
connection_string=connection_string,
collection_name=collect... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-6 | embedding_store = self.EmbeddingStore(
embedding=embedding,
document=text,
cmetadata=metadata,
custom_id=id,
collection_id=collection.uuid,
)
session.add(embedding_store)
sessi... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-7 | """
embedding = self.embedding_function.embed_query(text=query)
return self.similarity_search_by_vector(
embedding=embedding,
k=k,
filter=filter,
)
[docs] def similarity_search_with_score(
self,
query: str,
k: int = 4,
filter... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-8 | self,
embedding: List[float],
k: int = 4,
filter: Optional[dict] = None,
) -> List[Tuple[Document, float]]:
results = self.__query_collection(embedding=embedding, k=k, filter=filter)
return self._results_to_docs_and_scores(results)
def _results_to_docs_and_scores(self, re... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-9 | filter_clauses.append(filter_by_metadata)
else:
filter_by_metadata = self.EmbeddingStore.cmetadata[
key
].astext == str(value)
filter_clauses.append(filter_by_metadata)
filter_by = sql... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-10 | texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
ids: Optional[List[str]] = None,
pre_delete_collection: bool = Fals... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-11 | Example:
.. code-block:: python
from langchain.vectorstores import PGVector
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text_embeddings = embeddings.embed_documents(texts)
text_embedding_pai... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-12 | def get_connection_string(cls, kwargs: Dict[str, Any]) -> str:
connection_string: str = get_from_dict_or_env(
data=kwargs,
key="connection_string",
env_key="PGVECTOR_CONNECTION_STRING",
)
if not connection_string:
raise ValueError(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-13 | def connection_string_from_db_params(
cls,
driver: str,
host: str,
port: int,
database: str,
user: str,
password: str,
) -> str:
"""Return connection string from database parameters."""
return f"postgresql+{driver}://{user}:{password}@{host}:{p... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-14 | k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs selected using the maximal marginal relevance with score
to embedding vector.
Maximal margina... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-15 | [docs] def max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal rele... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-16 | filter: Optional[dict] = None,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs selected using the maximal marginal relevance with score.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-17 | **kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance
to embedding vector.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
embedding (str): Text to look u... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
5fec310b6df0-18 | # 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.max_marginal_relevance_search_by_vector,
embedding,
k=k... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
cb7de7174d73-0 | Source code for langchain.vectorstores.typesense
from __future__ import annotations
import uuid
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embeddings
from langchain.schema.vectorstore import Vecto... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
cb7de7174d73-1 | *,
typesense_collection_name: Optional[str] = None,
text_key: str = "text",
):
"""Initialize with Typesense client."""
try:
from typesense import Client
except ImportError:
raise ImportError(
"Could not import typesense python package. ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
cb7de7174d73-2 | for _id, vec, text, metadata in zip(_ids, embedded_texts, texts, _metadatas)
]
def _create_collection(self, num_dim: int) -> None:
fields = [
{"name": "vec", "type": "float[]", "num_dim": num_dim},
{"name": f"{self._text_key}", "type": "string"},
{"name": ".*", "t... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
cb7de7174d73-3 | return [doc["id"] for doc in docs]
[docs] def similarity_search_with_score(
self,
query: str,
k: int = 10,
filter: Optional[str] = "",
) -> List[Tuple[Document, float]]:
"""Return typesense documents most similar to query, along with scores.
Args:
query... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
cb7de7174d73-4 | ) -> List[Document]:
"""Return typesense documents most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 10.
Minimum 10 results would be returned.
filter: typesense filter_by expression ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
cb7de7174d73-5 | "Please install it with `pip install typesense`."
)
node = {
"host": host,
"port": str(port),
"protocol": protocol,
}
typesense_api_key = typesense_api_key or get_from_env(
"typesense_api_key", "TYPESENSE_API_KEY"
)
clie... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
af33f86b6972-0 | Source code for langchain.vectorstores.usearch
from __future__ import annotations
from typing import Any, Dict, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.base import AddableMixin, Docstore
from langchain.docstore.document import Document
from langchain.docstore.in_memory import InMemory... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html |
af33f86b6972-1 | Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
ids: Optional list of unique IDs.
Returns:
List of ids from adding the texts into the vectorstore.
"""
if not isinstance(se... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html |
af33f86b6972-2 | matches = self.index.search(np.array(query_embedding), k)
docs_with_scores: List[Tuple[Document, float]] = []
for id, score in zip(matches.keys, matches.distances):
doc = self.docstore.search(str(id))
if not isinstance(doc, Document):
raise ValueError(f"Could not ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html |
af33f86b6972-3 | This is a user friendly interface that:
1. Embeds documents.
2. Creates an in memory docstore
3. Initializes the USearch database
This is intended to be a quick way to get started.
Example:
.. code-block:: python
from langchain.vectorstores... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html |
6000f17d8a69-0 | Source code for langchain.vectorstores.alibabacloud_opensearch
import json
import logging
import numbers
from hashlib import sha1
from typing import Any, Dict, Iterable, List, Optional, Tuple
from langchain.schema import Document
from langchain.schema.embeddings import Embeddings
from langchain.schema.vectorstore impor... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
6000f17d8a69-1 | }
protocol (str): Communication Protocol between SDK and Server, default is http.
namespace (str) : The instance data will be partitioned based on the "namespace"
field,If the namespace is enabled, you need to specify the namespace field
name during initialization, Otherwise, the queri... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
6000f17d8a69-2 | self.inverse_field_name_mapping[value.split(",")[0]] = key
def __getitem__(self, item: str) -> Any:
return getattr(self, item)
[docs]def create_metadata(fields: Dict[str, Any]) -> Dict[str, Any]:
"""Create metadata from fields.
Args:
fields: The fields of the document. The fields must be a d... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
6000f17d8a69-3 | )
self.ha3_engine_client = client.Client(
models.Config(
endpoint=config.endpoint,
instance_id=config.instance_id,
protocol=config.protocol,
access_user_name=config.username,
access_pass_word=config.password,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
6000f17d8a69-4 | e,
)
raise e
from alibabacloud_ha3engine_vector import models
id_list = [sha1(t.encode("utf-8")).hexdigest() for t in texts]
embeddings = self.embedding.embed_documents(list(texts))
metadatas = metadatas or [{} for _ in texts]
field_name_map = self... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
6000f17d8a69-5 | self,
query: str,
k: int = 4,
search_filter: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform similarity retrieval based on text.
Args:
query: Vectorize text for retrieval.,should not be empty.
k: top n.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
6000f17d8a69-6 | ) -> List[Document]:
"""Perform retrieval directly using vectors.
Args:
embedding: vectors.
k: top n.
search_filter: Additional filtering conditions.
Returns:
document_list: List of documents.
"""
return self.create_results(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
6000f17d8a69-7 | return f'{md_filter_key}{md_filter_operator}"{md_value}"'
def search_data() -> Dict[str, Any]:
request = QueryRequest(
table_name=self.config.table_name,
namespace=self.config.namespace,
vector=embedding,
include_vector=True,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
6000f17d8a69-8 | fields = item["fields"]
query_result_list.append(
Document(
page_content=fields[self.config.field_name_mapping["document"]],
metadata=self.create_inverse_metadata(fields),
)
)
return query_res... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
6000f17d8a69-9 | [docs] def delete_documents_with_texts(self, texts: List[str]) -> bool:
"""Delete documents based on their page content.
Args:
texts: List of document page content.
Returns:
Whether the deletion was successful or not.
"""
id_list = [sha1(t.encode("utf-8"... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
6000f17d8a69-10 | e,
)
raise e
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
config: Optional[AlibabaCloudOpenSearchSettings] = None,
**kwargs: Any,
) -> "AlibabaCloudOpenSearch":... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
6000f17d8a69-11 | documents: Documents to be inserted into the vector storage,
should not be empty.
embedding: Embedding function, Embedding function.
config: Alibaba OpenSearch instance configuration.
ids: Specify the ID for the inserted document. If left empty, the ID will be
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
384da15d45c4-0 | Source code for langchain.vectorstores.annoy
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 langchain.docstore.base import Docstore
from ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
384da15d45c4-1 | self.embedding_function = embedding_function
self.index = index
self.metric = metric
self.docstore = docstore
self.index_to_docstore_id = index_to_docstore_id
@property
def embeddings(self) -> Optional[Embeddings]:
# TODO: Accept embedding object directly
return N... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
384da15d45c4-2 | """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 which defaults
to n_trees * n if not provided
Returns:
List of ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
384da15d45c4-3 | 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 which defaults
to n_trees * n if not provided
Returns:
List of Documents most similar to the query and score ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
384da15d45c4-4 | to n_trees * n if not provided
Returns:
List of Documents most similar to the embedding.
"""
docs_and_scores = self.similarity_search_with_score_by_index(
docstore_index, k, search_k
)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_sea... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
384da15d45c4-5 | lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
384da15d45c4-6 | 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.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among th... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
384da15d45c4-7 | index.build(trees, n_jobs=n_jobs)
documents = []
for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
documents.append(Document(page_content=text, metadata=metadata))
index_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))}
docs... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
384da15d45c4-8 | .. code-block:: python
from langchain.vectorstores import Annoy
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
index = Annoy.from_texts(texts, embeddings)
"""
embeddings = embedding.embed_documents(texts)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
384da15d45c4-9 | embeddings = OpenAIEmbeddings()
text_embeddings = embeddings.embed_documents(texts)
text_embedding_pairs = list(zip(texts, text_embeddings))
db = Annoy.from_embeddings(text_embedding_pairs, embeddings)
"""
texts = [t[0] for t in text_embeddings]
em... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
384da15d45c4-10 | Args:
folder_path: folder path to load index, docstore,
and index_to_docstore_id from.
embeddings: Embeddings to use when generating queries.
"""
path = Path(folder_path)
# load index separately since it is not picklable
annoy = dependable_annoy_im... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
7b8b53e55210-0 | Source code for langchain.vectorstores.docarray.base
from abc import ABC
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type
import numpy as np
from langchain.pydantic_v1 import Field
from langchain.schema import Document
from langchain.schema.embeddings import Embeddings
from langchain.schema.... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html |
7b8b53e55210-1 | def _get_doc_cls(**embeddings_params: Any) -> Type["BaseDoc"]:
"""Get docarray Document class describing the schema of DocIndex."""
from docarray import BaseDoc
from docarray.typing import NdArray
class DocArrayDoc(BaseDoc):
text: Optional[str]
embedding: Optional... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html |
7b8b53e55210-2 | self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of documents most similar... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html |
7b8b53e55210-3 | """Return docs and relevance scores, normalized on a scale from 0 to 1.
0 is dissimilar, 1 is most similar.
"""
raise NotImplementedError()
[docs] def similarity_search_by_vector(
self, embedding: List[float], k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs m... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html |
7b8b53e55210-4 | of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal marginal relevance.
"""
query_embedding = self.embedding.embed_query(query)
que... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html |
b988c1177e44-0 | Source code for langchain.vectorstores.docarray.hnsw
from __future__ import annotations
from typing import Any, List, Literal, Optional
from langchain.schema.embeddings import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_docarray_import,
)
[docs]class DocArrayHnswSearch(Do... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
b988c1177e44-1 | "cosine", "ip", and "l2". Defaults to "cosine".
max_elements (int): Maximum number of vectors that can be stored.
Defaults to 1024.
index (bool): Whether an index should be built for this field.
Defaults to True.
ef_construction (int): defines a constr... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
b988c1177e44-2 | work_dir: Optional[str] = None,
n_dim: Optional[int] = None,
**kwargs: Any,
) -> DocArrayHnswSearch:
"""Create an DocArrayHnswSearch store and insert data.
Args:
texts (List[str]): Text data.
embedding (Embeddings): Embedding function.
metadatas (O... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
36d2b2044acb-0 | Source code for langchain.vectorstores.docarray.in_memory
"""Wrapper around in-memory storage."""
from __future__ import annotations
from typing import Any, Dict, List, Literal, Optional
from langchain.schema.embeddings import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_d... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
36d2b2044acb-1 | [docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[Dict[Any, Any]]] = None,
**kwargs: Any,
) -> DocArrayInMemorySearch:
"""Create an DocArrayInMemorySearch store and insert data.
Args:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
e04c01785db2-0 | Source code for langchain.vectorstores.redis.schema
from __future__ import annotations
import os
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import numpy as np
import yaml
from typing_extensions import TYPE_CHECKING, Literal
from langchain.pydantic_v1 import BaseMo... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
e04c01785db2-1 | """Schema for tag fields in Redis."""
separator: str = ","
case_sensitive: bool = False
no_index: bool = False
sortable: Optional[bool] = False
[docs] def as_field(self) -> TagField:
from redis.commands.search.field import TagField # type: ignore
return TagField(
self.nam... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
e04c01785db2-2 | )
return v.upper()
def _fields(self) -> Dict[str, Any]:
field_data = {
"TYPE": self.datatype,
"DIM": self.dims,
"DISTANCE_METRIC": self.distance_metric,
}
if self.initial_cap is not None: # Only include it if it's set
field_data["INITI... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
e04c01785db2-3 | "EF_RUNTIME": self.ef_runtime,
"EPSILON": self.epsilon,
}
)
return VectorField(self.name, self.algorithm, field_data)
[docs]class RedisModel(BaseModel):
"""Schema for Redis index."""
# always have a content field for text
text: List[TextFieldSchema] = [TextFieldSc... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
e04c01785db2-4 | f"algorithm must be either FLAT or HNSW. Got "
f"{vector_field['algorithm']}"
)
[docs] def as_dict(self) -> Dict[str, List[Any]]:
schemas: Dict[str, List[Any]] = {"text": [], "tag": [], "numeric": []}
# iter over all class attributes
for attr, attr_value in self.__... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
e04c01785db2-5 | if field.name == self.content_vector_key:
return field
raise ValueError("No content_vector field found")
@property
def vector_dtype(self) -> np.dtype:
# should only ever be called after pydantic has validated the schema
return REDIS_VECTOR_DTYPE_MAP[self.content_vector.da... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
e04c01785db2-6 | ) -> Dict[str, Any]:
"""Reads in the index schema from a dict or yaml file.
Check if it is a dict and return RedisModel otherwise, check if it's a path and
read in the file assuming it's a yaml file and return a RedisModel
"""
if isinstance(index_schema, dict):
return index_schema
elif i... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
dc70e738e6bd-0 | Source code for langchain.vectorstores.redis.base
"""Wrapper around Redis vector database."""
from __future__ import annotations
import logging
import os
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
Tuple,
Type,
Union... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-1 | return False
logger.info("Index already exists")
return True
[docs]class Redis(VectorStore):
"""Redis vector database.
To use, you should have the ``redis`` python package installed
and have a running Redis Enterprise or Redis-Stack server
For production use cases, it is recommended to use Redis... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-2 | documents, # a list of Document objects from loaders or created
embeddings, # an Embeddings object
redis_url="redis://localhost:6379",
)
Initialize, create index, and load Documents with metadata
.. code-block:: python
rds = Redis.from_texts(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-3 | for production use cases where you want to optimize the
vector schema for your use case. ex. using HNSW instead of
FLAT (knn) which is the default
.. code-block:: python
vector_schema = {
"algorithm": "HNSW"
}
rds = Redis.from_texts(
te... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-4 | the yaml config (can also be a dictionary) above and the code below.
.. code-block:: python
rds = Redis.from_texts(
texts, # a list of strings
metadata, # a list of metadata dicts
embeddings, # an Embeddings object
index_schema="path/to... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-5 | raise ImportError(
"Could not import redis python package. "
"Please install it with `pip install redis`."
) from e
self.index_name = index_name
self._embeddings = embedding
try:
redis_client = get_client(redis_url=redis_url, **kwargs)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-6 | 3. Adds the documents to the newly created Redis index.
4. Returns the keys of the newly created documents once stored.
This method will generate schema based on the metadata passed in
if the `index_schema` is not defined. If the `index_schema` is defined,
it will compare against the... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-7 | vector schema to use. Defaults to None.
**kwargs (Any): Additional keyword arguments to pass to the Redis client.
Returns:
Tuple[Redis, List[str]]: Tuple of the Redis instance and the keys of
the newly created documents.
Raises:
ValueError: If the numb... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-8 | raise ValueError("Metadatas must be a list of dicts")
generated_schema = _generate_field_schema(metadatas[0])
if index_schema:
# read in the schema solely to compare to the generated schema
user_schema = read_schema(index_schema) # type: ignore
# ... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-9 | **kwargs: Any,
) -> Redis:
"""Create a Redis vectorstore from a list of texts.
This is a user-friendly interface that:
1. Embeds documents.
2. Creates a new Redis index if it doesn't already exist
3. Adds the documents to the newly created Redis index.
Thi... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-10 | or add to. Defaults to None.
index_schema (Optional[Union[Dict[str, str], str, os.PathLike]], optional):
Optional fields to index within the metadata. Overrides generated
schema. Defaults to None.
vector_schema (Optional[Dict[str, Union[str, int]]], optional): Opt... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-11 | for embedding queries.
index_name (str): Name of the index to connect to.
schema (Union[Dict[str, str], str, os.PathLike]): Schema of the index
and the vector schema. Can be a dict, or path to yaml file
**kwargs (Any): Additional keyword arguments to pass to the Redis... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-12 | """Write the schema to a yaml file."""
with open(path, "w+") as f:
yaml.dump(self.schema, f)
[docs] @staticmethod
def delete(
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> bool:
"""
Delete a Redis entry.
Args:
ids: List of ids (ke... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-13 | return True
except: # noqa: E722
# ids does not exist
return False
[docs] @staticmethod
def drop_index(
index_name: str,
delete_documents: bool,
**kwargs: Any,
) -> bool:
"""
Drop a Redis search index.
Args:
index_na... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-14 | batch_size: int = 1000,
clean_metadata: bool = True,
**kwargs: Any,
) -> List[str]:
"""Add more texts to the vectorstore.
Args:
texts (Iterable[str]): Iterable of strings/text to add to the vectorstore.
metadatas (Optional[List[dict]], optional): Optional list... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-15 | # Use provided values by default or fallback
key = keys_or_ids[i] if keys_or_ids else str(uuid.uuid4().hex)
if not key.startswith(self.key_prefix + ":"):
key = self.key_prefix + ":" + key
metadata = metadatas[i] if metadatas else {}
metadata = _prepare_met... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-16 | Args:
query (str): The query text for which to find similar documents.
k (int): The number of documents to return. Default is 4.
score_threshold (float): The minimum matching *distance* required
for a document to be considered a match. Defaults to 0.2.
Returns... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-17 | """
try:
import redis
except ImportError as e:
raise ImportError(
"Could not import redis python package. "
"Please install it with `pip install redis`."
) from e
if "score_threshold" in kwargs:
logger.warning(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-18 | metadata = {"id": result.id}
metadata.update(self._collect_metadata(result))
doc = Document(page_content=result.content, metadata=metadata)
distance = self._calculate_fp_distance(result.distance)
docs_with_scores.append((doc, distance))
return docs_with_scores... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-19 | return_metadata: bool = True,
distance_threshold: Optional[float] = None,
**kwargs: Any,
) -> List[Document]:
"""Run similarity search between a query vector and the indexed vectors.
Args:
embedding (List[float]): The query vector for which to find similar
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-20 | # ignore type because redis-py is wrong about bytes
try:
results = self.client.ft(self.index_name).search(redis_query, params_dict) # type: ignore # noqa: E501
except redis.exceptions.ResponseError as e:
# split error message and see if it starts with "Syntax"
if st... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-21 | k (int): Number of Documents to return. Defaults to 4.
fetch_k (int): Number of Documents to fetch to pass to MMR algorithm.
lambda_mult (float): Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diver... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-22 | np.array(query_embedding), prefetch_embeddings, lambda_mult=lambda_mult, k=k
)
selected_docs = [prefetch_docs[i] for i in selected_indices]
return selected_docs
def _collect_metadata(self, result: "Document") -> Dict[str, Any]:
"""Collect metadata from Redis.
Method ensures t... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-23 | }
# prepare return fields including score
return_fields = [self._schema.content_key]
if with_distance:
return_fields.append("distance")
if with_metadata:
return_fields.extend(self._schema.metadata_keys)
if distance_threshold:
params_dict["dista... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-24 | k: int,
filter: Optional[RedisFilterExpression] = None,
return_fields: Optional[List[str]] = None,
) -> "Query":
"""Prepare query for vector search.
Args:
k: Number of results to return.
filter: Optional metadata filter.
Returns:
query: Que... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-25 | # pass to the Pydantic validators
if index_schema:
schema_values = read_schema(index_schema) # type: ignore
schema = RedisModel(**schema_values)
# ensure user did not exclude the content field
# no modifications if content field found
schema.add_conte... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-26 | )
# Set vector dimension
# can't obtain beforehand because we don't
# know which embedding model is being used.
self._schema.content_vector.dims = dim
# Check if index exists
if not check_index_exists(self.client, self.index_name):
# Create Redis Index
... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-27 | def _select_relevance_score_fn(self) -> Callable[[float], float]:
if self.relevance_score_fn:
return self.relevance_score_fn
metric_map = {
"COSINE": self._cosine_relevance_score_fn,
"IP": self._max_inner_product_relevance_score_fn,
"L2": self._euclidean_r... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
dc70e738e6bd-28 | int(value)
result["numeric"].append({"name": key})
continue
except (ValueError, TypeError):
pass
# None values are not indexed as of now
if value is None:
continue
# if it's a list of strings, we assume it's a tag
if isinstance(valu... | lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.