id stringlengths 14 16 | text stringlengths 29 2.73k | source stringlengths 49 115 |
|---|---|---|
5350863b55b6-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 |
5350863b55b6-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 |
5350863b55b6-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 |
20018c947ef0-0 | Source code for langchain.vectorstores.deeplake
"""Wrapper around Activeloop Deep Lake."""
from __future__ import annotations
import logging
import uuid
from functools import partial
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
import numpy as np
from langchain.docstore.document imp... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-1 | returns:
nearest_indices: List, indices of nearest neighbors
"""
if data_vectors.shape[0] == 0:
return [], []
# Calculate the distance between the query_vector and all data_vectors
distances = distance_metric_map[distance_metric](query_embedding, data_vectors)
nearest_indices = np.ar... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-2 | embeddings = OpenAIEmbeddings()
vectorstore = DeepLake("langchain_store", embeddings.embed_query)
"""
_LANGCHAIN_DEFAULT_DEEPLAKE_PATH = "./deeplake/"
def __init__(
self,
dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH,
token: Optional[str] = None,
embedd... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-3 | del kwargs["overwrite"]
self.ds = deeplake.empty(
dataset_path, token=token, overwrite=True, **kwargs
)
with self.ds:
self.ds.create_tensor(
"text",
htype="text",
create_id_tensor=False,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-4 | ids (Optional[List[str]], optional): Optional list of IDs.
Returns:
List[str]: List of IDs of the added texts.
"""
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
text_list = list(texts)
if metadatas is None:
metadatas = [{}] * len(tex... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-5 | **kwargs,
)
self.ds.commit(allow_empty=True)
self.ds.summary()
return ids
def _search_helper(
self,
query: Any[str, None] = None,
embedding: Any[float, None] = None,
k: int = 4,
distance_metric: str = "L2",
use_maximal_marginal_relevanc... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-6 | return_score: Whether to return the score. Defaults to False.
Returns:
List of Documents selected by the specified distance metric,
if return_score True, return a tuple of (Document, score)
"""
view = self.ds
# attribute based filtering
if filter is not No... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-7 | view = view[indices]
scores = [scores[i] for i in indices]
docs = [
Document(
page_content=el["text"].data()["value"],
metadata=el["metadata"].data()["value"],
)
for el in view
]
if return_score:
retu... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-8 | [docs] def similarity_search_by_vector(
self, embedding: List[float], k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defau... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-9 | [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.
Maximal marg... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-10 | 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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-11 | To write to Deep Lake cloud datasets,
ensure that you are logged in to Deep Lake
(use 'activeloop login' from command line)
- AWS S3 path of the form ``s3://bucketname/path/to/dataset``.
Credentials are required in either the environment
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-12 | ) -> bool:
"""Delete the entities in the dataset
Args:
ids (Optional[List[str]], optional): The document_ids to delete.
Defaults to None.
filter (Optional[Dict[str, str]], optional): The filter to delete by.
Defaults to None.
delete_all... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
20018c947ef0-13 | """Persist the collection."""
self.ds.flush()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
6fc12dee1ee5-0 | Source code for langchain.vectorstores.weaviate
"""Wrapper around weaviate vector database."""
from __future__ import annotations
import datetime
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type
from uuid import uuid4
import numpy as np
from langchain.docstore.document import Document
from ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6fc12dee1ee5-1 | if weaviate_api_key is not None
else None
)
client = weaviate.Client(weaviate_url, auth_client_secret=auth)
return client
def _default_score_normalizer(val: float) -> float:
return 1 - 1 / (1 + np.exp(val))
[docs]class Weaviate(VectorStore):
"""Wrapper around Weaviate vector database.
To... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6fc12dee1ee5-2 | self._embedding = embedding
self._text_key = text_key
self._query_attrs = [self._text_key]
self._relevance_score_fn = relevance_score_fn
if attributes is not None:
self._query_attrs.extend(attributes)
[docs] def add_texts(
self,
texts: Iterable[str],
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6fc12dee1ee5-3 | self, query: str, k: int = 4, **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.
Returns:
List of Documents most similar to the query.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6fc12dee1ee5-4 | if "errors" in result:
raise ValueError(f"Error during query: {result['errors']}")
docs = []
for res in result["data"]["Get"][self._index_name]:
text = res.pop(self._text_key)
docs.append(Document(page_content=text, metadata=res))
return docs
[docs] def max... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6fc12dee1ee5-5 | [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.
Maximal marg... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6fc12dee1ee5-6 | text = payload[idx].pop(self._text_key)
payload[idx].pop("_additional")
meta = payload[idx]
docs.append(Document(page_content=text, metadata=meta))
return docs
[docs] def similarity_search_with_score(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6fc12dee1ee5-7 | """Return docs and relevance scores, normalized on a scale from 0 to 1.
0 is dissimilar, 1 is most similar.
"""
if self._relevance_score_fn is None:
raise ValueError(
"relevance_score_fn must be provided to"
" Weaviate constructor to normalize scores"
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6fc12dee1ee5-8 | from weaviate.util import get_valid_uuid
index_name = kwargs.get("index_name", f"LangChain_{uuid4().hex}")
embeddings = embedding.embed_documents(texts) if embedding else None
text_key = "text"
schema = _default_schema(index_name)
attributes = list(metadatas[0].keys()) if metadat... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
c6bca7a17d1a-0 | 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,
Mapping,
Optional,
Tuple,
Type,
)
import num... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c6bca7a17d1a-1 | "Please refer to Redis Stack docs: https://redis.io/docs/stack/"
)
logging.error(error_message)
raise ValueError(error_message)
def _check_index_exists(client: RedisType, index_name: str) -> bool:
"""Check if Redis index exists."""
try:
client.ft(index_name).info()
except: # noqa: E722
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c6bca7a17d1a-2 | 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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c6bca7a17d1a-3 | schema = (
TextField(name=self.content_key),
TextField(name=self.metadata_key),
VectorField(
self.vector_key,
"FLAT",
{
"TYPE": "FLOAT32",
"DIM": dim,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c6bca7a17d1a-4 | # Write data to redis
pipeline = self.client.pipeline(transaction=False)
for i, text in enumerate(texts):
# Use provided values by default or fallback
key = keys[i] if keys else _redis_key(prefix)
metadata = metadatas[i] if metadatas else {}
embedding = em... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c6bca7a17d1a-5 | Returns the most similar indexed documents to the query text within the
score_threshold range.
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 matchin... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c6bca7a17d1a-6 | )
[docs] def similarity_search_with_score(
self, query: str, k: int = 4
) -> 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:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c6bca7a17d1a-7 | " Weaviate constructor to normalize scores"
)
docs_and_scores = self.similarity_search_with_score(query, k=k)
return [(doc, self.relevance_score_fn(score)) for doc, score in docs_and_scores]
[docs] @classmethod
def from_texts(
cls: Type[Redis],
texts: List[str],
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c6bca7a17d1a-8 | # Create instance
instance = cls(
redis_url=redis_url,
index_name=index_name,
embedding_function=embedding.embed_query,
content_key=content_key,
metadata_key=metadata_key,
vector_key=vector_key,
**kwargs,
)
# Cre... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c6bca7a17d1a-9 | # Check if index exists
try:
client.ft(index_name).dropindex(delete_documents)
logger.info("Drop index")
return True
except: # noqa: E722
# Index not exist
return False
[docs] @classmethod
def from_existing_index(
cls,
e... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c6bca7a17d1a-10 | metadata_key=metadata_key,
vector_key=vector_key,
**kwargs,
)
[docs] def as_retriever(self, **kwargs: Any) -> BaseRetriever:
return RedisVectorStoreRetriever(vectorstore=self, **kwargs)
class RedisVectorStoreRetriever(BaseRetriever, BaseModel):
vectorstore: Redis
searc... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c6bca7a17d1a-11 | """Add documents to vectorstore."""
return self.vectorstore.add_documents(documents, **kwargs)
async def aadd_documents(
self, documents: List[Document], **kwargs: Any
) -> List[str]:
"""Add documents to vectorstore."""
return await self.vectorstore.aadd_documents(documents, **kw... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
12d0558128eb-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 |
12d0558128eb-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 |
12d0558128eb-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 |
12d0558128eb-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 |
12d0558128eb-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 |
12d0558128eb-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 |
12d0558128eb-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 |
12d0558128eb-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 |
12d0558128eb-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
ed72b1f3b380-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 |
757e7fb626e5-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 |
757e7fb626e5-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 |
757e7fb626e5-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,
**kwargs: Any,
) -> List[Document]:
"""Query the chroma collection."""
try:
import chro... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
757e7fb626e5-3 | ids (Optional[List[str]], optional): Optional list of IDs.
Returns:
List[str]: List of IDs of the added texts.
"""
# TODO: Handle the case where the user doesn't provide ids on the Collection
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
embeddi... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
757e7fb626e5-4 | """Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most similar to the query vector.
"""
results = self.__query_collec... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
757e7fb626e5-5 | 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 relevance.
Maximal marginal relevance optimizes for similarity to query AND diversi... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
757e7fb626e5-6 | 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 relevance.
Maximal marginal relevance optimizes f... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
757e7fb626e5-7 | return self._collection.get()
[docs] def persist(self) -> None:
"""Persist the collection.
This can be used to explicitly persist the data to disk.
It will also be called automatically when the object is destroyed.
"""
if self._persist_directory is None:
raise Valu... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
757e7fb626e5-8 | Args:
texts (List[str]): List of texts to add to the collection.
collection_name (str): Name of the collection to create.
persist_directory (Optional[str]): Directory to persist the collection.
embedding (Optional[Embeddings]): Embedding function. Defaults to None.
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
757e7fb626e5-9 | Otherwise, the data will be ephemeral in-memory.
Args:
collection_name (str): Name of the collection to create.
persist_directory (Optional[str]): Directory to persist the collection.
ids (Optional[List[str]]): List of document IDs. Defaults to None.
documents (Li... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
fe18fa7ddfcd-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
fe18fa7ddfcd-1 | ):
"""Initialize with necessary components."""
self.embedding_function = embedding_function
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... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
fe18fa7ddfcd-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 |
fe18fa7ddfcd-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 |
fe18fa7ddfcd-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 |
fe18fa7ddfcd-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 |
fe18fa7ddfcd-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 |
fe18fa7ddfcd-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 |
fe18fa7ddfcd-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 |
fe18fa7ddfcd-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 |
fe18fa7ddfcd-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 |
2be67f146ca8-0 | Source code for langchain.output_parsers.rail_parser
from __future__ import annotations
from typing import Any, Dict
from langchain.schema import BaseOutputParser
[docs]class GuardrailsOutputParser(BaseOutputParser):
guard: Any
@property
def _type(self) -> str:
return "guardrails"
[docs] @classme... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html |
701ab2e0b405-0 | Source code for langchain.output_parsers.regex_dict
from __future__ import annotations
import re
from typing import Dict, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexDictParser(BaseOutputParser):
"""Class to parse the output into a dictionary."""
regex_pattern: str = r"{}:\s?([^.'\n'... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html |
7d304f3e794e-0 | Source code for langchain.output_parsers.retry
from __future__ import annotations
from typing import TypeVar
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.prompts.base import BasePromptTemplate
from langchain.prompts.prompt import PromptTemplate
from lang... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
7d304f3e794e-1 | chain = LLMChain(llm=llm, prompt=prompt)
return cls(parser=parser, retry_chain=chain)
[docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:
try:
parsed_completion = self.parser.parse(completion)
except OutputParserException:
new_completio... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
7d304f3e794e-2 | ) -> RetryWithErrorOutputParser[T]:
chain = LLMChain(llm=llm, prompt=prompt)
return cls(parser=parser, retry_chain=chain)
[docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:
try:
parsed_completion = self.parser.parse(completion)
except Outp... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
def4274dcb71-0 | Source code for langchain.output_parsers.pydantic
import json
import re
from typing import Type, TypeVar
from pydantic import BaseModel, ValidationError
from langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS
from langchain.schema import BaseOutputParser, OutputParserException
T = TypeVar(... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
def4274dcb71-1 | @property
def _type(self) -> str:
return "pydantic"
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
cb8d5ae9c3a3-0 | Source code for langchain.output_parsers.regex
from __future__ import annotations
import re
from typing import Dict, List, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexParser(BaseOutputParser):
"""Class to parse the output into a dictionary."""
regex: str
output_keys: List[str]
... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex.html |
cc0a593df8d9-0 | Source code for langchain.output_parsers.fix
from __future__ import annotations
from typing import TypeVar
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.output_parsers.prompts import NAIVE_FIX_PROMPT
from langchain.prompts.base import BasePromptTemplate
f... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html |
3c97d2af41c9-0 | Source code for langchain.output_parsers.structured
from __future__ import annotations
import json
from typing import Any, List
from pydantic import BaseModel
from langchain.output_parsers.format_instructions import STRUCTURED_FORMAT_INSTRUCTIONS
from langchain.schema import BaseOutputParser, OutputParserException
line... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html |
3c97d2af41c9-1 | ) -> StructuredOutputParser:
return cls(response_schemas=response_schemas)
[docs] def get_format_instructions(self) -> str:
schema_str = "\n".join(
[_get_sub_string(schema) for schema in self.response_schemas]
)
return STRUCTURED_FORMAT_INSTRUCTIONS.format(format=schema_st... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html |
007d1473e2e3-0 | Source code for langchain.output_parsers.list
from __future__ import annotations
from abc import abstractmethod
from typing import List
from langchain.schema import BaseOutputParser
[docs]class ListOutputParser(BaseOutputParser):
"""Class to parse the output of an LLM call to a list."""
@property
def _type(... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html |
ecc8fb3e3b65-0 | Source code for langchain.utilities.bing_search
"""Util that calls Bing Search.
In order to set this up, follow instructions at:
https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e
"""
from typing import Dict, List
import requests
from pydantic import BaseModel, Extra, ro... | https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.