id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
90d40b6cee25-20 | embedding = self.embedding_function(query)
docs = self.max_marginal_relevance_search_by_vector(
embedding,
k,
fetch_k,
lambda_mult=lambda_mult,
filter=filter,
**kwargs,
)
return docs
[docs] def merge_from(self, target: FA... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-21 | # Merge two IndexFlatL2
self.index.merge_from(target.index)
# Get id and docs from target FAISS object
full_info = []
for i, target_id in target.index_to_docstore_id.items():
doc = target.docstore.search(target_id)
if not isinstance(doc, Document):
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-22 | embeddings: List[List[float]],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
normalize_L2: bool = False,
**kwargs: Any,
) -> FAISS:
faiss = dependable_faiss_import()
index = faiss.IndexFlatL2(len(embeddings[0])... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-23 | index_to_id = dict(enumerate(ids))
docstore = InMemoryDocstore(dict(zip(index_to_id.values(), documents)))
return cls(
embedding.embed_query,
index,
docstore,
index_to_id,
normalize_L2=normalize_L2,
**kwargs,
)
[docs] @cl... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-24 | 3. Initializes the FAISS database
This is intended to be a quick way to get started.
Example:
.. code-block:: python
from langchain import FAISS
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
f... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-25 | **kwargs: Any,
) -> FAISS:
"""Construct FAISS wrapper from raw documents.
This is a user friendly interface that:
1. Embeds documents.
2. Creates an in memory docstore
3. Initializes the FAISS database
This is intended to be a quick way to get started.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-26 | return cls.__from(
texts,
embeddings,
embedding,
metadatas=metadatas,
ids=ids,
**kwargs,
)
[docs] def save_local(self, folder_path: str, index_name: str = "index") -> None:
"""Save FAISS index, docstore, and index_to_docstore_id ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-27 | faiss.write_index(
self.index, str(path / "{index_name}.faiss".format(index_name=index_name))
)
# save docstore and index_to_docstore_id
with open(path / "{index_name}.pkl".format(index_name=index_name), "wb") as f:
pickle.dump((self.docstore, self.index_to_docstore_id), ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-28 | """
path = Path(folder_path)
# load index separately since it is not picklable
faiss = dependable_faiss_import()
index = faiss.read_index(
str(path / "{index_name}.faiss".format(index_name=index_name))
)
# load docstore and index_to_docstore_id
with op... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
90d40b6cee25-29 | **kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs and their similarity scores on a scale from 0 to 1."""
if self.relevance_score_fn is None:
raise ValueError(
"normalize_score_fn must be provided to"
" FAISS constructor to normalize scores"
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
d9089cdcde2e-0 | Source code for langchain.vectorstores.matching_engine
"""Vertex Matching Engine implementation of the vector store."""
from __future__ import annotations
import json
import logging
import time
import uuid
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Type
from langchain.docstore.document import Docu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-1 | documents will be stored in GCS.
An existing Index and corresponding Endpoint are preconditions for
using this module.
See usage in docs/modules/indexes/vectorstores/examples/matchingengine.ipynb
Note that this implementation is mostly meant for reading if you are
planning to do a real time implemen... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-2 | documents will be stored in GCS.
An existing Index and corresponding Endpoint are preconditions for
using this module.
See usage in
docs/modules/indexes/vectorstores/examples/matchingengine.ipynb.
Note that this implementation is mostly meant for reading if you are
planni... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-3 | gcs_client: The GCS client.
gcs_bucket_name: The GCS bucket name.
credentials (Optional): Created GCP credentials.
"""
super().__init__()
self._validate_google_libraries_installation()
self.project_id = project_id
self.index = index
self.endpoint =... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-4 | "google-cloud-aiplatform google-cloud-storage`"
"to use the MatchingEngine Vectorstore."
)
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the emb... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-5 | # Could be improved with async.
for embedding, text in zip(embeddings, texts):
id = str(uuid.uuid4())
ids.append(id)
jsons.append({"id": id, "embedding": embedding})
self._upload_to_gcs(text, f"documents/{id}")
logger.debug(f"Uploaded {len(ids)} documents ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-6 | self.index = self.index.update_embeddings(
contents_delta_uri=f"gs://{self.gcs_bucket_name}/{filename_prefix}/"
)
logger.debug("Updated index with new configuration.")
return ids
def _upload_to_gcs(self, data: str, gcs_location: str) -> None:
"""Uploads data to gcs_locati... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-7 | Args:
query: The string that will be used to search for similar documents.
k: The amount of neighbors that will be retrieved.
Returns:
A list of k matching documents.
"""
logger.debug(f"Embedding query {query}.")
embedding_query = self.embedding.embed_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-8 | # one element.
for doc in response[0]:
page_content = self._download_from_gcs(f"documents/{doc.id}")
results.append(Document(page_content=page_content))
logger.debug("Downloaded documents for query.")
return results
def _get_index_id(self) -> str:
"""Gets the ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-9 | """Downloads from GCS in text format.
Args:
gcs_location: The location where the file is located.
Returns:
The string contents of the file.
"""
bucket = self.gcs_client.get_bucket(self.gcs_bucket_name)
blob = bucket.blob(gcs_location)
return blob.d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-10 | "`add_texts`"
)
[docs] @classmethod
def from_components(
cls: Type["MatchingEngine"],
project_id: str,
region: str,
gcs_bucket_name: str,
index_id: str,
endpoint_id: str,
credentials_path: Optional[str] = None,
embedding: Optional[Embeddings... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-11 | endpoint_id: The id of the created endpoint.
credentials_path: (Optional) The path of the Google credentials on
the local file system.
embedding: The :class:`Embeddings` that will be used for
embedding the texts.
Returns:
A configured MatchingEngine wi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-12 | return cls(
project_id=project_id,
index=index,
endpoint=endpoint,
embedding=embedding or cls._get_default_embeddings(),
gcs_client=gcs_client,
credentials=credentials,
gcs_bucket_name=gcs_bucket_name,
)
@classmethod
def... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-13 | f"the bucket name. Received {gcs_bucket_name}"
)
return gcs_bucket_name
@classmethod
def _create_credentials_from_file(
cls, json_credentials_path: Optional[str]
) -> Optional[Credentials]:
"""Creates credentials for GCP.
Args:
json_credentials_path: ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-14 | def _create_index_by_id(
cls, index_id: str, project_id: str, region: str, credentials: "Credentials"
) -> MatchingEngineIndex:
"""Creates a MatchingEngineIndex object by id.
Args:
index_id: The created index id.
project_id: The project to retrieve index from.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-15 | def _create_endpoint_by_id(
cls, endpoint_id: str, project_id: str, region: str, credentials: "Credentials"
) -> MatchingEngineIndexEndpoint:
"""Creates a MatchingEngineIndexEndpoint object by id.
Args:
endpoint_id: The created endpoint id.
project_id: The project to ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-16 | def _get_gcs_client(
cls, credentials: "Credentials", project_id: str
) -> "storage.Client":
"""Lazily creates a GCS client.
Returns:
A configured GCS client.
"""
from google.cloud import storage
return storage.Client(credentials=credentials, project=proje... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
d9089cdcde2e-17 | credentials: The GCS Credentials object.
"""
from google.cloud import aiplatform
logger.debug(
f"Initializing AI Platform for project {project_id} on "
f"{region} and for {gcs_bucket_name}."
)
aiplatform.init(
project=project_id,
lo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
436d6de4ad62-0 | Source code for langchain.vectorstores.tair
"""Wrapper around Tair Vector."""
from __future__ import annotations
import json
import logging
import uuid
from typing import Any, Iterable, List, Optional, Type
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
436d6de4ad62-1 | **kwargs: Any,
):
self.embedding_function = embedding_function
self.index_name = index_name
try:
from tair import Tair as TairClient
except ImportError:
raise ImportError(
"Could not import tair python package. "
"Please install... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
436d6de4ad62-2 | index_type: str,
data_type: str,
**kwargs: Any,
) -> bool:
index = self.client.tvs_get_index(self.index_name)
if index is not None:
logger.info("Index already exists")
return False
self.client.tvs_create_index(
self.index_name,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
436d6de4ad62-3 | # Write data to tair
pipeline = self.client.pipeline(transaction=False)
embeddings = self.embedding_function.embed_documents(list(texts))
for i, text in enumerate(texts):
# Use provided key otherwise use default key
key = keys[i] if keys else _uuid_key()
metad... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
436d6de4ad62-4 | """
Returns the most similar indexed documents to the query text.
Args:
query (str): The query text for which to find similar documents.
k (int): The number of documents to return. Default is 4.
Returns:
List[Document]: A list of documents that are most simila... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
436d6de4ad62-5 | return [
Document(
page_content=d[1],
metadata=json.loads(d[0]),
)
for d in docs
]
[docs] @classmethod
def from_texts(
cls: Type[Tair],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dic... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
436d6de4ad62-6 | )
url = get_from_dict_or_env(kwargs, "tair_url", "TAIR_URL")
if "tair_url" in kwargs:
kwargs.pop("tair_url")
distance_type = tairvector.DistanceMetric.InnerProduct
if "distance_type" in kwargs:
distance_type = kwargs.pop("distance_typ")
index_type = tairve... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
436d6de4ad62-7 | keys = None
if "keys" in kwargs:
keys = kwargs.pop("keys")
try:
tair_vector_store = cls(
embedding,
url,
index_name,
content_key=content_key,
metadata_key=metadata_key,
search_params=s... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
436d6de4ad62-8 | [docs] @classmethod
def from_documents(
cls,
documents: List[Document],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
index_name: str = "langchain",
content_key: str = "content",
metadata_key: str = "metadata",
**kwargs: Any,
) ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
436d6de4ad62-9 | Args:
index_name (str): Name of the index to drop.
Returns:
bool: True if the index is dropped successfully.
"""
try:
from tair import Tair as TairClient
except ImportError:
raise ValueError(
"Could not import tair python pa... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
436d6de4ad62-10 | if ret == 0:
# index not exist
logger.info("Index does not exist")
return False
return True
[docs] @classmethod
def from_existing_index(
cls,
embedding: Embeddings,
index_name: str = "langchain",
content_key: str = "content",
met... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
436d6de4ad62-11 | metadata_key=metadata_key,
search_params=search_params,
**kwargs,
) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
d9d58b1b82d9-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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-1 | """
_ATLAS_DEFAULT_ID_FIELD = "atlas_id"
def __init__(
self,
name: str,
embedding_function: Optional[Embeddings] = None,
api_key: Optional[str] = None,
description: str = "A description for your project",
is_public: bool = True,
reset_project_if_exists: bo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-2 | 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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-3 | self.project = AtlasProject(
name=name,
description=description,
modality=modality,
is_public=is_public,
reset_project_if_exists=reset_project_if_exists,
unique_id_field=AtlasDB._ATLAS_DEFAULT_ID_FIELD,
)
self.project._latest_projec... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-4 | 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.
"""
if (
metadatas is not None
and len(met... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-5 | data = [
{AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i], "text": texts[i]}
for i, _ in enumerate(texts)
]
else:
for i in range(len(metadatas)):
metadatas[i][AtlasDB._ATLAS_DEFAULT_ID_FIELD] = ids[i]
met... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-6 | for i, text in enumerate(texts)
]
else:
for i, text in enumerate(texts):
metadatas[i]["text"] = texts
metadatas[i][AtlasDB._ATLAS_DEFAULT_ID_FIELD] = ids[i]
data = metadatas
self.project._validate_map_data_in... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-7 | See
https://docs.nomic.ai/atlas_api.html#nomic.project.AtlasProject.create_index
for full detail.
"""
with self.project.wait_for_project_lock():
return self.project.create_index(**kwargs)
[docs] def similarity_search(
self,
query: str,
k: int = 4,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-8 | )
_embedding = self._embedding_function.embed_documents([query])[0]
embedding = np.array(_embedding).reshape(1, -1)
with self.project.wait_for_project_lock():
neighbors, _ = self.project.projections[0].vector_search(
queries=embedding, k=k
)
da... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-9 | name: Optional[str] = None,
api_key: Optional[str] = None,
description: str = "A description for your project",
is_public: bool = True,
reset_project_if_exists: bool = False,
index_kwargs: Optional[dict] = None,
**kwargs: Any,
) -> AtlasDB:
"""Create an AtlasD... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-10 | 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): Whether to reset this project if it
already exists. Default Fals... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-11 | all_index_kwargs[k] = v
# Build project
atlasDB = cls(
name,
embedding_function=embedding,
api_key=api_key,
description="A description for your project",
is_public=is_public,
reset_project_if_exists=reset_project_if_exists,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-12 | persist_directory: Optional[str] = None,
description: str = "A description for your project",
is_public: bool = True,
reset_project_if_exists: bool = False,
index_kwargs: Optional[dict] = None,
**kwargs: Any,
) -> AtlasDB:
"""Create an AtlasDB vectorstore from a list ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-13 | 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.
index_kwargs (Optio... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
d9d58b1b82d9-14 | embedding=embedding,
metadatas=metadatas,
ids=ids,
description=description,
is_public=is_public,
reset_project_if_exists=reset_project_if_exists,
index_kwargs=index_kwargs,
) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
aa3fd9b9e22d-0 | Source code for langchain.vectorstores.singlestoredb
"""Wrapper around SingleStore DB."""
from __future__ import annotations
import enum
import json
from typing import (
Any,
ClassVar,
Collection,
Iterable,
List,
Optional,
Tuple,
Type,
)
from sqlalchemy.pool import QueuePool
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-1 | DistanceStrategy.DOT_PRODUCT: "DESC",
}
[docs]class SingleStoreDB(VectorStore):
"""
This class serves as a Pythonic interface to the SingleStore DB database.
The prerequisite for using this class is the installation of the ``singlestoredb``
Python package.
The SingleStoreDB vectorstore can be create... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-2 | def __init__(
self,
embedding: Embeddings,
*,
distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
table_name: str = "embeddings",
content_field: str = "content",
metadata_field: str = "metadata",
vector_field: str = "vector",
pool_size... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-3 | This is the default behavior
- EUCLIDEAN_DISTANCE: Computes the Euclidean distance between
two vectors. This metric considers the geometric distance in
the vector space, and might be more suitable for embeddings
that rely on spatial relationshi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-4 | the pool. Defaults to 5.
max_overflow (int, optional): Determines the maximum number of connections
allowed beyond the pool_size. Defaults to 10.
timeout (float, optional): Specifies the maximum wait time in seconds for
establishing a connection. Defaults to 30.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-5 | database connection:
pure_python (bool, optional): Toggles the connector mode. If True,
operates in pure Python mode.
local_infile (bool, optional): Allows local file uploads.
charset (str, optional): Specifies the character set for string values.
ssl_key ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-6 | ssl_verify_identity (bool, optional): Verifies the server's identity.
conv (dict[int, Callable], optional): A dictionary of data conversion
functions.
credential_type (str, optional): Specifies the type of authentication to
use: auth.PASSWORD, auth.JWT, or auth.BR... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-7 | OpenAIEmbeddings(),
host="https://user:password@127.0.0.1:3306/database"
)
Advanced Usage:
.. code-block:: python
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import SingleStoreDB
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-8 | os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'
vectorstore = SingleStoreDB(OpenAIEmbeddings())
"""
self.embedding = embedding
self.distance_strategy = distance_strategy
self.table_name = table_name
self.content_field = content_field
self... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-9 | self.connection_kwargs["conn_attrs"][
"program_version"
] = "0.0.205" # the version of SingleStoreDB VectorStore implementation
"""Create connection pool."""
self.connection_pool = QueuePool(
self._get_connection,
max_overflow=max_overflow,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-10 | self.content_field,
self.vector_field,
self.metadata_field,
),
)
finally:
cur.close()
finally:
conn.close()
[docs] def add_texts(
self,
texts: Iterable[str],
met... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-11 | List[str]: empty list
"""
conn = self.connection_pool.connect()
try:
cur = conn.cursor()
try:
# Write data to singlestore db
for i, text in enumerate(texts):
# Use provided values by default or fallback
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-12 | conn.close()
return []
[docs] def similarity_search(
self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any
) -> List[Document]:
"""Returns the most similar indexed documents to the query text.
Uses cosine similarity.
Args:
query (str): The ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-13 | docs,
OpenAIEmbeddings(),
host="username:password@localhost:3306/database"
)
s2.similarity_search("query text", 1,
{"metadata_field": "metadata_value"})
"""
docs_and_scores = self.similarity_search_with_score(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-14 | filter: A dictionary of metadata fields and values to filter by.
Defaults to None.
Returns:
List of Documents most similar to the query and score for each
"""
# Creates embedding vector from user query
embedding = self.embedding.embed_query(query)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-15 | )
else:
arguments.append(
"JSON_EXTRACT_JSON({}, {}) = %s".format(
self.metadata_field,
", ".join(["%s"] * (len(prefix_args) + 1)),
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-16 | where_clause,
ORDERING_DIRECTIVE[self.distance_strategy],
),
("[{}]".format(",".join(map(str, embedding))),)
+ tuple(where_clause_values)
+ (k,),
)
for row in cur.fetchall():
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-17 | content_field: str = "content",
metadata_field: str = "metadata",
vector_field: str = "vector",
pool_size: int = 5,
max_overflow: int = 10,
timeout: float = 30,
**kwargs: Any,
) -> SingleStoreDB:
"""Create a SingleStoreDB vectorstore from raw documents.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-18 | texts,
OpenAIEmbeddings(),
host="username:password@localhost:3306/database"
)
"""
instance = cls(
embedding,
distance_strategy=distance_strategy,
table_name=table_name,
content_field=content_field,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
aa3fd9b9e22d-19 | """Retriever for SingleStoreDB vector stores."""
vectorstore: SingleStoreDB
k: int = 4
allowed_search_types: ClassVar[Collection[str]] = ("similarity",)
def get_relevant_documents(self, query: str) -> List[Document]:
if self.search_type == "similarity":
docs = self.vectorstore.simila... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html |
ff0557551d47-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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-1 | client = kwargs.get("client")
if client is not None:
return client
weaviate_url = get_from_dict_or_env(kwargs, "weaviate_url", "WEAVIATE_URL")
try:
# the weaviate api key param should not be mandatory
weaviate_api_key = get_from_dict_or_env(
kwargs, "weaviate_api_key", "W... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-2 | 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))
def _json_serializable(value: Any) -> Any:
if isinstance(value, datetime.datetime):
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-3 | weaviate = Weaviate(client, index_name, text_key)
"""
def __init__(
self,
client: Any,
index_name: str,
text_key: str,
embedding: Optional[Embeddings] = None,
attributes: Optional[List[str]] = None,
relevance_score_fn: Optional[
Callable[[float... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-4 | raise ValueError(
f"client should be an instance of weaviate.Client, got {type(client)}"
)
self._client = client
self._index_name = index_name
self._embedding = embedding
self._text_key = text_key
self._query_attrs = [self._text_key]
self._rele... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-5 | ids = []
with self._client.batch as batch:
for i, text in enumerate(texts):
data_properties = {self._text_key: text}
if metadatas is not None:
for key, val in metadatas[i].items():
data_properties[key] = _json_serializable(v... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-6 | if self._embedding is not None:
vector = self._embedding.embed_documents([text])[0]
else:
vector = None
batch.add_data_object(
data_object=data_properties,
class_name=self._index_name,
uui... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-7 | if self._by_text:
return self.similarity_search_by_text(query, k, **kwargs)
else:
if self._embedding is None:
raise ValueError(
"_embedding cannot be None for similarity_search when "
"_by_text=False"
)
e... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-8 | """
content: Dict[str, Any] = {"concepts": [query]}
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.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-9 | return docs
[docs] def similarity_search_by_vector(
self, embedding: List[float], k: int = 4, **kwargs: Any
) -> List[Document]:
"""Look up similar documents by embedding vector in Weaviate."""
vector = {"vector": embedding}
query_obj = self._client.query.get(self._index_name, sel... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-10 | text = res.pop(self._text_key)
docs.append(Document(page_content=text, metadata=res))
return docs
[docs] def max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Docum... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-11 | 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.
"""
if self._embedding is not None:
emb... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-12 | **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:
embedding: Embedding to look up documents similar to.
k... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-13 | if kwargs.get("where_filter"):
query_obj = query_obj.with_where(kwargs.get("where_filter"))
results = (
query_obj.with_additional("vector")
.with_near_vector(vector)
.with_limit(fetch_k)
.do()
)
payload = results["data"]["Get"][self._in... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-14 | self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[Document, float]]:
"""
Return list of documents most similar to the query
text and cosine distance in float for each.
Lower score represents more similarity.
"""
if self._embedding is None:
raise ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-15 | result = (
query_obj.with_near_vector(vector)
.with_limit(k)
.with_additional("vector")
.do()
)
else:
result = (
query_obj.with_near_text(content)
.with_limit(k)
.with_addition... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-16 | self,
query: str,
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.
"""
if self._relevance_score_fn is None:
raise ValueError(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-17 | texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
**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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-18 | texts,
embeddings,
weaviate_url="http://localhost:8080"
)
"""
client = _create_weaviate_client(**kwargs)
from weaviate.util import get_valid_uuid
index_name = kwargs.get("index_name", f"LangChain_{uuid4().hex}")
embeddings =... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-19 | if metadatas is not None:
for key in metadatas[i].keys():
data_properties[key] = metadatas[i][key]
# If the UUID of one of the objects already exists
# then the existing objectwill be replaced by the new object.
if "uuids" in kw... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
ff0557551d47-20 | if embeddings is not None:
params["vector"] = embeddings[i]
batch.add_data_object(**params)
batch.flush()
relevance_score_fn = kwargs.get("relevance_score_fn")
by_text: bool = kwargs.get("by_text", False)
return cls(
client,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
79acd5ad3a21-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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
79acd5ad3a21-1 | return False
return True
[docs]class MyScaleSettings(BaseSettings):
"""MyScale Client Configuration
Attribute:
myscale_host (str) : An URL to connect to MyScale backend.
Defaults to 'localhost'.
myscale_port (int) : URL port to connect with HTTP. Defaults to 8443... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
79acd5ad3a21-2 | supported are ('l2', 'cosine', 'ip'). Defaults to 'cosine'.
column_map (Dict) : Column type map to project column name onto langchain
semantics. Must have keys: `text`, `id`, `vector`,
must be same size to number of columns. For example:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
79acd5ad3a21-3 | column_map: Dict[str, str] = {
"id": "id",
"text": "text",
"vector": "vector",
"metadata": "metadata",
}
database: str = "default"
table: str = "langchain"
metric: str = "cosine"
def __getitem__(self, item: str) -> Any:
return getattr(self, item)
class Con... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.