id
stringlengths
14
15
text
stringlengths
44
2.47k
source
stringlengths
61
181
87442ab14498-0
Source code for langchain.vectorstores.annoy from __future__ import annotations import os import pickle import uuid from configparser import ConfigParser from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple import numpy as np from langchain.docstore.base import Docstore from ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
87442ab14498-1
self.embedding_function = embedding_function self.index = index self.metric = metric self.docstore = docstore self.index_to_docstore_id = index_to_docstore_id @property def embeddings(self) -> Optional[Embeddings]: # TODO: Accept embedding object directly return N...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
87442ab14498-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. search_k: inspect up to search_k nodes which defaults to n_trees * n if not provided Returns: List of ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
87442ab14498-3
Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. search_k: inspect up to search_k nodes which defaults to n_trees * n if not provided Returns: List of Documents most similar to the query and score ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
87442ab14498-4
to n_trees * n if not provided Returns: List of Documents most similar to the embedding. """ docs_and_scores = self.similarity_search_with_score_by_index( docstore_index, k, search_k ) return [doc for doc, _ in docs_and_scores] [docs] def similarity_sea...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
87442ab14498-5
lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults to 0.5. Returns: List of Documents selected by maximal ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
87442ab14498-6
Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. fetch_k: Number of Documents to fetch to pass to MMR algorithm. lambda_mult: Number between 0 and 1 that determines the degree of diversity among th...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
87442ab14498-7
index.build(trees, n_jobs=n_jobs) documents = [] for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} documents.append(Document(page_content=text, metadata=metadata)) index_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))} docs...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
87442ab14498-8
.. code-block:: python from langchain.vectorstores import Annoy from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() index = Annoy.from_texts(texts, embeddings) """ embeddings = embedding.embed_documents(texts) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
87442ab14498-9
embeddings = OpenAIEmbeddings() text_embeddings = embeddings.embed_documents(texts) text_embedding_pairs = list(zip(texts, text_embeddings)) db = Annoy.from_embeddings(text_embedding_pairs, embeddings) """ texts = [t[0] for t in text_embeddings] em...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
87442ab14498-10
Args: folder_path: folder path to load index, docstore, and index_to_docstore_id from. embeddings: Embeddings to use when generating queries. """ path = Path(folder_path) # load index separately since it is not picklable annoy = dependable_annoy_im...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
a051b217fef7-0
Source code for langchain.vectorstores.vectara from __future__ import annotations import json import logging import os from hashlib import md5 from typing import Any, Iterable, List, Optional, Tuple, Type import requests from langchain.pydantic_v1 import Field from langchain.schema import Document from langchain.schema...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
a051b217fef7-1
or self._vectara_corpus_id is None or self._vectara_api_key is None ): logger.warning( "Can't find Vectara credentials, customer_id or corpus_id in " "environment." ) else: logger.debug(f"Using corpus id {self._vectara_corpu...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
a051b217fef7-2
headers=self._get_post_headers(), timeout=self.vectara_api_timeout, ) if response.status_code != 200: logger.error( f"Delete request failed for doc_id = {doc_id} with status code " f"{response.status_code}, reason {response.reason}, text " ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
a051b217fef7-3
pre-processing and chunking occurs internally in an optimal way This method provides a way to use that API in LangChain Args: files_list: Iterable of strings, each representing a local file path. Files could be text, HTML, PDF, markdown, doc/docx, ppt/pptx, etc. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
a051b217fef7-4
doc_ids.append(doc_id) else: logger.info(f"Error indexing file {file}: {response.json()}") return doc_ids [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, doc_metadata: Optional[dict] = None, **kwargs...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
a051b217fef7-5
], } success_str = self._index_doc(doc) if success_str == "E_ALREADY_EXISTS": self._delete_doc(doc_id) self._index_doc(doc) elif success_str == "E_NO_PERMISSIONS": print( """No permissions to add document to Vectara. Ch...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
a051b217fef7-6
""" data = json.dumps( { "query": [ { "query": query, "start": 0, "num_results": k, "context_config": { "sentences_before": n_sentence_conte...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
a051b217fef7-7
doc_num = x["documentIndex"] doc_md = {m["name"]: m["value"] for m in documents[doc_num]["metadata"]} md.update(doc_md) metadatas.append(md) docs_with_score = [ ( Document( page_content=x["text"], metadata=md...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
a051b217fef7-8
n_sentence_context=n_sentence_context, **kwargs, ) return [doc for doc, _ in docs_and_scores] [docs] @classmethod def from_texts( cls: Type[Vectara], texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
a051b217fef7-9
**kwargs: Any, ) -> Vectara: """Construct Vectara wrapper from raw documents. This is intended to be a quick way to get started. Example: .. code-block:: python from langchain.vectorstores import Vectara vectara = Vectara.from_files( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
a051b217fef7-10
filter: Dictionary of argument(s) to filter on metadata. For example a filter can be "doc.rating > 3.0 and part.lang = 'deu'"} see https://docs.vectara.com/docs/search-apis/sql/filter-overview for more details. n_sentence_context: number of sentences before/after the matching...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
ff1e17f1d826-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.schema import Document from langchain.schema.embeddings import Embeddings from langchain.schema.vectorstore impor...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html
ff1e17f1d826-1
""" endpoint: str 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", ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html
ff1e17f1d826-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
ff1e17f1d826-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
ff1e17f1d826-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
ff1e17f1d826-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
ff1e17f1d826-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
ff1e17f1d826-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
ff1e17f1d826-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
96331df04095-0
Source code for langchain.vectorstores.nucliadb import os from typing import Any, Dict, Iterable, List, Optional, Type from langchain.schema.document import Document from langchain.schema.embeddings import Embeddings from langchain.schema.vectorstore import VST, VectorStore FIELD_TYPES = { "f": "files", "t": "t...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html
96331df04095-1
if not backend: backend = "http://localhost:8080" self._config["BACKEND"] = f"{backend}/api/v1" self._config["TOKEN"] = None NucliaAuth().nucliadb(url=backend) NucliaAuth().kb(url=self.kb_url, interactive=False) else: self._config["BACK...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html
96331df04095-2
) ids.append(id) return ids [docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: if not ids: return None from nuclia.sdk import NucliaResource factory = NucliaResource() results: List[bool] = [] for id in id...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html
96331df04095-3
"metadata": { "extra": getattr( getattr(resource, "extra", {}), "metadata", None ), "value": value, }, "order": paragraph.order, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/nucliadb.html
73a052eb2561-0
Source code for langchain.vectorstores.elasticsearch import logging import uuid from abc import ABC, abstractmethod from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Literal, Optional, Tuple, Union, ) from langchain.docstore.document import Document from la...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-1
Returns: Dict: The Elasticsearch query body. """ [docs] @abstractmethod def index( self, dims_length: Union[int, None], vector_query_field: str, similarity: Union[DistanceStrategy, None], ) -> Dict: """ Executes when the index is created. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-2
[docs] def __init__( self, query_model_id: Optional[str] = None, hybrid: Optional[bool] = False, ): self.query_model_id = query_model_id self.hybrid = hybrid [docs] def query( self, query_vector: Union[List[float], None], query: Union[str, None],...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-3
if self.hybrid: return { "knn": knn, "query": { "bool": { "must": [ { "match": { text_field: { "...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-4
query: Union[str, None], k: int, fetch_k: int, vector_query_field: str, text_field: str, filter: Union[List[dict], None], similarity: Union[DistanceStrategy, None], ) -> Dict: if similarity is DistanceStrategy.COSINE: similarityAlgo = ( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-5
return { "mappings": { "properties": { vector_query_field: { "type": "dense_vector", "dims": dims_length, "index": False, }, } } } [docs]class S...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-6
if self.model_id: client.ingest.put_pipeline( id=self._get_pipeline_name(), description="Embedding pipeline for langchain vectorstore", processors=[ { "inference": { "model_id": self.model...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-7
es_url: URL of the Elasticsearch instance to connect to. cloud_id: Cloud ID of the Elasticsearch instance to connect to. es_user: Username to use when connecting to Elasticsearch. es_password: Password to use when connecting to Elasticsearch. es_api_key: API key to use when connecting to...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-8
from langchain.embeddings.openai import OpenAIEmbeddings from elasticsearch import Elasticsearch es_connection = Elasticsearch("http://localhost:9200") vectorstore = ElasticsearchStore( embedding=OpenAIEmbeddings(), index_name="langchain-demo", ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-9
[docs] def __init__( self, index_name: str, *, embedding: Optional[Embeddings] = None, es_connection: Optional["Elasticsearch"] = None, es_url: Optional[str] = None, es_cloud_id: Optional[str] = None, es_user: Optional[str] = None, es_api_key: O...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-10
or valid credentials for creating a new connection.""" ) [docs] @staticmethod def get_user_agent() -> str: from langchain import __version__ return f"langchain-py-vs/{__version__}" [docs] @staticmethod def connect_to_elasticsearch( *, es_url: Optional[str] = Non...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-11
raise e return es_client @property def embeddings(self) -> Optional[Embeddings]: return self.embedding [docs] def similarity_search( self, query: str, k: int = 4, filter: Optional[List[dict]] = None, **kwargs: Any, ) -> List[Document]: """Re...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-12
self, embedding: List[float], k: int = 4, filter: Optional[List[Dict]] = None, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return Elasticsearch documents most similar to query, along with scores. Args: embedding: Embedding to look up documents sim...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-13
custom_query: Function to modify the Elasticsearch query body before it is sent to Elasticsearch. Returns: List of Documents most similar to the query and score for each """ if fields is None: fields = ["metadata"] if self.query_field not ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-14
**kwargs: Any, ) -> Optional[bool]: """Delete documents from the Elasticsearch index. Args: ids: List of ids of documents to delete. refresh_indices: Whether to refresh the index after deleting documents. Defaults to True. """ try: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-15
""" if self.client.indices.exists(index=index_name): logger.debug(f"Index {index_name} already exists. Skipping creation.") else: if dims_length is None and self.strategy.require_inference(): raise ValueError( "Cannot create index without speci...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-16
refresh_indices: Whether to refresh the Elasticsearch indices after adding the texts. create_index_if_not_exists: Whether to create the Elasticsearch index if it doesn't already exist. *bulk_kwargs: Additional arguments to pass ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-17
"_id": ids[i], } ) else: # the search_type doesn't require inference, so we don't need to # embed the texts. if create_index_if_not_exists: self._create_index_if_not_exists(index_name=self.index_name) for i, text...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-18
bulk_kwargs: Optional[Dict] = None, **kwargs: Any, ) -> "ElasticsearchStore": """Construct ElasticsearchStore wrapper from raw documents. Example: .. code-block:: python from langchain.vectorstores import ElasticsearchStore from langchain.embedding...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-19
""" elasticsearchStore = ElasticsearchStore._create_cls_from_kwargs( embedding=embedding, **kwargs ) # Encode the provided texts and add them to the newly created index. elasticsearchStore.add_texts( texts, metadatas=metadatas, bulk_kwargs=bulk_kwargs ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-20
es_api_key=es_api_key, strategy=strategy, distance_strategy=distance_strategy, **optional_args, ) [docs] @classmethod def from_documents( cls, documents: List[Document], embedding: Optional[Embeddings] = None, bulk_kwargs: Optional[Dict]...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-21
bulk_kwargs: Optional. Additional arguments to pass to Elasticsearch bulk. """ elasticsearchStore = ElasticsearchStore._create_cls_from_kwargs( embedding=embedding, **kwargs ) # Encode the provided texts and add them to the newly created index. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
73a052eb2561-22
[docs] @staticmethod def SparseVectorRetrievalStrategy( model_id: Optional[str] = None, ) -> "SparseRetrievalStrategy": """Used to perform sparse vector search via text_expansion. Used for when you want to use ELSER model to perform document search. At build index time, this s...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elasticsearch.html
02d619e0dcc0-0
Source code for langchain.vectorstores.pinecone from __future__ import annotations import logging import uuid import warnings from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Tuple, Union import numpy as np from langchain.docstore.document import Document from langchain.schema.embeddings impor...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
02d619e0dcc0-1
raise ImportError( "Could not import pinecone python package. " "Please install it with `pip install pinecone-client`." ) if not isinstance(embedding, Embeddings): warnings.warn( "Passing in `embedding` as a Callable is deprecated. Please p...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
02d619e0dcc0-2
namespace: Optional[str] = None, batch_size: int = 32, embedding_chunk_size: int = 1000, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Upsert optimization is done by chunking the embeddings and upserting them. This...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
02d619e0dcc0-3
for i in range(0, len(texts), embedding_chunk_size): chunk_texts = texts[i : i + embedding_chunk_size] chunk_ids = ids[i : i + embedding_chunk_size] chunk_metadatas = metadatas[i : i + embedding_chunk_size] embeddings = self._embed_documents(chunk_texts) async...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
02d619e0dcc0-4
embedding: List[float], *, k: int = 4, filter: Optional[dict] = None, namespace: Optional[str] = None, ) -> List[Tuple[Document, float]]: """Return pinecone documents most similar to embedding, along with scores.""" if namespace is None: namespace = self._...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
02d619e0dcc0-5
""" docs_and_scores = self.similarity_search_with_score( query, k=k, filter=filter, namespace=namespace, **kwargs ) return [doc for doc, _ in docs_and_scores] def _select_relevance_score_fn(self) -> Callable[[float], float]: """ The 'correct' relevance function ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
02d619e0dcc0-6
Args: embedding: Embedding to look up documents similar to. k: Number of Documents to return. Defaults to 4. fetch_k: Number of Documents to fetch to pass to MMR algorithm. lambda_mult: Number between 0 and 1 that determines the degree of diversity...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
02d619e0dcc0-7
) -> 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 of Documents to ret...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
02d619e0dcc0-8
elif len(indexes) == 0: raise ValueError( "No active indexes found in your Pinecone project, " "are you sure you're using the right Pinecone API key and Environment? " "Please double check your Pinecone dashboard." ) else: raise...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
02d619e0dcc0-9
# in your Pinecone console pinecone.init(api_key="***", environment="...") embeddings = OpenAIEmbeddings() pinecone = Pinecone.from_texts( texts, embeddings, index_name="langchain-demo" ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
02d619e0dcc0-10
filter: Dictionary of conditions to filter vectors to delete. """ if namespace is None: namespace = self._namespace if delete_all: self._index.delete(delete_all=True, namespace=namespace, **kwargs) elif ids is not None: chunk_size = 1000 fo...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
c1df46f64aa8-0
Source code for langchain.vectorstores.meilisearch 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.schema.embeddings import Embeddings from langchain.schema.vectorstore impor...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html
c1df46f64aa8-1
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-python/. See the following documentation for how to run a Me...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html
c1df46f64aa8-2
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]] = None, **kwargs: An...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html
c1df46f64aa8-3
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 the query. Args: query (str): Query text for whic...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html
c1df46f64aa8-4
""" _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_vector_with_scores( self, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html
c1df46f64aa8-5
**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. filter (Optional[Dict[str, str]]): F...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html
c1df46f64aa8-6
Example: .. code-block:: python from langchain.vectorstores import Meilisearch from langchain.embeddings import OpenAIEmbeddings import meilisearch # The environment should be the one specified next to the API key # in your Meil...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/meilisearch.html
478f8a1e86ab-0
Source code for langchain.vectorstores.awadb 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 langchain.schema.embeddings import Embeddings from l...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-1
"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 = awadb.Client(log_and_data_dir) else: self.awadb_client = awadb.Clie...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-2
""" 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].embed_documents( list(texts) ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-3
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_price": 4.20}` `price` is the metadata field, means range filter(4.20<='price'<=15.66). kwargs: Any possible extend pa...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-4
Args: query: Text query. k: The k most similar documents to the text query. text_in_page_content: Filter by the text in page_content of Document. meta_filter: Filter by metadata. Defaults to None. kwargs: Any possible extend parameters in the future. R...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-5
[docs] def similarity_search_by_vector( self, embedding: Optional[List[float]] = None, k: int = DEFAULT_TOPN, text_in_page_content: Optional[str] = None, meta_filter: Optional[dict] = None, not_include_fields_in_metadata: Optional[Set[str]] = None, **kwargs: An...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-6
if item_key in not_include_fields_in_metadata: continue meta_data[item_key] = item_detail[item_key] results.append(Document(page_content=content, metadata=meta_data)) return results [docs] def max_marginal_relevance_search( self, query: str,...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-7
else: from awadb import AwaEmbedding embedding = AwaEmbedding().Embedding(query) if embedding.__len__() == 0: return [] results = self.max_marginal_relevance_search_by_vector( embedding, k, fetch_k, lambda_mult=lambda_mu...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-8
""" if self.awadb_client is None: raise ValueError("AwaDB client is None!!!") results: List[Document] = [] if embedding is None: return results not_include_fields: set = {"_id", "score"} retrieved_docs = self.similarity_search_by_vector( embedd...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-9
limit: The number of documents to return. Defaults to 5. Optional. Returns: Documents which satisfy the input conditions. """ if self.awadb_client is None: raise ValueError("AwaDB client is None!!!") docs_detail = self.awadb_client.Get( ids=ids, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-10
return ret ret = self.awadb_client.Delete(ids) return ret [docs] def update( self, ids: List[str], texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> List[str]: """Update the documents which have the specified ids. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-11
return ret [docs] def list_tables( self, **kwargs: Any, ) -> List[str]: """List all the tables created by the client.""" if self.awadb_client is None: return [] return self.awadb_client.ListAllTables() [docs] def get_current_table( self, **kw...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
478f8a1e86ab-12
log_and_data_dir=log_and_data_dir, client=client, ) awadb_client.add_texts(texts=texts, metadatas=metadatas) return awadb_client [docs] @classmethod def from_documents( cls: Type[AwaDB], documents: List[Document], embedding: Optional[Embeddings] = None,...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
f42e419738b7-0
Source code for langchain.vectorstores.pgembedding from __future__ import annotations import logging import uuid from typing import Any, Dict, Iterable, List, Optional, Tuple, Type import sqlalchemy from sqlalchemy import func from sqlalchemy.dialects.postgresql import JSON, UUID from sqlalchemy.orm import Session, dec...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
f42e419738b7-1
Returns [Collection, bool] where the bool is True if the collection was created. """ created = False collection = cls.get_by_name(session, name) if collection: return collection, created collection = cls(name=name, cmetadata=cmetadata) session.add(collection) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
f42e419738b7-2
- NOTE: This is not the name of the table, but the name of the collection. The tables will be created when initializing the store (if not exists) So, make sure the user has the right permissions to create tables. - `distance_strategy` is the distance strategy to use. (default: EUCLIDEAN) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
f42e419738b7-3
[docs] def create_hnsw_extension(self) -> None: try: with Session(self._conn) as session: statement = sqlalchemy.text("CREATE EXTENSION IF NOT EXISTS embedding") session.execute(statement) session.commit() except Exception as e: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
f42e419738b7-4
try: with Session(self._conn) as session: # Create the HNSW index session.execute(create_index_query) session.commit() print("HNSW extension and index created successfully.") except Exception as e: print(f"Failed to create HNSW ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
f42e419738b7-5
pre_delete_collection=pre_delete_collection, ) store.add_embeddings( texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs ) return store [docs] def add_embeddings( self, texts: List[str], embeddings: List[List[float]], ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
f42e419738b7-6
embedding_store = EmbeddingStore( embedding=embedding, document=text, cmetadata=metadata, custom_id=id, ) collection.embeddings.append(embedding_store) session.add(embedding_store) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
f42e419738b7-7
if filter is not None: filter_clauses = [] for key, value in filter.items(): IN = "in" if isinstance(value, dict) and IN in map(str.lower, value): value_case_insensitive = { k.lower(): v for k, v ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
f42e419738b7-8
metadata=result.EmbeddingStore.cmetadata, ), result.distance if self.embedding_function is not None else None, ) for result in results ] return docs [docs] def similarity_search_by_vector( self, embedding: List[float], k:...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
f42e419738b7-9
ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any, ) -> PGEmbedding: texts = [t[0] for t in text_embeddings] embeddings = [t[1] for t in text_embeddings] return cls._initialize_from_embeddings( texts, embeddings, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
f42e419738b7-10
def from_documents( cls: Type[PGEmbedding], documents: List[Document], embedding: Embeddings, collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, ids: Optional[List[str]] = None, pre_delete_collection: bool = False, **kwargs: Any, ) -> PGEmbedding: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html