id
stringlengths
14
16
text
stringlengths
13
2.7k
source
stringlengths
57
178
c16601bbdd12-9
fetch_k=fetch_k, **kwargs, ) return docs [docs] async def asimilarity_search_with_score( self, query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any, ) -> List[Tuple[Document, float]]: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-10
k: Number of Documents to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. fetch_k: (Optional[int]) Number of Documents to fetch before filtering. Defaults to 20. Returns: List of Documents most similar to t...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-11
[docs] def similarity_search( self, query: str, k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any, ) -> List[Document]: """Return docs most similar to query. Args: query: Text to look up documents simi...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-12
Returns: List of Documents most similar to the query. """ docs_and_scores = await self.asimilarity_search_with_score( query, k, filter=filter, fetch_k=fetch_k, **kwargs ) return [doc for doc, _ in docs_and_scores] [docs] def max_marginal_relevance_search_with_s...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-13
for i in indices[0]: if i == -1: # This happens when not enough docs are returned. continue _id = self.index_to_docstore_id[i] doc = self.docstore.search(_id) if not isinstance(doc, Document): rai...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-14
[docs] async def amax_marginal_relevance_search_with_score_by_vector( self, embedding: List[float], *, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, Any]] = None, ) -> List[Tuple[Document, float]]: """Return doc...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-15
k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversi...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-16
among selected documents. 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 before filtering to pass to MMR algorithm. lambda_mult: Number between...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-17
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. """ embedding = self._embed_query(query) do...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-18
embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, filter=filter, **kwargs, ) return docs [docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: """Delete by ID. These are the IDs in the vec...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-19
Add the target FAISS to the current one. Args: target: FAISS object you wish to merge into the current one Returns: None. """ if not isinstance(self.docstore, AddableMixin): raise ValueError("Cannot merge with this type of docstore") # Numerica...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-20
if distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: index = faiss.IndexFlatIP(len(embeddings[0])) else: # Default to L2, currently other metric types not initialized. index = faiss.IndexFlatL2(len(embeddings[0])) vecstore = cls( embedding, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-21
**kwargs, ) [docs] @classmethod async def afrom_texts( cls, texts: list[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> FAISS: """Construct FAISS wrapper from raw document...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-22
3. Initializes the FAISS database This is intended to be a quick way to get started. Example: .. code-block:: python from langchain.vectorstores import FAISS from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-23
index_name: for saving with a specific index file name """ path = Path(folder_path) path.mkdir(exist_ok=True, parents=True) # save index separately since it is not picklable faiss = dependable_faiss_import() faiss.write_index( self.index, str(path / "{index_na...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-24
docstore, index_to_docstore_id = pickle.load(f) return cls(embeddings, index, docstore, index_to_docstore_id, **kwargs) [docs] def serialize_to_bytes(self) -> bytes: """Serialize FAISS index, docstore, and index_to_docstore_id to bytes.""" return pickle.dumps((self.index, self.docstore, self....
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-25
return self._euclidean_relevance_score_fn elif self.distance_strategy == DistanceStrategy.COSINE: return self._cosine_relevance_score_fn else: raise ValueError( "Unknown distance strategy, must be cosine, max_inner_product," " or euclidean" ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c16601bbdd12-26
**kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs and their similarity scores on a scale from 0 to 1.""" # Pop score threshold so that only relevancy scores, not raw scores, are # filtered. relevance_score_fn = self._select_relevance_score_fn() if relevance_sco...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
c26e5ec88402-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
c26e5ec88402-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
c26e5ec88402-2
data=json.dumps(body), verify=True, 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"{resp...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
c26e5ec88402-3
""" Vectara provides a way to add documents directly via our API where 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. ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
c26e5ec88402-4
doc_id = response.json()["document"]["documentId"] 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]] = ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
c26e5ec88402-5
for text, md in zip(texts, metadatas) ], } 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 permissio...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
c26e5ec88402-6
to add, defaults to 2 Returns: List of Documents most similar to the query and score for each. """ data = json.dumps( { "query": [ { "query": query, "start": 0, "nu...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
c26e5ec88402-7
md = {m["name"]: m["value"] for m in x["metadata"]} 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( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
c26e5ec88402-8
k=k, lambda_val=lambda_val, filter=filter, score_threshold=None, n_sentence_context=n_sentence_context, **kwargs, ) return [doc for doc, _ in docs_and_scores] [docs] @classmethod def from_texts( cls: Type[Vectara], texts:...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
c26e5ec88402-9
files: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> Vectara: """Construct Vectara wrapper from raw documents. This is intended to be a quick way to get started. Example: .. code-block:: pyth...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
c26e5ec88402-10
lambda_val: lexical match parameter for hybrid search. 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_...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
cc4a876c20c3-0
Source code for langchain.vectorstores.vearch from __future__ import annotations import os import time import uuid from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type import numpy as np from langchain.docstore.document import Document from langchain.schema.embeddings import Embeddings fro...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
cc4a876c20c3-1
self.using_db_name = db_name self.url = path_or_url self.vearch = vearch_cluster.VearchCluster(path_or_url) else: if path_or_url is None: metadata_path = os.getcwd().replace("\\", "/") else: metadata_path = path_or_url i...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
cc4a876c20c3-2
embedding=embedding, metadatas=metadatas, path_or_url=path_or_url, table_name=table_name, db_name=db_name, flag=flag, **kwargs, ) [docs] @classmethod def from_texts( cls: Type[Vearch], texts: List[str], embedd...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
cc4a876c20c3-3
engine_info = { "index_size": 10000, "retrieval_type": "IVFPQ", "retrieval_param": {"ncentroids": 2048, "nsubvector": 32}, } fields = [ vearch.GammaFieldInfo(fi["field"], type_dict[fi["type"]]) for fi in field_list ] vector_fiel...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
cc4a876c20c3-4
"text": { "type": "string", }, "metadata": { "type": "string", }, "text_embedding": { "type": "vector", "index": True, "dimension": dim, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
cc4a876c20c3-5
for text, metadata, embed in zip(texts, metadatas, embeddings): profiles: dict[str, Any] = {} profiles["text"] = text profiles["metadata"] = metadata["source"] embed_np = np.array(embed) profiles["text_embedding"] = { ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
cc4a876c20c3-6
docid = self.vearch.add(doc_items) t_time = 0 while len(docid) != len(embeddings): time.sleep(0.5) if t_time > 6: break t_time += 1 self.vearch.dump() return docid def _load(se...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
cc4a876c20c3-7
k: int = DEFAULT_TOPN, **kwargs: Any, ) -> List[Document]: """ Return docs most similar to query. """ if self.embedding_func is None: raise ValueError("embedding_func is None!!!") embeddings = self.embedding_func.embed_query(query) docs = self.simi...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
cc4a876c20c3-8
"feature": embed / np.linalg.norm(embed), } ], "fields": [], "is_brute_search": 1, "retrieval_param": {"metric_type": "InnerProduct", "nprobe": 20}, "topn": k, } query_result = self.vearch.search(...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
cc4a876c20c3-9
if self.flag: query_data = { "query": { "sum": [ { "field": "text_embedding", "feature": (embed / np.linalg.norm(embed)).tolist(), } ], ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
cc4a876c20c3-10
tmp_res = (Document(page_content=content, metadata=meta_data), score) results.append(tmp_res) return results def _similarity_search_with_relevance_scores( self, query: str, k: int = 4, **kwargs: Any, ) -> List[Tuple[Document, float]]: return self.simil...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
cc4a876c20c3-11
Returns: Documents which satisfy the input conditions. """ results: Dict[str, Document] = {} if ids is None or ids.__len__() == 0: return results if self.flag: query_data = {"query": {"ids": ids}} docs_detail = self.vearch.mget_by_ids( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vearch.html
682eef8aaa20-0
Source code for langchain.vectorstores.tair 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.schema.embeddings import Embeddings from langchain.schema.vectorstore import Vector...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
682eef8aaa20-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
682eef8aaa20-2
**{ "TEXT": text, self.content_key: text, self.metadata_key: json.dumps(metadata), }, ) else: pipeline.tvs_hset( self.index_name, key, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
682eef8aaa20-3
cls: Type[Tair], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, index_name: str = "langchain", content_key: str = "content", metadata_key: str = "metadata", **kwargs: Any, ) -> Tair: try: from tair import t...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
682eef8aaa20-4
metadata_key=metadata_key, search_params=search_params, **kwargs, ) except ValueError as e: raise ValueError(f"tair failed to connect: {e}") # Create embeddings for documents embeddings = embedding.embed_documents(texts) tair_vector...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
682eef8aaa20-5
except ImportError: raise ValueError( "Could not import tair python package. " "Please install it with `pip install tair`." ) url = get_from_dict_or_env(kwargs, "tair_url", "TAIR_URL") try: if "tair_url" in kwargs: kwarg...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
7106ac669f38-0
Source code for langchain.vectorstores.atlas 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.schema.embeddings import Embeddings from langchain.schema.vectorstore impor...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
7106ac669f38-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
7106ac669f38-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
7106ac669f38-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) ] ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
7106ac669f38-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
7106ac669f38-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 ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
7106ac669f38-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
7106ac669f38-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
f83b20163cfe-0
Source code for langchain.vectorstores.tencentvectordb """Wrapper around the Tencent vector database.""" from __future__ import annotations import json import logging import time from typing import Any, Dict, Iterable, List, Optional, Tuple import numpy as np from langchain.docstore.document import Document from langch...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html
f83b20163cfe-1
index_type: str = "HNSW", metric_type: str = "L2", params: Optional[Dict] = None, ): self.dimension = dimension self.shard = shard self.replicas = replicas self.index_type = index_type self.metric_type = metric_type self.params = params [docs]class Ten...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html
f83b20163cfe-2
for db in db_list: if database_name == db.database_name: db_exist = True break if db_exist: self.database = self.vdb_client.database(database_name) else: self.database = self.vdb_client.create_database(database_name) try: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html
f83b20163cfe-3
self.field_id, enum.FieldType.String, enum.IndexType.PRIMARY_KEY ), vdb_index.VectorIndex( self.field_vector, self.index_params.dimension, index_type, metric_type, params, ), vdb_index.FilterI...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html
f83b20163cfe-4
except NotImplementedError: embeddings = [embedding.embed_query(texts[0])] dimension = len(embeddings[0]) if index_params is None: index_params = IndexParams(dimension=dimension) else: index_params.dimension = dimension vector_db = cls( emb...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html
f83b20163cfe-5
metadata = json.dumps(metadatas[id]) doc = self.document.Document( id="{}-{}-{}".format(time.time_ns(), hash(texts[id]), id), vector=embeddings[id], text=texts[id], metadata=metadata, ) docs.a...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html
f83b20163cfe-6
) return res [docs] def similarity_search_by_vector( self, embedding: List[float], k: int = 4, param: Optional[dict] = None, expr: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any, ) -> List[Document]: """Perform a similari...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html
f83b20163cfe-7
for result in res[0]: meta = result.get(self.field_metadata) if meta is not None: meta = json.loads(meta) doc = Document(page_content=result.get(self.field_text), metadata=meta) pair = (doc, result.get("score", 0.0)) ret.append(pair) re...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html
f83b20163cfe-8
"""Perform a search and return results that are reordered by MMR.""" filter = None if expr is None else self.document.Filter(expr) ef = 10 if param is None else param.get("ef", 10) res: List[List[Dict]] = self.collection.search( vectors=[embedding], filter=filter, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tencentvectordb.html
0aba36bff0d0-0
Source code for langchain.vectorstores.neo4j_vector from __future__ import annotations import enum import logging import os import uuid from typing import ( Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, ) from langchain.docstore.document import Document from langchain.schem...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-1
"UNWIND nodes AS n " "RETURN n.node AS node, (n.score / max) AS score " # We use 0 as min "} " "WITH node, max(score) AS score ORDER BY score DESC LIMIT $k " # dedup ), } return type_to_query_map[search_type] [docs]def check_if_not_null(props: List[str], values: Lis...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-2
Example: .. code-block:: python from langchain.vectorstores.neo4j_vector import Neo4jVector from langchain.embeddings.openai import OpenAIEmbeddings url="bolt://localhost:7687" username="neo4j" password="pleaseletmein" embeddings = OpenAIEm...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-3
# Allow only cosine and euclidean distance strategies if distance_strategy not in [ DistanceStrategy.EUCLIDEAN_DISTANCE, DistanceStrategy.COSINE, ]: raise ValueError( "distance_strategy must be either 'EUCLIDEAN_DISTANCE' or 'COSINE'" ) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-4
], [index_name, node_label, embedding_node_property, text_node_property], ) self.embedding = embedding self._distance_strategy = distance_strategy self.index_name = index_name self.keyword_index_name = keyword_index_name self.node_label = node_label se...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-5
""" from neo4j.exceptions import CypherSyntaxError params = params or {} with self._driver.session(database=self._database) as session: try: data = session.run(query, params) return [r.data() for r in data] except CypherSyntaxError as e: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-6
If the index doesn't exist, `None` is returned. Returns: int or None: The embedding dimension of the existing index if found. """ index_information = self.query( "SHOW INDEXES YIELD name, type, labelsOrTypes, properties, options " "WHERE type = 'VECTOR' AND (n...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-7
"SHOW INDEXES YIELD name, type, labelsOrTypes, properties, options " "WHERE type = 'FULLTEXT' AND (name = $keyword_index_name " "OR (labelsOrTypes = [$node_label] AND " "properties = $text_node_property)) " "RETURN name, labelsOrTypes, properties, options ", p...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-8
} self.query(index_query, params=parameters) [docs] def create_new_keyword_index(self, text_node_properties: List[str] = []) -> None: """ This method constructs a Cypher query and executes it to create a new full text index in Neo4j. """ node_props = text_node_properti...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-9
if not embedding_dimension: store.create_new_index() # If the index already exists, check if embedding dimensions match elif not store.embedding_dimension == embedding_dimension: raise ValueError( f"Index with name {store.index_name} already exists." ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-10
"""Add embeddings to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. embeddings: List of list of embedding vectors. metadatas: List of metadatas associated with the texts. kwargs: vectorstore specific parameters """ if ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-11
"""Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. kwargs: vectorstore specific parameters Returns: List of ids f...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-12
docs = self.similarity_search_with_score_by_vector( embedding=embedding, k=k, query=query ) return docs [docs] def similarity_search_with_score_by_vector( self, embedding: List[float], k: int = 4, **kwargs: Any ) -> List[Tuple[Document, float]]: """ Perform a s...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-13
"embedding": embedding, "keyword_index": self.keyword_index_name, "query": kwargs["query"], } results = self.query(read_query, params=parameters) docs = [ ( Document( page_content=result["text"], metadata...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-14
Neo4j credentials are required in the form of `url`, `username`, and `password` and optional `database` parameters. """ embeddings = embedding.embed_documents(list(texts)) return cls.__from( texts, embeddings, embedding, metadatas=metadatas...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-15
return cls.__from( texts, embeddings, embedding, metadatas=metadatas, ids=ids, distance_strategy=distance_strategy, pre_delete_collection=pre_delete_collection, **kwargs, ) [docs] @classmethod def from_existin...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-16
raise ValueError( "The provided embedding function and vector index " "dimensions do not match.\n" f"Embedding function dimension: {store.embedding_dimension}\n" f"Vector index dimension: {embedding_dimension}" ) if search_type == Searc...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-17
ids=ids, **kwargs, ) [docs] @classmethod def from_existing_graph( cls: Type[Neo4jVector], embedding: Embeddings, node_label: str, embedding_node_property: str, text_node_properties: List[str], *, keyword_index_name: Optional[str] = "keyw...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-18
if not retrieval_query: retrieval_query = ( f"RETURN reduce(str='', k IN {text_node_properties} |" " str + '\\n' + k + ': ' + coalesce(node[k], '')) AS text, " "node {.*, `" + embedding_node_property + "`: Null, id: Null, " ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-19
if not fts_node_label: store.create_new_keyword_index(text_node_properties) else: # Validate that FTS and Vector index use the same information if not fts_node_label == store.node_label: raise ValueError( "Vector and keyword index ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
0aba36bff0d0-20
def _select_relevance_score_fn(self) -> Callable[[float], float]: """ The 'correct' relevance function may differ depending on a few things, including: - the distance / similarity metric used by the VectorStore - the scale of your embeddings (OpenAI's are unit normed. Many others...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html
41e880cdf43f-0
Source code for langchain.vectorstores.azuresearch from __future__ import annotations import base64 import json import logging import uuid from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, ) import numpy as np from langchain.callbacks.man...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-1
def _get_search_client( endpoint: str, key: str, index_name: str, semantic_configuration_name: Optional[str] = None, fields: Optional[List[SearchField]] = None, vector_search: Optional[VectorSearch] = None, semantic_settings: Optional[SemanticSettings] = None, scoring_profiles: Optional[...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-2
# Fields configuration if fields is not None: # Check mandatory fields fields_types = {f.name: f.type for f in fields} mandatory_fields = {df.name: df.type for df in default_fields} # Check for missing keys missing_fields = { key: manda...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-3
"metric": "cosine", }, ) ] ) # Create the semantic settings with the configuration if semantic_settings is None and semantic_configuration_name is not None: semantic_settings = SemanticSettings( configura...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-4
default_scoring_profile: Optional[str] = None, **kwargs: Any, ): from azure.search.documents.indexes.models import ( SearchableField, SearchField, SearchFieldDataType, SimpleField, ) """Initialize with necessary components.""" #...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-5
self.fields = fields if fields else default_fields @property def embeddings(self) -> Optional[Embeddings]: # TODO: Support embedding object directly return None [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-6
# Check if all documents were successfully uploaded if not all([r.succeeded for r in response]): raise Exception(response) # Reset data data = [] # Considering case where data is an exact multiple of batch-size entries if len(data) == 0...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-7
) [docs] def vector_search(self, query: str, k: int = 4, **kwargs: Any) -> 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 retur...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-8
if FIELDS_METADATA in result else { k: v for k, v in result.items() if k != FIELDS_CONTENT_VECTOR }, ), float(result["@search.score"]), ) for result in results ] return docs [docs] ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-9
k=k, fields=FIELDS_CONTENT_VECTOR, ) ], filter=filters, top=k, ) # Convert results to Document objects docs = [ ( Document( page_content=result.pop(FIELDS_CONTENT), ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-10
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 similar to the query text. """ docs_and_scores = self.semantic_hybrid_se...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-11
semantic_answers = results.get_answers() or [] semantic_answers_dict: Dict = {} for semantic_answer in semantic_answers: semantic_answers_dict[semantic_answer.key] = { "text": semantic_answer.text, "highlights": semantic_answer.highlights, } ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-12
**kwargs: Any, ) -> AzureSearch: # Creating a new Azure Search instance azure_search = cls( azure_search_endpoint, azure_search_key, index_name, embedding.embed_query, ) azure_search.add_texts(texts, metadatas, **kwargs) return ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
41e880cdf43f-13
docs = self.vectorstore.hybrid_search(query, k=self.k, **kwargs) elif self.search_type == "semantic_hybrid": docs = self.vectorstore.semantic_hybrid_search(query, k=self.k, **kwargs) else: raise ValueError(f"search_type of {self.search_type} not allowed.") return docs ...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html
efb92b8561a3-0
Source code for langchain.vectorstores.lancedb from __future__ import annotations import uuid from typing import Any, Iterable, List, Optional from langchain.docstore.document import Document from langchain.schema.embeddings import Embeddings from langchain.schema.vectorstore import VectorStore [docs]class LanceDB(Vect...
lang/api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html