id stringlengths 14 16 | text stringlengths 44 2.73k | source stringlengths 49 115 |
|---|---|---|
f02cae0015b6-2 | 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 ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
f02cae0015b6-3 | 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 for each
"""
embedding = self.embedding_function(query)
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
f02cae0015b6-4 | 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_search(
self, query: str, k: int =... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
f02cae0015b6-5 | 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.
"""
idxs = self.index.get_nns_by_vector(
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
f02cae0015b6-6 | 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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
f02cae0015b6-7 | 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))}
docstore = InMemoryDocstore(
{inde... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
f02cae0015b6-8 | from langchain import Annoy
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
index = Annoy.from_texts(texts, embeddings)
"""
embeddings = embedding.embed_documents(texts)
return cls.__from(
texts, embedd... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
f02cae0015b6-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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
f02cae0015b6-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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
865a2cd8c4b1-0 | Source code for langchain.vectorstores.analyticdb
"""VectorStore wrapper around a Postgres/PGVector database."""
from __future__ import annotations
import logging
import uuid
from typing import Any, Dict, Iterable, List, Optional, Tuple
import sqlalchemy
from sqlalchemy import REAL, Index
from sqlalchemy.dialects.postg... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
865a2cd8c4b1-1 | """
created = False
collection = cls.get_by_name(session, name)
if collection:
return collection, created
collection = cls(name=name, cmetadata=cmetadata)
session.add(collection)
session.commit()
created = True
return collection, created
class ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
865a2cd8c4b1-2 | - `connection_string` is a postgres connection string.
- `embedding_function` any embedding function implementing
`langchain.embeddings.base.Embeddings` interface.
- `collection_name` is the name of the collection to use. (default: langchain)
- NOTE: This is not the name of the table, but the na... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
865a2cd8c4b1-3 | return conn
[docs] def create_tables_if_not_exists(self) -> None:
Base.metadata.create_all(self._conn)
[docs] def drop_tables(self) -> None:
Base.metadata.drop_all(self._conn)
[docs] def create_collection(self) -> None:
if self.pre_delete_collection:
self.delete_collection()... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
865a2cd8c4b1-4 | embeddings = self.embedding_function.embed_documents(list(texts))
if not metadatas:
metadatas = [{} for _ in texts]
with Session(self._conn) as session:
collection = self.get_collection(session)
if not collection:
raise ValueError("Collection not found... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
865a2cd8c4b1-5 | """Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List of Documents most similar to th... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
865a2cd8c4b1-6 | EmbeddingStore.collection_id == CollectionStore.uuid,
)
.limit(k)
.all()
)
docs = [
(
Document(
page_content=result.EmbeddingStore.document,
metadata=result.EmbeddingStore.cmetadata,
)... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
865a2cd8c4b1-7 | Return VectorStore initialized from texts and embeddings.
Postgres connection string is required
Either pass it as a parameter
or set the PGVECTOR_CONNECTION_STRING environment variable.
"""
connection_string = cls.get_connection_string(kwargs)
store = cls(
co... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
865a2cd8c4b1-8 | metadatas = [d.metadata for d in documents]
connection_string = cls.get_connection_string(kwargs)
kwargs["connection_string"] = connection_string
return cls.from_texts(
texts=texts,
pre_delete_collection=pre_delete_collection,
embedding=embedding,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
38b9bb1c8f13-0 | Source code for langchain.vectorstores.pinecone
"""Wrapper around Pinecone vector database."""
from __future__ import annotations
import uuid
from typing import Any, Callable, Iterable, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
38b9bb1c8f13-1 | self._embedding_function = embedding_function
self._text_key = text_key
self._namespace = namespace
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
namespace: Optional[str] = None,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
38b9bb1c8f13-2 | filter: Optional[dict] = None,
namespace: Optional[str] = None,
) -> List[Tuple[Document, float]]:
"""Return pinecone documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
38b9bb1c8f13-3 | namespace: Namespace to search in. Default will search in '' namespace.
Returns:
List of Documents most similar to the query and score for each
"""
if namespace is None:
namespace = self._namespace
query_obj = self._embedding_function(query)
docs = []
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
38b9bb1c8f13-4 | pinecone.init(api_key="***", environment="...")
embeddings = OpenAIEmbeddings()
pinecone = Pinecone.from_texts(
texts,
embeddings,
index_name="langchain-demo"
)
"""
try:
import pinecon... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
38b9bb1c8f13-5 | metadata = metadatas[i:i_end]
else:
metadata = [{} for _ in range(i, i_end)]
for j, line in enumerate(lines_batch):
metadata[j][text_key] = line
to_upsert = zip(ids_batch, embeds, metadata)
# upsert to Pinecone
index.upsert(vect... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
05b2022dd617-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-1 | 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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-2 | Args:
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 ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-3 | "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"... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-4 | if drop_old and isinstance(self.col, Collection):
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 impor... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-5 | and ("user" in addr)
and (addr["user"] == tmp_user)
):
logger.debug("Using previous connection: %s", con[0])
return con[0]
# Generate a new connection if one doesnt exist
alias = uuid4().hex
try:
connections.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-6 | # Datatype isnt compatible
if dtype == DataType.UNKNOWN or dtype == DataType.NONE:
logger.error(
"Failure to create collection, unrecognized dtype for key: %s",
key,
)
raise ValueError(f"Unrecogni... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-7 | schema = self.col.schema
for x in schema.fields:
self.fields.append(x.name)
# Since primary field is auto-id, no need to track it
self.fields.remove(self._primary_field)
def _get_index(self) -> Optional[dict[str, Any]]:
"""Return the vector index informati... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-8 | using=self.alias,
)
logger.debug(
"Successfully created an index on collection: %s",
self.collection_name,
)
except MilvusException as e:
logger.error(
"Failed to create an index o... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-9 | embedding and the columns are decided by the first metadata dict.
Metada keys will need to be present for all inserted values. At
the moment there is no None equivalent in Milvus.
Args:
texts (Iterable[str]): The texts to embed, it is assumed
that they all fit in memo... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-10 | for key, value in d.items():
if key in self.fields:
insert_dict.setdefault(key, []).append(value)
# Total insert count
vectors: list = insert_dict[self._vector_field]
total_count = len(vectors)
pks: list[str] = []
assert isinstance(self... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-11 | Defaults to None.
expr (str, optional): Filtering expression. Defaults to None.
timeout (int, optional): How long to wait before timeout error.
Defaults to None.
kwargs: Collection.search() keyword arguments.
Returns:
List[Document]: Document resul... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-12 | return []
res = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs
)
return [doc for doc, _ in res]
[docs] def similarity_search_with_score(
self,
query: str,
k: int = 4,
param: O... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-13 | output_fields = self.fields[:]
output_fields.remove(self._vector_field)
res = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs
)
return res
[docs] def similarity_search_with_score_by_vector(
se... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-14 | # Determine result metadata fields.
output_fields = self.fields[:]
output_fields.remove(self._vector_field)
# Perform the search.
res = self.col.search(
data=[embedding],
anns_field=self._vector_field,
param=param,
limit=k,
expr... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-15 | to maximum diversity and 1 to minimum diversity.
Defaults to 0.5
param (dict, optional): The search params for the specified index.
Defaults to None.
expr (str, optional): Filtering expression. Defaults to None.
timeout (int, optional): How lon... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-16 | 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
param (dict, optional): The search params for the specif... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-17 | output_fields=[self._primary_field, self._vector_field],
timeout=timeout,
)
# Reorganize the results from query to match search order.
vectors = {x[self._primary_field]: x[self._vector_field] for x in vectors}
ordered_result_embeddings = [vectors[x] for x in ids]
# Ge... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
05b2022dd617-18 | Defaults to None.
collection_name (str, optional): Collection name to use. Defaults to
"LangChainCollection".
connection_args (dict[str, Any], optional): Connection args to use. Defaults
to DEFAULT_MILVUS_CONNECTION.
consistency_level (str, optional): ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
3c6c6ee95f14-0 | Source code for langchain.vectorstores.base
"""Interface for vector stores."""
from __future__ import annotations
import asyncio
from abc import ABC, abstractmethod
from functools import partial
from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, TypeVar
from pydantic import BaseModel, Field, root_vali... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
3c6c6ee95f14-1 | documents (List[Document]: Documents to add to the vectorstore.
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.metada... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
3c6c6ee95f14-2 | ) -> List[Document]:
"""Return docs most similar to query using specified search type."""
if search_type == "similarity":
return await self.asimilarity_search(query, **kwargs)
elif search_type == "mmr":
return await self.amax_marginal_relevance_search(query, **kwargs)
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
3c6c6ee95f14-3 | k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs and relevance scores, normalized on a scale from 0 to 1.
0 is dissimilar, 1 is most similar.
"""
raise NotImplementedError
[docs] async def asimilarity_search(
self, query: str, k: int = 4... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
3c6c6ee95f14-4 | # asynchronous in the vector store implementations.
func = partial(self.similarity_search_by_vector, embedding, k, **kwargs)
return await asyncio.get_event_loop().run_in_executor(None, func)
[docs] def max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
3c6c6ee95f14-5 | # asynchronous in the vector store implementations.
func = partial(
self.max_marginal_relevance_search, query, k, fetch_k, lambda_mult, **kwargs
)
return await asyncio.get_event_loop().run_in_executor(None, func)
[docs] def max_marginal_relevance_search_by_vector(
self,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
3c6c6ee95f14-6 | [docs] @classmethod
def from_documents(
cls: Type[VST],
documents: List[Document],
embedding: Embeddings,
**kwargs: Any,
) -> VST:
"""Return VectorStore initialized from documents and embeddings."""
texts = [d.page_content for d in documents]
metadatas ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
3c6c6ee95f14-7 | """Return VectorStore initialized from texts and embeddings."""
raise NotImplementedError
[docs] def as_retriever(self, **kwargs: Any) -> BaseRetriever:
return VectorStoreRetriever(vectorstore=self, **kwargs)
class VectorStoreRetriever(BaseRetriever, BaseModel):
vectorstore: VectorStore
searc... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
3c6c6ee95f14-8 | docs = await self.vectorstore.amax_marginal_relevance_search(
query, **self.search_kwargs
)
else:
raise ValueError(f"search_type of {self.search_type} not allowed.")
return docs
def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
af349d9a9667-0 | 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(... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
af349d9a9667-1 | "Failed to create an index on collection: %s", self.collection_name
)
raise e
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
collection_name: str = "LangChainCollecti... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
af349d9a9667-2 | Zilliz: Zilliz Vector Store
"""
vector_db = cls(
embedding_function=embedding,
collection_name=collection_name,
connection_args=connection_args,
consistency_level=consistency_level,
index_params=index_params,
search_params=search_pa... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
4c7c440dcd3a-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
4c7c440dcd3a-1 | """
_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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
4c7c440dcd3a-2 | self,
query_texts: Optional[List[str]] = None,
query_embeddings: Optional[List[List[float]]] = None,
n_results: int = 4,
where: Optional[Dict[str, str]] = None,
) -> List[Document]:
"""Query the chroma collection."""
for i in range(n_results, 0, -1):
try:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
4c7c440dcd3a-3 | ids = [str(uuid.uuid1()) for _ in texts]
embeddings = None
if self._embedding_function is not None:
embeddings = self._embedding_function.embed_documents(list(texts))
self._collection.add(
metadatas=metadatas, embeddings=embeddings, documents=texts, ids=ids
)
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
4c7c440dcd3a-4 | """
results = self.__query_collection(
query_embeddings=embedding, n_results=k, where=filter
)
return _results_to_docs(results)
[docs] def similarity_search_with_score(
self,
query: str,
k: int = 4,
filter: Optional[Dict[str, str]] = None,
*... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
4c7c440dcd3a-5 | ) -> List[Document]:
"""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 Documen... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
4c7c440dcd3a-6 | **kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
query: Text to look up documents similar to.
k: Number ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
4c7c440dcd3a-7 | "creation to persist the collection."
)
self._client.persist()
[docs] def update_document(self, document_id: str, document: Document) -> None:
"""Update a document in the collection.
Args:
document_id (str): ID of the document to update.
document (Document)... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
4c7c440dcd3a-8 | ids (Optional[List[str]]): List of document IDs. Defaults to None.
client_settings (Optional[chromadb.config.Settings]): Chroma client settings
Returns:
Chroma: Chroma vectorstore.
"""
chroma_collection = cls(
collection_name=collection_name,
embed... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
4c7c440dcd3a-9 | client_settings (Optional[chromadb.config.Settings]): Chroma client settings
Returns:
Chroma: Chroma vectorstore.
"""
texts = [doc.page_content for doc in documents]
metadatas = [doc.metadata for doc in documents]
return cls.from_texts(
texts=texts,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
05179cf9418b-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
05179cf9418b-1 | embedding: Embeddings,
table_name: str,
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 pa... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
05179cf9418b-2 | if not table_name:
raise ValueError("Supabase document table_name is required.")
embeddings = embedding.embed_documents(texts)
docs = cls._texts_to_documents(texts, metadatas)
_ids = cls._add_vectors(client, table_name, embeddings, docs)
return cls(
client=client,... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
05179cf9418b-3 | self, query: List[float], k: int
) -> List[Tuple[Document, float]]:
match_documents_params = dict(query_embedding=query, match_count=k)
res = self._client.rpc(self.query_name, match_documents_params).execute()
match_result = [
(
Document(
metad... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
05179cf9418b-4 | metadatas: Optional[Iterable[dict[Any, Any]]] = None,
) -> List[Document]:
"""Return list of Documents from list of texts and metadatas."""
if metadatas is None:
metadatas = repeat({})
docs = [
Document(page_content=text, metadata=metadata)
for text, metad... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
05179cf9418b-5 | return id_list
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
05179cf9418b-6 | k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
05179cf9418b-7 | $$;```
"""
embedding = self._embedding.embed_documents([query])
docs = self.max_marginal_relevance_search_by_vector(
embedding[0], k, fetch_k, lambda_mult=lambda_mult
)
return docs
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
08a748b0434d-0 | Source code for langchain.vectorstores.weaviate
"""Wrapper around weaviate vector database."""
from __future__ import annotations
from typing import Any, Dict, Iterable, List, Optional, Type
from uuid import uuid4
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.base import ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
08a748b0434d-1 | if weaviate_api_key is not None
else None
)
client = weaviate.Client(weaviate_url, auth_client_secret=auth)
return client
[docs]class Weaviate(VectorStore):
"""Wrapper around Weaviate vector database.
To use, you should have the ``weaviate-client`` python package installed.
Example:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
08a748b0434d-2 | [docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""Upload texts with metadata (properties) to Weaviate."""
from weaviate.util import get_valid_uuid
with self._client.batch as batch:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
08a748b0434d-3 | if kwargs.get("search_distance"):
content["certainty"] = kwargs.get("search_distance")
query_obj = self._client.query.get(self._index_name, self._query_attrs)
if kwargs.get("where_filter"):
query_obj = query_obj.with_where(kwargs.get("where_filter"))
result = query_obj.wi... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
08a748b0434d-4 | k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
08a748b0434d-5 | 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 algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
08a748b0434d-6 | **kwargs: Any,
) -> Weaviate:
"""Construct Weaviate wrapper from raw documents.
This is a user-friendly interface that:
1. Embeds documents.
2. Creates a new index for the embeddings in the Weaviate instance.
3. Adds the documents to the newly created Weaviate ind... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
08a748b0434d-7 | # if an embedding strategy is not provided, we let
# weaviate create the embedding. Note that this will only
# work if weaviate has been installed with a vectorizer module
# like text2vec-contextionary for example
params = {
"uuid": _id... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
073c109cd4b6-0 | Source code for langchain.vectorstores.elastic_vector_search
"""Wrapper around Elasticsearch vector database."""
from __future__ import annotations
import uuid
from abc import ABC
from typing import Any, Dict, Iterable, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.embeddings.bas... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
073c109cd4b6-1 | # and attributes.
[docs]class ElasticVectorSearch(VectorStore, ABC):
"""Wrapper around Elasticsearch as a vector database.
To connect to an Elasticsearch instance that does not require
login credentials, pass the Elasticsearch URL and index name along with the
embedding object to the constructor.
Ex... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
073c109cd4b6-2 | Example:
.. code-block:: python
from langchain import ElasticVectorSearch
from langchain.embeddings import OpenAIEmbeddings
embedding = OpenAIEmbeddings()
elastic_host = "cluster_id.region_id.gcp.cloud.es.io"
elasticsearch_url = f"https://username:pass... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
073c109cd4b6-3 | [docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
refresh_indices: bool = True,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
073c109cd4b6-4 | "metadata": metadata,
"_id": _id,
}
ids.append(_id)
requests.append(request)
bulk(self.client, requests)
if refresh_indices:
self.client.indices.refresh(index=self.index_name)
return ids
[docs] def similarity_search(
self... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
073c109cd4b6-5 | (
Document(
page_content=hit["_source"]["text"],
metadata=hit["_source"]["metadata"],
),
hit["_score"],
)
for hit in hits
]
return docs_and_scores
[docs] @classmethod
def from_texts(
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
073c109cd4b6-6 | except ValueError as e:
raise ValueError(
"Your elasticsearch client string is misformatted. " f"Got error: {e} "
)
index_name = kwargs.get("index_name", uuid.uuid4().hex)
embeddings = embedding.embed_documents(texts)
dim = len(embeddings[0])
mappi... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
7fd62b69fda9-0 | Source code for langchain.vectorstores.myscale
"""Wrapper around MyScale vector database."""
from __future__ import annotations
import json
import logging
from hashlib import sha1
from threading import Thread
from typing import Any, Dict, Iterable, List, Optional, Tuple
from pydantic import BaseSettings
from langchain.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
7fd62b69fda9-1 | .. code-block:: python
{
'id': 'text_id',
'vector': 'text_embedding',
'text': 'text_plain',
'metadata': 'metadata_dictionary_in_json',
}... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
7fd62b69fda9-2 | config: Optional[MyScaleSettings] = None,
**kwargs: Any,
) -> None:
"""MyScale Wrapper to LangChain
embedding_function (Embeddings):
config (MyScaleSettings): Configuration to MyScale Client
Other keyword arguments will pass into
[clickhouse-connect](https://docs.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
7fd62b69fda9-3 | CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}(
{self.config.column_map['id']} String,
{self.config.column_map['text']} String,
{self.config.column_map['vector']} Array(Float32),
{self.config.column_map['metadata']} JSON,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
7fd62b69fda9-4 | _data.append(f"({n})")
i_str = f"""
INSERT INTO TABLE
{self.config.database}.{self.config.table}({ks})
VALUES
{','.join(_data)}
"""
return i_str
def _insert(self, transac: Iterable, column_names: Iterable[str]) -> N... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
7fd62b69fda9-5 | column_names[colmap_["metadata"]] = map(json.dumps, metadatas)
assert len(set(colmap_) - set(column_names)) >= 0
keys, values = zip(*column_names.items())
try:
t = None
for v in self.pgbar(
zip(*values), desc="Inserting data...", total=len(metadatas)
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
7fd62b69fda9-6 | texts (Iterable[str]): List or tuple of strings to be added
config (MyScaleSettings, Optional): Myscale configuration
text_ids (Optional[Iterable], optional): IDs for the texts.
Defaults to None.
batch_size (int, optional): Batchsi... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
7fd62b69fda9-7 | ).named_results():
_repr += (
f"|\033[94m{r['name']:24s}\033[0m|\033[96m{r['type']:24s}\033[0m|\n"
)
_repr += "-" * 51 + "\n"
return _repr
def _build_qstr(
self, q_emb: List[float], topk: int, where_str: Optional[str] = None
) -> str:
q_emb... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
7fd62b69fda9-8 | of SQL injection. When dealing with metadatas, remember to
use `{self.metadata_column}.attribute` instead of `attribute`
alone. The default name for it is `metadata`.
Returns:
List[Document]: List of Documents
"""
return self.similarity_search_by_v... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
7fd62b69fda9-9 | ]
except Exception as e:
logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m")
return []
[docs] def similarity_search_with_relevance_scores(
self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any
) -> List[Tuple[Document, float]]:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
7fd62b69fda9-10 | return []
[docs] def drop(self) -> None:
"""
Helper function: Drop data
"""
self.client.command(
f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}"
)
@property
def metadata_column(self) -> str:
return self.config.column_map["metadata... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
f60d51e2772a-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.