id stringlengths 14 16 | text stringlengths 45 2.73k | source stringlengths 49 114 |
|---|---|---|
4fd0f44fb656-2 | starting_len = len(self.index_to_docstore_id)
self.index.add(np.array(embeddings, dtype=np.float32))
# Get list of index, id, and docs.
full_info = [
(starting_len + i, str(uuid.uuid4()), doc)
for i, doc in enumerate(documents)
]
# Add information to docst... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
4fd0f44fb656-3 | self,
text_embeddings: Iterable[Tuple[str, List[float]]],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
text_embeddings: Iterable pairs of string and embedding to
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
4fd0f44fb656-4 | # This happens when not enough docs are returned.
continue
_id = self.index_to_docstore_id[i]
doc = self.docstore.search(_id)
if not isinstance(doc, Document):
raise ValueError(f"Could not find document for id {_id}, got {doc}")
docs.append... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
4fd0f44fb656-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.
Returns:
List of Documents most similar to the query.
"""
docs_and_scores = self.similarity_search_with_score(quer... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
4fd0f44fb656-6 | continue
_id = self.index_to_docstore_id[i]
doc = self.docstore.search(_id)
if not isinstance(doc, Document):
raise ValueError(f"Could not find document for id {_id}, got {doc}")
docs.append(doc)
return docs
[docs] def max_marginal_relevance_sea... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
4fd0f44fb656-7 | # Merge two IndexFlatL2
self.index.merge_from(target.index)
# Create new id for docs from target FAISS object
full_info = []
for i in target.index_to_docstore_id:
doc = target.docstore.search(target.index_to_docstore_id[i])
if not isinstance(doc, Document):
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
4fd0f44fb656-8 | return cls(embedding.embed_query, index, docstore, index_to_id, **kwargs)
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> FAISS:
"""Construct FAISS wrapper from raw do... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
4fd0f44fb656-9 | Example:
.. code-block:: python
from langchain import FAISS
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text_embeddings = embeddings.embed_documents(texts)
text_embedding_pairs = list(zip(te... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
4fd0f44fb656-10 | ) -> FAISS:
"""Load FAISS index, docstore, and index_to_docstore_id to disk.
Args:
folder_path: folder path to load index, docstore,
and index_to_docstore_id from.
embeddings: Embeddings to use when generating queries
index_name: for saving with a spec... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
20a19d69966c-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 |
20a19d69966c-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 |
20a19d69966c-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 |
20a19d69966c-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 |
20a19d69966c-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 |
20a19d69966c-5 | return id_list
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance opti... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
20a19d69966c-6 | k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Returns:
List of Documents selected by maximal marginal relevance.
`max_marginal_relevance_search` requires that `query_name` returns matched
embeddings alongs... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
a61c6d63d66a-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
from langchain.docstore.document import Document
from langchain.embeddings.base impor... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
a61c6d63d66a-1 | embedding object to the constructor.
Example:
.. code-block:: python
from langchain import ElasticVectorSearch
from langchain.embeddings import OpenAIEmbeddings
embedding = OpenAIEmbeddings()
elastic_vector_search = ElasticVectorSearch(
elastic... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
a61c6d63d66a-2 | elastic_host = "cluster_id.region_id.gcp.cloud.es.io"
elasticsearch_url = f"https://username:password@{elastic_host}:9243"
elastic_vector_search = ElasticVectorSearch(
elasticsearch_url=elasticsearch_url,
index_name="test_index",
embedding=embeddin... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
a61c6d63d66a-3 | **kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
refresh_indices: bool to refresh Elasti... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
a61c6d63d66a-4 | if refresh_indices:
self.client.indices.refresh(index=self.index_name)
return ids
[docs] def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query.
Args:
query: Text to look up documents sim... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
a61c6d63d66a-5 | embeddings = OpenAIEmbeddings()
elastic_vector_search = ElasticVectorSearch.from_texts(
texts,
embeddings,
elasticsearch_url="http://localhost:9200"
)
"""
elasticsearch_url = get_from_dict_or_env(
kwa... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
a61c6d63d66a-6 | "metadata": metadata,
}
requests.append(request)
bulk(client, requests)
client.indices.refresh(index=index_name)
return cls(elasticsearch_url, index_name, embedding)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
533db4463a70-0 | Source code for langchain.vectorstores.atlas
"""Wrapper around Atlas by Nomic."""
from __future__ import annotations
import logging
import uuid
from typing import Any, Iterable, List, Optional, Type
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
533db4463a70-1 | is_public (bool): Whether your project is publicly accessible.
True by default.
reset_project_if_exists (bool): Whether to reset this project if it
already exists. Default False.
Generally userful during development and testing.
"""
try:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
533db4463a70-2 | metadatas (Optional[List[dict]], optional): Optional list of metadatas.
ids (Optional[List[str]]): An optional list of ids.
refresh(bool): Whether or not to refresh indices with the updated data.
Default True.
Returns:
List[str]: List of IDs of the added texts... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
533db4463a70-3 | else:
if metadatas is None:
data = [
{"text": text, AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i]}
for i, text in enumerate(texts)
]
else:
for i, text in enumerate(texts):
metadatas[i]["text"] =... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
533db4463a70-4 | """
if self._embedding_function is None:
raise NotImplementedError(
"AtlasDB requires an embedding_function for text similarity search!"
)
_embedding = self._embedding_function.embed_documents([query])[0]
embedding = np.array(_embedding).reshape(1, -1)
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
533db4463a70-5 | ids (Optional[List[str]]): Optional list of document IDs. If None,
ids will be auto created
description (str): A description for your project.
is_public (bool): Whether your project is publicly accessible.
True by default.
reset_project_if_exists (bool... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
533db4463a70-6 | ids: Optional[List[str]] = None,
name: Optional[str] = None,
api_key: Optional[str] = None,
persist_directory: Optional[str] = None,
description: str = "A description for your project",
is_public: bool = True,
reset_project_if_exists: bool = False,
index_kwargs: O... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
533db4463a70-7 | return cls.from_texts(
name=name,
api_key=api_key,
texts=texts,
embedding=embedding,
metadatas=metadatas,
ids=ids,
description=description,
is_public=is_public,
reset_project_if_exists=reset_project_if_exists,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
f78d5c799ac6-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 |
f78d5c799ac6-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 |
f78d5c799ac6-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 |
f78d5c799ac6-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 |
f78d5c799ac6-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 |
f78d5c799ac6-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 |
63ee562ef2a9-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 |
63ee562ef2a9-1 | returns:
nearest_indices: List, indices of nearest neighbors
"""
# Calculate the distance between the query_vector and all data_vectors
distances = distance_metric_map[distance_metric](query_embedding, data_vectors)
nearest_indices = np.argsort(distances)
nearest_indices = (
nearest_... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
63ee562ef2a9-2 | vectorstore = DeepLake("langchain_store", embeddings.embed_query)
"""
_LANGCHAIN_DEFAULT_DEEPLAKE_PATH = "mem://langchain"
def __init__(
self,
dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH,
token: Optional[str] = None,
embedding_function: Optional[Embeddings] = None,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
63ee562ef2a9-3 | create_sample_info_tensor=False,
create_shape_tensor=False,
chunk_compression="lz4",
)
self.ds.create_tensor(
"metadata",
htype="json",
create_id_tensor=False,
create_s... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
63ee562ef2a9-4 | text_list = list(texts)
if metadatas is None:
metadatas = [{}] * len(text_list)
elements = list(zip(text_list, metadatas, ids))
@self._deeplake.compute
def ingest(sample_in: list, sample_out: list) -> None:
text_list = [s[0] for s in sample_in]
embeds:... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
63ee562ef2a9-5 | k: int = 4,
distance_metric: str = "L2",
use_maximal_marginal_relevance: Optional[bool] = False,
fetch_k: Optional[int] = 20,
filter: Optional[Any[Dict[str, str], Callable, str]] = None,
return_score: Optional[bool] = False,
**kwargs: Any,
) -> Any[List[Document], Lis... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
63ee562ef2a9-6 | if filter is not None:
if isinstance(filter, dict):
filter = partial(dp_filter, filter=filter)
view = view.filter(filter)
if len(view) == 0:
return []
if self._embedding_function is None:
view = view.filter(lambda x: query in x["tex... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
63ee562ef2a9-7 | return docs
[docs] def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query.
Args:
query: text to embed and run the query on.
k: Number of Documents to return.
Defaults to 4.
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
63ee562ef2a9-8 | Returns:
List of Documents most similar to the query vector.
"""
return self.search(embedding=embedding, k=k, **kwargs)
[docs] def similarity_search_with_score(
self,
query: str,
distance_metric: str = "L2",
k: int = 4,
filter: Optional[Dict[str, st... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
63ee562ef2a9-9 | 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.
Returns:
List of Documents selected by maximal marginal relevance.
"""
retu... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
63ee562ef2a9-10 | dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH,
**kwargs: Any,
) -> DeepLake:
"""Create a Deep Lake dataset from a raw documents.
If a dataset_path is specified, the dataset will be persisted there.
Otherwise, the data will be ephemeral in-memory.
Args:
path... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
63ee562ef2a9-11 | DeepLake: Deep Lake dataset.
"""
deeplake_dataset = cls(
dataset_path=dataset_path, embedding_function=embedding, **kwargs
)
deeplake_dataset.add_texts(texts=texts, metadatas=metadatas, ids=ids)
return deeplake_dataset
[docs] def delete(
self,
ids: ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
63ee562ef2a9-12 | """Delete the collection."""
self.delete(delete_all=True)
[docs] def persist(self) -> None:
"""Persist the collection."""
self.ds.flush()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
690acc5045d2-0 | Source code for langchain.vectorstores.milvus
"""Wrapper around the Milvus vector database."""
from __future__ import annotations
import uuid
from typing import Any, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
690acc5045d2-1 | if not connections.has_connection("default"):
connections.connect(**connection_args)
self.embedding_func = embedding_function
self.collection_name = collection_name
self.text_field = text_field
self.auto_id = False
self.primary_field = None
self.vector_field =... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
690acc5045d2-2 | texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
partition_name: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[str]:
"""Insert text data into Milvus.
When using add_texts() it is assumed that a collecton has already
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
690acc5045d2-3 | # Insert into the collection.
res = self.col.insert(
insert_list, partition_name=partition_name, timeout=timeout
)
# Flush to make sure newly inserted is immediately searchable.
self.col.flush()
return res.primary_keys
def _worker_search(
self,
que... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
690acc5045d2-4 | ret.append(
(
Document(page_content=meta.pop(self.text_field), metadata=meta),
result.distance,
result.id,
)
)
return data[0], ret
[docs] def similarity_search_with_score(
self,
query: str,... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
690acc5045d2-5 | )
return [(x, y) for x, y, _ in result]
[docs] def max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
param: Optional[dict] = None,
expr: Optional[str] = None,
partition_names: Optional[List[str]] = None,
round_decim... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
690acc5045d2-6 | # Extract result IDs.
ids = [x for _, _, x in res]
# Get the raw vectors from Milvus.
vectors = self.col.query(
expr=f"{self.primary_field} in {ids}",
output_fields=[self.primary_field, self.vector_field],
)
# Reorganize the results from query to match res... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
690acc5045d2-7 | Defaults to None.
expr (str, optional): Filtering expression. Defaults to None.
partition_names (List[str], optional): What partitions to search.
Defaults to None.
round_decimal (int, optional): What decimal point to round to.
Defaults to -1.
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
690acc5045d2-8 | "Please install it with `pip install pymilvus`."
)
# Connect to Milvus instance
if not connections.has_connection("default"):
connections.connect(**kwargs.get("connection_args", {"port": 19530}))
# Determine embedding dim
embeddings = embedding.embed_query(texts[0... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
690acc5045d2-9 | )
else:
fields.append(FieldSchema(key, dtype))
# Find out max length of texts
max_length = 0
for y in texts:
max_length = max(max_length, len(y))
# Create the text field
fields.append(
FieldSchema(text_field, DataType.VA... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
56cd35ffec32-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 |
56cd35ffec32-1 | def __init__(
self,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
embedding_function: Optional[Embeddings] = None,
persist_directory: Optional[str] = None,
client_settings: Optional[chromadb.config.Settings] = None,
collection_metadata: Optional[Dict] = None,... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
56cd35ffec32-2 | **kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts (Iterable[str]): Texts to add to the vectorstore.
metadatas (Optional[List[dict]], optional): Optional list of metadatas.
ids (Optional[List[str]], opti... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
56cd35ffec32-3 | [docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
filter: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
56cd35ffec32-4 | query_embeddings=[query_embedding], n_results=k, where=filter
)
return _results_to_docs_and_scores(results)
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
filter: Optional[Dict[str, str]] = N... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
56cd35ffec32-5 | k: int = 4,
fetch_k: int = 20,
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 diversity
among selected document... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
56cd35ffec32-6 | def from_texts(
cls: Type[Chroma],
texts: List[str],
embedding: Optional[Embeddings] = None,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
persist_directory: Optional[str] = None... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
56cd35ffec32-7 | return chroma_collection
[docs] @classmethod
def from_documents(
cls: Type[Chroma],
documents: List[Document],
embedding: Optional[Embeddings] = None,
ids: Optional[List[str]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
persist_directory: Opt... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
56cd35ffec32-8 | client=client,
)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
82d1608a308b-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 |
82d1608a308b-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 |
82d1608a308b-2 | query, k=k, **kwargs
)
if any(
similarity < 0.0 or similarity > 1.0
for _, similarity in docs_and_similarities
):
raise ValueError(
"Relevance scores must be between"
f" 0 and 1, got {docs_and_similarities}"
)
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
82d1608a308b-3 | Returns:
List of Documents most similar to the query vector.
"""
raise NotImplementedError
[docs] async def asimilarity_search_by_vector(
self, embedding: List[float], k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to embedding vector."""
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
82d1608a308b-4 | # asynchronous in the vector store implementations.
func = partial(self.max_marginal_relevance_search, query, k, fetch_k, **kwargs)
return await asyncio.get_event_loop().run_in_executor(None, func)
[docs] def max_marginal_relevance_search_by_vector(
self, embedding: List[float], k: int = 4, f... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
82d1608a308b-5 | [docs] @classmethod
async def afrom_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]
met... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
82d1608a308b-6 | @root_validator()
def validate_search_type(cls, values: Dict) -> Dict:
"""Validate search type."""
if "search_type" in values:
search_type = values["search_type"]
if search_type not in ("similarity", "mmr"):
raise ValueError(f"search_type of {search_type} not ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
82d1608a308b-7 | ) -> List[str]:
"""Add documents to vectorstore."""
return await self.vectorstore.aadd_documents(documents, **kwargs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
335a62e7b5d8-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 |
335a62e7b5d8-1 | "Please install it with `pip install weaviate-client`."
)
if not isinstance(client, weaviate.Client):
raise ValueError(
f"client should be an instance of weaviate.Client, got {type(client)}"
)
self._client = client
self._index_name = index_name... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
335a62e7b5d8-2 | 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.
"""
content: Dict[str, Any] = {"concepts": [query]}
if kwargs.get("search_distance"):
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
335a62e7b5d8-3 | return docs
[docs] def max_marginal_relevance_search(
self, query: str, k: int = 4, fetch_k: int = 20, **kwargs: Any
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
335a62e7b5d8-4 | payload[idx].pop("_additional")
meta = payload[idx]
docs.append(Document(page_content=text, metadata=meta))
return docs
[docs] @classmethod
def from_texts(
cls: Type[Weaviate],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]]... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
335a62e7b5d8-5 | 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 metadatas else None
# check whether the index al... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
4d42fc38a60f-0 | Source code for langchain.vectorstores.qdrant
"""Wrapper around Qdrant vector database."""
from __future__ import annotations
import uuid
from operator import itemgetter
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union
from langchain.docstore.document import Document
from langchain.e... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4d42fc38a60f-1 | f"client should be an instance of qdrant_client.QdrantClient, "
f"got {type(client)}"
)
self.client: qdrant_client.QdrantClient = client
self.collection_name = collection_name
self.embedding_function = embedding_function
self.content_payload_key = content_payl... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4d42fc38a60f-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.
filter: Filter by metadata. Defaults to None.
Returns:
List of Documents most similar to the query.
"""
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4d42fc38a60f-3 | **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/qdrant.html |
4d42fc38a60f-4 | prefix: Optional[str] = None,
timeout: Optional[float] = None,
host: Optional[str] = None,
path: Optional[str] = None,
collection_name: Optional[str] = None,
distance_func: str = "Cosine",
content_payload_key: str = CONTENT_KEY,
metadata_payload_key: str = METADAT... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4d42fc38a60f-5 | Example: service/v1 will result in
http://localhost:6333/service/v1/{qdrant-endpoint} for REST API.
Default: None
timeout:
Timeout for REST and gRPC API requests.
Default: 5.0 seconds for REST and unlimited for gRPC
host:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4d42fc38a60f-6 | from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
qdrant = Qdrant.from_texts(texts, embeddings, "localhost")
"""
try:
import qdrant_client
except ImportError:
raise ValueError(
"Could not impo... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4d42fc38a60f-7 | texts, metadatas, content_payload_key, metadata_payload_key
),
),
)
return cls(
client=client,
collection_name=collection_name,
embedding_function=embedding.embed_query,
content_payload_key=content_payload_key,
metad... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
4d42fc38a60f-8 | return rest.Filter(
must=[
rest.FieldCondition(
key=f"{self.metadata_payload_key}.{key}",
match=rest.MatchValue(value=value),
)
for key, value in filter.items()
]
)
By Harrison Chase
© Copy... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
01302bf4a160-0 | Source code for langchain.prompts.chat
"""Chat prompt template."""
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, List, Sequence, Tuple, Type, Union
from pydantic import BaseModel, Field
from langchain.memory.buffer import get_buffer_str... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
01302bf4a160-1 | def input_variables(self) -> List[str]:
"""Input variables for this prompt template."""
return [self.variable_name]
class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
prompt: StringPromptTemplate
additional_kwargs: dict = Field(default_factory=dict)
@classmethod
def f... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
01302bf4a160-2 | text = self.prompt.format(**kwargs)
return SystemMessage(content=text, additional_kwargs=self.additional_kwargs)
class ChatPromptValue(PromptValue):
messages: List[BaseMessage]
def to_string(self) -> str:
"""Return prompt as string."""
return get_buffer_string(self.messages)
def to_m... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
01302bf4a160-3 | for role, template in string_messages
]
return cls.from_messages(messages)
@classmethod
def from_messages(
cls, messages: Sequence[Union[BaseMessagePromptTemplate, BaseMessage]]
) -> ChatPromptTemplate:
input_vars = set()
for message in messages:
if isinst... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
c10747ed13d5-0 | Source code for langchain.prompts.few_shot
"""Prompt template that contains few shot examples."""
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
StringPromptTemplate,
check_valid_template,
)
from langcha... | https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
c10747ed13d5-1 | """Check that one and only one of examples/example_selector are provided."""
examples = values.get("examples", None)
example_selector = values.get("example_selector", None)
if examples and example_selector:
raise ValueError(
"Only one of 'examples' and 'example_select... | https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
c10747ed13d5-2 | # Get the examples to use.
examples = self._get_examples(**kwargs)
# Format the examples.
example_strings = [
self.example_prompt.format(**example) for example in examples
]
# Create the overall template.
pieces = [self.prefix, *example_strings, self.suffix]
... | https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
7187430eb733-0 | Source code for langchain.prompts.loading
"""Load prompts from disk."""
import importlib
import json
import logging
from pathlib import Path
from typing import Union
import yaml
from langchain.output_parsers.regex import RegexParser
from langchain.prompts.base import BasePromptTemplate
from langchain.prompts.few_shot i... | https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.