id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
a4fca93b5831-0 | Source code for langchain.vectorstores.zilliz
from __future__ import annotations
import logging
from typing import Any, List, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.milvus import Milvus
logger = logging.getLogger(__name__)
[docs]class Zilliz(Milvus):
"""Initialize wrap... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
a4fca93b5831-1 | instance. Example address: "localhost:19530"
uri (str): The uri of Zilliz instance. Example uri:
"https://in03-ba4234asae.api.gcp-us-west1.zillizcloud.com",
host (str): The host of Zilliz instance. Default at "localhost",
PyMilvus will fill in the default host if only port is pro... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
a4fca93b5831-2 | embedding = OpenAIEmbeddings()
# Connect to a Zilliz instance
milvus_store = Milvus(
embedding_function = embedding,
collection_name = "LangChainCollection",
connection_args = {
"uri": "https://in03-ba4234asae.api.gcp-us-west1.zillizcloud.com",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
a4fca93b5831-3 | }
self.col.create_index(
self._vector_field,
index_params=self.index_params,
using=self.alias,
)
logger.debug(
"Successfully created an index on collection: %s",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
a4fca93b5831-4 | Defaults to None.
search_params (Optional[dict], optional): Which search params to use.
Defaults to None.
drop_old (Optional[bool], optional): Whether to drop the collection with
that name if it exists. Defaults to False.
Returns:
Zilliz: Zilli... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
1d984b4c4a31-0 | Source code for langchain.vectorstores.lancedb
"""Wrapper around LanceDB vector database"""
from __future__ import annotations
import uuid
from typing import Any, Iterable, List, Optional
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.base i... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
1d984b4c4a31-1 | self._id_key = id_key
self._text_key = text_key
@property
def embeddings(self) -> Embeddings:
return self._embedding
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
1d984b4c4a31-2 | Returns:
List of documents most similar to the query.
"""
embedding = self._embedding.embed_query(query)
docs = self._connection.search(embedding).limit(k).to_df()
return [
Document(
page_content=row[self._text_key],
metadata=row[do... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
44240a494a4b-0 | Source code for langchain.vectorstores.awadb
"""Wrapper around AwaDB for embedding vectors"""
from __future__ import annotations
import logging
import uuid
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Set, Tuple, Type
import numpy as np
from langchain.docstore.document import Document
from lan... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-1 | raise ValueError(
"Could not import awadb python package. "
"Please install it with `pip install awadb`."
)
if client is not None:
self.awadb_client = client
else:
if log_and_data_dir is not None:
self.awadb_client = awa... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-2 | List of ids from adding the texts into the vectorstore.
"""
if self.awadb_client is None:
raise ValueError("AwaDB client is None!!!")
embeddings = None
if self.using_table_name in self.table2embeddings:
embeddings = self.table2embeddings[self.using_table_name].emb... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-3 | meta_filter (Optional[dict]): Filter by metadata. Defaults to None.
E.g. `{"color" : "red", "price": 4.20}`. Optional.
E.g. `{"max_price" : 15.66, "min_price": 4.20}`
`price` is the metadata field, means range filter(4.20<'price'<15.66).
E.g. `{"maxe_price" : 15.66, "mine... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-4 | meta_filter: Optional[dict] = None,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""The most k similar documents and scores of the specified query.
Args:
query: Text query.
k: The k most similar documents to the text query.
text_in_page_content: Filte... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-5 | self,
query: str,
k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
return self.similarity_search_with_score(query, k, **kwargs)
[docs] def similarity_search_by_vector(
self,
embedding: Optional[List[float]] = None,
k: int = DEFAULT_TOPN,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-6 | content = ""
meta_data = {}
for item_key in item_detail:
if item_key == "embedding_text":
content = item_detail[item_key]
continue
elif not_include_fields_in_metadata is not None:
if item_key in not_inclu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-7 | raise ValueError("AwaDB client is None!!!")
embedding: List[float] = []
if self.using_table_name in self.table2embeddings:
embedding = self.table2embeddings[self.using_table_name].embed_query(query)
else:
from awadb import AwaEmbedding
embedding = AwaEmbedding... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-8 | Defaults to 0.5.
text_in_page_content: Filter by the text in page_content of Document.
meta_filter (Optional[dict]): Filter by metadata. Defaults to None.
Returns:
List of Documents selected by maximal marginal relevance.
"""
if self.awadb_client is None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-9 | Args:
ids: The ids of the embedding vectors.
text_in_page_content: Filter by the text in page_content of Document.
meta_filter: Filter by any metadata of the document.
not_include_fields: Not pack the specified fields of each document.
limit: The number of doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-10 | False otherwise, None if not implemented.
"""
if self.awadb_client is None:
raise ValueError("AwaDB client is None!!!")
ret: Optional[bool] = None
if ids is None or ids.__len__() == 0:
return ret
ret = self.awadb_client.Delete(ids)
return ret
[docs... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-11 | table_name: str,
**kwargs: Any,
) -> bool:
"""Use the specified table. Don't know the tables, please invoke list_tables."""
if self.awadb_client is None:
return False
ret = self.awadb_client.Use(table_name)
if ret:
self.using_table_name = table_name
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-12 | table_name (str): Name of the table to create.
log_and_data_dir (Optional[str]): Directory of logging and persistence.
client (Optional[awadb.Client]): AwaDB client
Returns:
AwaDB: AwaDB vectorstore.
"""
awadb_client = cls(
table_name=table_name,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
44240a494a4b-13 | metadatas = [doc.metadata for doc in documents]
return cls.from_texts(
texts=texts,
embedding=embedding,
metadatas=metadatas,
table_name=table_name,
log_and_data_dir=log_and_data_dir,
client=client,
) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html |
7167c33ab80f-0 | Source code for langchain.vectorstores.meilisearch
"""Wrapper around Meilisearch vector database."""
from __future__ import annotations
import uuid
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type
from langchain.docstore.document import Document
from langchain.embeddings.base import Em... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html |
7167c33ab80f-1 | """Initialize wrapper around Meilisearch vector database.
To use this, you need to have `meilisearch` python package installed,
and a running Meilisearch instance.
To learn more about Meilisearch Python, refer to the in-depth
Meilisearch Python documentation: https://meilisearch.github.io/meilisearch-py... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html |
7167c33ab80f-2 | self._client = client
self._index_name = index_name
self._embedding = embedding
self._text_key = text_key
self._metadata_key = metadata_key
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html |
7167c33ab80f-3 | self._client.index(str(self._index_name)).add_documents(docs)
return ids
[docs] def similarity_search(
self,
query: str,
k: int = 4,
filter: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return meilisearch documents most similar to... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html |
7167c33ab80f-4 | text and score for each.
"""
_query = self._embedding.embed_query(query)
docs = self.similarity_search_by_vector_with_scores(
embedding=_query,
k=k,
filter=filter,
kwargs=kwargs,
)
return docs
[docs] def similarity_search_by_vect... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html |
7167c33ab80f-5 | filter: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return meilisearch documents most similar to embedding vector.
Args:
embedding (List[float]): Embedding to look up similar documents.
k (int): Number of documents to return. Defaults to 4.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html |
7167c33ab80f-6 | This is intended to be a quick way to get started.
Example:
.. code-block:: python
from langchain import Meilisearch
from langchain.embeddings import OpenAIEmbeddings
import meilisearch
# The environment should be the one specified next... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html |
643e022d96e1-0 | Source code for langchain.vectorstores.clarifai
from __future__ import annotations
import logging
import os
import traceback
from typing import Any, Iterable, List, Optional, Tuple
import requests
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstor... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
643e022d96e1-1 | """
try:
from clarifai.auth.helper import DEFAULT_BASE, ClarifaiAuthHelper
from clarifai.client import create_stub
except ImportError:
raise ValueError(
"Could not import clarifai python package. "
"Please install it with `pip install c... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
643e022d96e1-2 | Args:
text (str): Text to post.
metadata (dict): Metadata to post.
Returns:
str: ID of the input.
"""
try:
from clarifai_grpc.grpc.api import resources_pb2, service_pb2
from clarifai_grpc.grpc.api.status import status_code_pb2
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
643e022d96e1-3 | to a Clarifai application.
Application use base workflow that create and store embedding for each text.
Make sure you are using a base workflow that is compatible with text
(such as Language Understanding).
Args:
texts (Iterable[str]): Texts to add to the vectorstore.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
643e022d96e1-4 | Args:
query (str): Query text to search for.
k (int): Number of results to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata.
Defaults to None.
Returns:
List[Document]: List of documents most similar to the query text.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
643e022d96e1-5 | + post_annotations_searches_response.status.description
)
# Retrieve hits
hits = post_annotations_searches_response.hits
docs_and_scores = []
# Iterate over hits and retrieve metadata and text
for hit in hits:
metadata = json_format.MessageToDict(hit.input... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
643e022d96e1-6 | app_id: Optional[str] = None,
pat: Optional[str] = None,
number_of_docs: Optional[int] = None,
api_base: Optional[str] = None,
**kwargs: Any,
) -> Clarifai:
"""Create a Clarifai vectorstore from a list of texts.
Args:
user_id (str): User ID.
ap... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
643e022d96e1-7 | **kwargs: Any,
) -> Clarifai:
"""Create a Clarifai vectorstore from a list of documents.
Args:
user_id (str): User ID.
app_id (str): App ID.
documents (List[Document]): List of documents to add.
pat (Optional[str]): Personal access token. Defaults to N... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
ec8228f89aff-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 |
ec8228f89aff-1 | 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 False.
Generally useful d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
ec8228f89aff-2 | """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]]): An optional list of ids.
refresh(b... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
ec8228f89aff-3 | self.project.add_embeddings(embeddings=embeddings, data=data)
# Text upload case
else:
if metadatas is None:
data = [
{"text": text, AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i]}
for i, text in enumerate(texts)
]
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
ec8228f89aff-4 | Returns:
List[Document]: List of documents most similar to the query text.
"""
if self._embedding_function is None:
raise NotImplementedError(
"AtlasDB requires an embedding_function for text similarity search!"
)
_embedding = self._embedding_f... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
ec8228f89aff-5 | embedding (Optional[Embeddings]): Embedding function. Defaults to None.
metadatas (Optional[List[dict]]): List of metadatas. Defaults to None.
ids (Optional[List[str]]): Optional list of document IDs. If None,
ids will be auto created
description (str): A description ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
ec8228f89aff-6 | def from_documents(
cls: Type[AtlasDB],
documents: List[Document],
embedding: Optional[Embeddings] = None,
ids: Optional[List[str]] = None,
name: Optional[str] = None,
api_key: Optional[str] = None,
persist_directory: Optional[str] = None,
description: str... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
ec8228f89aff-7 | texts = [doc.page_content for doc in documents]
metadatas = [doc.metadata for doc in documents]
return cls.from_texts(
name=name,
api_key=api_key,
texts=texts,
embedding=embedding,
metadatas=metadatas,
ids=ids,
descripti... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
12ef878aeaaa-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 |
12ef878aeaaa-1 | self,
dim: int,
distance_type: str,
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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
12ef878aeaaa-2 | ) -> List[Document]:
"""
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 d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
12ef878aeaaa-3 | 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 = tairvector.IndexType.HNSW
if "index_type" in kwargs:
index_type... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
12ef878aeaaa-4 | 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,
) -> Tair:
texts = [d.page_content for d in docum... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
12ef878aeaaa-5 | # 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",
metadata_key: str = "metadat... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
f9a52219ec3a-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 |
f9a52219ec3a-1 | 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 implementation. Whil... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
f9a52219ec3a-2 | raise ImportError(
"You must run `pip install --upgrade "
"google-cloud-aiplatform google-cloud-storage`"
"to use the MatchingEngine Vectorstore."
)
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
f9a52219ec3a-3 | f"{self.gcs_bucket_name}/{filename}."
)
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_locat... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
f9a52219ec3a-4 | # and the similarity_search method only receives one query. This
# means that the match method will always return an array with only
# one element.
for doc in response[0]:
page_content = self._download_from_gcs(f"documents/{doc.id}")
results.append(Document(page_content=p... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
f9a52219ec3a-5 | "This method is not implemented. Instead, you should initialize the class"
" with `MatchingEngine.from_components(...)` and then call "
"`add_texts`"
)
[docs] @classmethod
def from_components(
cls: Type["MatchingEngine"],
project_id: str,
region: str,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
f9a52219ec3a-6 | )
gcs_client = cls._get_gcs_client(credentials, project_id)
cls._init_aiplatform(project_id, region, gcs_bucket_name, credentials)
return cls(
project_id=project_id,
index=index,
endpoint=endpoint,
embedding=embedding or cls._get_default_embeddings... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
f9a52219ec3a-7 | json_credentials_path
)
return credentials
@classmethod
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 c... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
f9a52219ec3a-8 | )
@classmethod
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=cre... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/matching_engine.html |
7dcdb6f859f1-0 | Source code for langchain.vectorstores.cassandra
"""Wrapper around Cassandra vector-store capabilities, based on cassIO."""
from __future__ import annotations
import typing
import uuid
from typing import Any, Callable, Iterable, List, Optional, Tuple, Type, TypeVar
import numpy as np
if typing.TYPE_CHECKING:
from c... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
7dcdb6f859f1-1 | ) -> None:
try:
from cassio.vector import VectorTable
except (ImportError, ModuleNotFoundError):
raise ImportError(
"Could not import cassio python package. "
"Please install it with `pip install cassio`."
)
"""Create a vector t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
7dcdb6f859f1-2 | False otherwise, None if not implemented.
"""
if ids is None:
raise ValueError("No ids provided to delete.")
for document_id in ids:
self.delete_by_document_id(document_id)
return True
[docs] def add_texts(
self,
texts: Iterable[str],
me... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
7dcdb6f859f1-3 | batch_texts = _texts[i : i + batch_size]
batch_embedding_vectors = embedding_vectors[i : i + batch_size]
batch_ids = ids[i : i + batch_size]
batch_metadatas = metadatas[i : i + batch_size]
futures = [
self.table.put_async(
text, embeddi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
7dcdb6f859f1-4 | page_content=hit["document"],
metadata=hit["metadata"],
),
0.5 + 0.5 * hit["distance"],
hit["document_id"],
)
for hit in hits
]
[docs] def similarity_search_with_score_id(
self,
query: str,
k: ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
7dcdb6f859f1-5 | return self.similarity_search_by_vector(
embedding_vector,
k,
)
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
**kwargs: Any,
) -> List[Document]:
return [
doc
for doc, _ in self.sim... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
7dcdb6f859f1-6 | """
prefetchHits = self.table.search(
embedding_vector=embedding,
top_k=fetch_k,
metric="cos",
metric_threshold=None,
)
# let the mmr utility pick the *indices* in the above array
mmrChosenIndices = maximal_marginal_relevance(
n... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
7dcdb6f859f1-7 | Optional.
Returns:
List of Documents selected by maximal marginal relevance.
"""
embedding_vector = self.embedding.embed_query(query)
return self.max_marginal_relevance_search_by_vector(
embedding_vector,
k,
fetch_k,
lambda_mult... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
7dcdb6f859f1-8 | metadatas = [doc.metadata for doc in documents]
session: Session = kwargs["session"]
keyspace: str = kwargs["keyspace"]
table_name: str = kwargs["table_name"]
return cls.from_texts(
texts=texts,
metadatas=metadatas,
embedding=embedding,
ses... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
a419b665fc9d-0 | Source code for langchain.vectorstores.alibabacloud_opensearch
import json
import logging
import numbers
from hashlib import sha1
from typing import Any, Dict, Iterable, List, Optional, Tuple
from langchain.embeddings.base import Embeddings
from langchain.schema import Document
from langchain.vectorstores.base import V... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
a419b665fc9d-1 | instance_id: str
username: str
password: str
datasource_name: str
embedding_index_name: str
field_name_mapping: Dict[str, str] = {
"id": "id",
"document": "document",
"embedding": "embedding",
"metadata_field_x": "metadata_field_x,operator",
}
[docs] def __init... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
a419b665fc9d-2 | [docs] def __init__(
self,
embedding: Embeddings,
config: AlibabaCloudOpenSearchSettings,
**kwargs: Any,
) -> None:
try:
from alibabacloud_ha3engine import client, models
from alibabacloud_tea_util import models as util_models
except ImportE... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
a419b665fc9d-3 | )
push_response = self.ha3EngineClient.push_documents(
self.config.datasource_name, field_name_map["id"], push_request
)
json_response = json.loads(push_response.body)
if json_response["status"] == "OK":
return [
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
a419b665fc9d-4 | ",".join(str(unit) for unit in embedding),
)
if metadata is not None:
for md_key, md_value in metadata.items():
add_doc_fields.__setitem__(
field_name_map[md_key].split(",")[0], md_value
)
add_doc.__s... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
a419b665fc9d-5 | return self.create_results(
self.inner_embedding_query(
embedding=embedding, search_filter=search_filter, k=k
)
)
[docs] def inner_embedding_query(
self,
embedding: List[float],
search_filter: Optional[Dict[str, Any]] = None,
k: int = 4,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
a419b665fc9d-6 | )
return ""
md_filter_key = expr[0].strip()
md_filter_operator = expr[1].strip()
if isinstance(md_value, numbers.Number):
return f"{md_filter_key} {md_filter_operator} {md_value}"
return f'{md_filter_key}{md_filter_operator}"{md_value}"'
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
a419b665fc9d-7 | metadata=create_metadata(fields),
)
)
return query_result_list
[docs] def create_results_with_score(
self, json_result: Dict[str, Any]
) -> List[Tuple[Document, float]]:
items = json_result["result"]["items"]
query_result_list: List[Tuple[Document, floa... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
a419b665fc9d-8 | texts = [d.page_content for d in documents]
metadatas = [d.metadata for d in documents]
return cls.from_texts(
texts=texts,
embedding=embedding,
metadatas=metadatas,
config=config,
**kwargs,
) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
bf5abe4502b0-0 | Source code for langchain.vectorstores.pinecone
"""Wrapper around Pinecone vector database."""
from __future__ import annotations
import logging
import uuid
from typing import Any, Callable, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.bas... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
bf5abe4502b0-1 | )
if not isinstance(index, pinecone.index.Index):
raise ValueError(
f"client should be an instance of pinecone.index.Index, "
f"got {type(index)}"
)
self._index = index
self._embedding_function = embedding_function
self._text_key = ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
bf5abe4502b0-2 | docs.append((ids[i], embedding, metadata))
# upsert to Pinecone
self._index.upsert(
vectors=docs, namespace=namespace, batch_size=batch_size, **kwargs
)
return ids
[docs] def similarity_search_with_score(
self,
query: str,
k: int = 4,
filter... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
bf5abe4502b0-3 | [docs] def similarity_search(
self,
query: str,
k: int = 4,
filter: Optional[dict] = None,
namespace: Optional[str] = None,
**kwargs: Any,
) -> List[Document]:
"""Return pinecone documents most similar to query.
Args:
query: Text to look... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
bf5abe4502b0-4 | raise ValueError(
"Unknown distance strategy, must be cosine, max_inner_product "
"(dot product), or euclidean"
)
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
bf5abe4502b0-5 | k=k,
lambda_mult=lambda_mult,
)
selected = [results["matches"][i]["metadata"] for i in mmr_selected]
return [
Document(page_content=metadata.pop((self._text_key)), metadata=metadata)
for metadata in selected
]
[docs] def max_marginal_relevance_searc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
bf5abe4502b0-6 | metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
batch_size: int = 32,
text_key: str = "text",
index_name: Optional[str] = None,
namespace: Optional[str] = None,
upsert_kwargs: Optional[dict] = None,
**kwargs: Any,
) -> Pinecone:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
bf5abe4502b0-7 | "are you sure you're using the right API key and environment?"
)
else:
raise ValueError(
f"Index '{index_name}' not found in your Pinecone project. "
f"Did you mean one of the following indexes: {', '.join(indexes)}"
)
for i in range(0,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
bf5abe4502b0-8 | namespace: Optional[str] = None,
) -> Pinecone:
"""Load pinecone vectorstore from index name."""
try:
import pinecone
except ImportError:
raise ValueError(
"Could not import pinecone python package. "
"Please install it with `pip instal... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
fe1da3249493-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 |
fe1da3249493-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))
def _json_serializable(value: Any) -> Any:
if isinstance(value, datetime.datetime):
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
fe1da3249493-2 | )
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
self._embedding = embedding
self._text_key = text_k... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
fe1da3249493-3 | data_properties[key] = _json_serializable(val)
# Allow for ids (consistent w/ other methods)
# # Or uuids (backwards compatble w/ existing arg)
# If the UUID of one of the objects already exists
# then the existing object will be replaced by the new object... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
fe1da3249493-4 | 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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
fe1da3249493-5 | if kwargs.get("additional"):
query_obj = query_obj.with_additional(kwargs.get("additional"))
result = query_obj.with_near_vector(vector).with_limit(k).do()
if "errors" in result:
raise ValueError(f"Error during query: {result['errors']}")
docs = []
for res in resu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
fe1da3249493-6 | )
return self.max_marginal_relevance_search_by_vector(
embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, **kwargs
)
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
fe1da3249493-7 | mmr_selected = maximal_marginal_relevance(
np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult
)
docs = []
for idx in mmr_selected:
text = payload[idx].pop(self._text_key)
payload[idx].pop("_additional")
meta = payload[idx]
do... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
fe1da3249493-8 | raise ValueError(f"Error during query: {result['errors']}")
docs_and_scores = []
for res in result["data"]["Get"][self._index_name]:
text = res.pop(self._text_key)
score = np.dot(res["_additional"]["vector"], embedded_query)
docs_and_scores.append((Document(page_conte... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
fe1da3249493-9 | text_key = "text"
schema = _default_schema(index_name)
attributes = list(metadatas[0].keys()) if metadatas else None
# check whether the index already exists
if not client.schema.contains(schema):
client.schema.create_class(schema)
with client.batch as batch:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
fe1da3249493-10 | relevance_score_fn=relevance_score_fn,
by_text=by_text,
)
[docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None:
"""Delete by vector IDs.
Args:
ids: List of ids to delete.
"""
if ids is None:
raise ValueError("No id... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
a3995490ca87-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 (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Mapping,
Optional,
Tuple,
Union,
)
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
a3995490ca87-1 | # defined as an abstract base class itself, allowing the creation of subclasses with
# their own specific implementations. If you plan to subclass ElasticVectorSearch,
# you can inherit from it and define your own implementation of the necessary methods
# and attributes.
[docs]class ElasticVectorSearch(VectorStore, ABC... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.