id
stringlengths
14
16
source
stringlengths
49
117
text
stringlengths
16
2.73k
824167dadd07-2
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
query_embeddings: Optional[List[List[float]]] = None, n_results: int = 4, where: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> List[Document]: """Query the chroma collection.""" try: import chromadb except ImportError: raise ValueError( ...
824167dadd07-3
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
# TODO: Handle the case where the user doesn't provide ids on the Collection if ids is None: ids = [str(uuid.uuid1()) for _ in texts] embeddings = None if self._embedding_function is not None: embeddings = self._embedding_function.embed_documents(list(texts)) self...
824167dadd07-4
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List of Documents most similar to the query vector. """ results = self.__query_collection( query_embeddings=embedding, n_results=k, where=filter ) return _results_to_docs(res...
824167dadd07-5
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
[docs] def max_marginal_relevance_search_by_vector( self, embedding: List[float], k: int = DEFAULT_K, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> List[Document]: """Return docs selected u...
824167dadd07-6
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
[docs] def max_marginal_relevance_search( self, query: str, k: int = DEFAULT_K, fetch_k: int = 20, lambda_mult: float = 0.5, filter: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal margi...
824167dadd07-7
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
"""Gets the collection. Args: include (Optional[List[str]]): List of fields to include from db. Defaults to None. """ if include is not None: return self._collection.get(include=include) else: return self._collection.get() [docs] def...
824167dadd07-8
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, persist_directory: Optional[str] = None, client_settings: Optional[chromadb.config.Settings] = None, client: Optional[chromadb.Client] = None, **kwargs: Any, ) -> Chroma: """Create a Chroma vectorstore from a raw docu...
824167dadd07-9
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html
persist_directory: Optional[str] = None, client_settings: Optional[chromadb.config.Settings] = None, client: Optional[chromadb.Client] = None, # Add this line **kwargs: Any, ) -> Chroma: """Create a Chroma vectorstore from a list of documents. If a persist_directory is speci...
2fc70cd48f6c-0
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
Source code for langchain.vectorstores.deeplake """Wrapper around Activeloop Deep Lake.""" from __future__ import annotations import logging import uuid from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple import numpy as np from langchain.docstore.document imp...
2fc70cd48f6c-1
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
nearest_indices: List, indices of nearest neighbors """ if data_vectors.shape[0] == 0: return [], [] # Calculate the distance between the query_vector and all data_vectors distances = distance_metric_map[distance_metric](query_embedding, data_vectors) nearest_indices = np.argsort(distances) ...
2fc70cd48f6c-2
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
vectorstore = DeepLake("langchain_store", embeddings.embed_query) """ _LANGCHAIN_DEFAULT_DEEPLAKE_PATH = "./deeplake/" def __init__( self, dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH, token: Optional[str] = None, embedding_function: Optional[Embeddings] = None, ...
2fc70cd48f6c-3
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
f"Deep Lake Dataset in {dataset_path} already exists, " f"loading from the storage" ) self.ds.summary() else: if "overwrite" in kwargs: del kwargs["overwrite"] self.ds = deeplake.empty( dataset_path, ...
2fc70cd48f6c-4
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
"""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]], optional): Optional list of IDs. Return...
2fc70cd48f6c-5
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
ingest().eval( batched, self.ds, num_workers=min(self.num_workers, len(batched) // max(self.num_workers, 1)), **kwargs, ) self.ds.commit(allow_empty=True) if self.verbose: self.ds.summary() return ids def _search_helper( ...
2fc70cd48f6c-6
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
Defaults to False. fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to 20. return_score: Whether to return the score. Defaults to False. Returns: List of Documents selected by the specified distance metric, if return_score T...
2fc70cd48f6c-7
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
lambda_mult=lambda_mult, ) view = view[indices] scores = [scores[i] for i in indices] docs = [ Document( page_content=el["text"].data()["value"], metadata=el["metadata"].data()["value"], ) for el ...
2fc70cd48f6c-8
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
[docs] def similarity_search_by_vector( self, embedding: List[float], k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs most similar to embedding vector. Args: embedding: Embedding to look up documents similar to. k: Number of Documents to return. Defau...
2fc70cd48f6c-9
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among ...
2fc70cd48f6c-10
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
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 the results with 0 corresponding to maximum diversity and 1 to minimum diversity. Defaults...
2fc70cd48f6c-11
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
- AWS S3 path of the form ``s3://bucketname/path/to/dataset``. Credentials are required in either the environment - Google Cloud Storage path of the form ``gcs://bucketname/path/to/dataset`` Credentials are required in either the environment ...
2fc70cd48f6c-12
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
filter (Optional[Dict[str, str]], optional): The filter to delete by. Defaults to None. delete_all (Optional[bool], optional): Whether to drop the dataset. Defaults to None. """ if delete_all: self.ds.delete(large_ok=True) return True ...
c0932f6b2a02-0
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
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 ...
c0932f6b2a02-1
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
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): return value.isoformat() return value [docs]class...
c0932f6b2a02-2
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
self._index_name = index_name self._embedding = embedding self._text_key = text_key self._query_attrs = [self._text_key] self._relevance_score_fn = relevance_score_fn self._by_text = by_text if attributes is not None: self._query_attrs.extend(attributes) [docs...
c0932f6b2a02-3
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
) -> 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. """ if self._by_text: ...
c0932f6b2a02-4
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
raise ValueError(f"Error during query: {result['errors']}") docs = [] for res in result["data"]["Get"][self._index_name]: text = res.pop(self._text_key) docs.append(Document(page_content=text, metadata=res)) return docs [docs] def similarity_search_by_vector( s...
c0932f6b2a02-5
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
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 the results with 0 c...
c0932f6b2a02-6
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
Returns: List of Documents selected by maximal marginal relevance. """ vector = {"vector": embedding} query_obj = self._client.query.get(self._index_name, self._query_attrs) if kwargs.get("where_filter"): query_obj = query_obj.with_where(kwargs.get("where_filter")...
c0932f6b2a02-7
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
query_obj.with_near_vector(vector) .with_limit(k) .with_additional("vector") .do() ) else: result = ( query_obj.with_near_text(content) .with_limit(k) .with_additional("vector") ...
c0932f6b2a02-8
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> Weaviate: """Construct Weaviate wrapper from raw documents. This is a user-friendly interface that: 1. Embeds documents. 2. Creates a new index for the embeddings in the Weaviate instance. 3. Adds...
c0932f6b2a02-9
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
# If the UUID of one of the objects already exists # then the existing objectwill be replaced by the new object. if "uuids" in kwargs: _id = kwargs["uuids"][i] else: _id = get_valid_uuid(uuid4()) # if an embedding st...
f41b6e1b9c30-0
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
Source code for langchain.vectorstores.typesense """Wrapper around Typesense vector search""" from __future__ import annotations import uuid from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings fro...
f41b6e1b9c30-1
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
text_key: str = "text", ): """Initialize with Typesense client.""" try: from typesense import Client except ImportError: raise ValueError( "Could not import typesense python package. " "Please install it with `pip install typesense`." ...
f41b6e1b9c30-2
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
{"name": "vec", "type": "float[]", "num_dim": num_dim}, {"name": f"{self._text_key}", "type": "string"}, {"name": ".*", "type": "auto"}, ] self._typesense_client.collections.create( {"name": self._typesense_collection_name, "fields": fields} ) [docs] def ad...
f41b6e1b9c30-3
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
"""Return typesense documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: typesense filter_by expression to filter documents on Returns: List of Docum...
f41b6e1b9c30-4
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
docs_and_score = self.similarity_search_with_score(query, k=k, filter=filter) return [doc for doc, _ in docs_and_score] [docs] @classmethod def from_client_params( cls, embedding: Embeddings, *, host: str = "localhost", port: Union[str, int] = "8108", proto...
f41b6e1b9c30-5
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
"connection_timeout_seconds": connection_timeout_seconds, } return cls(Client(client_config), embedding, **kwargs) [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, ids: Optional[List[s...
b372f973ac52-0
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
Source code for langchain.vectorstores.analyticdb """VectorStore wrapper around a Postgres/PGVector database.""" from __future__ import annotations import logging import uuid from typing import Any, Dict, Iterable, List, Optional, Tuple import sqlalchemy from sqlalchemy import REAL, Index from sqlalchemy.dialects.postg...
b372f973ac52-1
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
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) ...
b372f973ac52-2
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
AnalyticDB is a distributed full PostgresSQL syntax cloud-native database. - `connection_string` is a postgres connection string. - `embedding_function` any embedding function implementing `langchain.embeddings.base.Embeddings` interface. - `collection_name` is the name of the collection to use. (de...
b372f973ac52-3
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
[docs] def create_tables_if_not_exists(self) -> None: Base.metadata.create_all(self._conn) [docs] def drop_tables(self) -> None: Base.metadata.drop_all(self._conn) [docs] def create_collection(self) -> None: if self.pre_delete_collection: self.delete_collection() wit...
b372f973ac52-4
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
if not metadatas: metadatas = [{} for _ in texts] with Session(self._conn) as session: collection = self.get_collection(session) if not collection: raise ValueError("Collection not found") for text, metadata, embedding, id in zip(texts, metadatas, ...
b372f973ac52-5
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List of Documents most similar to the query and score for each """ embedding = self....
b372f973ac52-6
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
Document( page_content=result.EmbeddingStore.document, metadata=result.EmbeddingStore.cmetadata, ), result.distance if self.embedding_function is not None else None, ) for result in results ] return docs [doc...
b372f973ac52-7
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
connection_string=connection_string, collection_name=collection_name, embedding_function=embedding, pre_delete_collection=pre_delete_collection, ) store.add_texts(texts=texts, metadatas=metadatas, ids=ids, **kwargs) return store [docs] @classmethod def ...
b372f973ac52-8
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
ids=ids, collection_name=collection_name, **kwargs, ) [docs] @classmethod def connection_string_from_db_params( cls, driver: str, host: str, port: int, database: str, user: str, password: str, ) -> str: """Return ...
e7dded4122b5-0
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
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...
e7dded4122b5-1
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
# 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): """Wrapper around Elasticsearch as a vector database. To connect to an Ela...
e7dded4122b5-2
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243. Example: .. code-block:: python from langchain import ElasticVectorSearch from langchain.embeddings import OpenAIEmbeddings embedding = OpenAIEmbeddings() elastic_host = "cluster_id.region_id...
e7dded4122b5-3
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
raise ValueError( f"Your elasticsearch client string is mis-formatted. Got error: {e} " ) [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, refresh_indices: bool = True, **kwargs: Any, ) -> List[str]: ...
e7dded4122b5-4
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
"vector": embeddings[i], "text": text, "metadata": metadata, "_id": _id, } ids.append(_id) requests.append(request) bulk(self.client, requests) if refresh_indices: self.client.indices.refresh(index=self.index...
e7dded4122b5-5
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
docs_and_scores = [ ( Document( page_content=hit["_source"]["text"], metadata=hit["_source"]["metadata"], ), hit["_score"], ) for hit in hits ] return docs_and_scores [docs] @cl...
e7dded4122b5-6
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
return vectorsearch [docs] def create_index(self, client: Any, index_name: str, mapping: Dict) -> None: version_num = client.info()["version"]["number"][0] version_num = int(version_num) if version_num >= 8: client.indices.create(index=index_name, mappings=mapping) else: ...
e7dded4122b5-7
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
index_name: The name of the Elasticsearch index. embedding: An instance of the Embeddings class, used to generate vector representations of text strings. es_connection: An existing Elasticsearch connection. es_cloud_id: The Cloud ID of the Elasticsearch instance. Requ...
e7dded4122b5-8
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
"similarity": "dot_product", }, } } @staticmethod def _default_knn_query( query_vector: Optional[List[float]] = None, query: Optional[str] = None, model_id: Optional[str] = None, field: Optional[str] = "vector", k: Optional[int] = 10, ...
e7dded4122b5-9
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...], None] ] = None, ) -> Dict: """ Performs a k-nearest neighbor (k-NN) search on the Elasticsearch index. The search can be conducted using either a raw query vector or a model ID. The method first generates t...
e7dded4122b5-10
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
source=source, fields=fields, ) return dict(res) def knn_hybrid_search( self, query: Optional[str] = None, k: Optional[int] = 10, query_vector: Optional[List[float]] = None, model_id: Optional[str] = None, size: Optional[int] = 10, ...
e7dded4122b5-11
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
source: Whether to include the source of each hit in the results. knn_boost: The boost factor for the k-NN part of the search. query_boost: The boost factor for the text-based part of the search. fields The fields to include in the source of each hit. If None, all fie...
ad46bbbb2c17-0
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
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 from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings...
ad46bbbb2c17-1
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
self._embedding_function = embedding_function self._text_key = text_key self._namespace = namespace [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, namespace: Optional[str] = None, ...
ad46bbbb2c17-2
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
) -> List[Tuple[Document, float]]: """Return pinecone documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Dictionary of argument(s) to filter on metadata ...
ad46bbbb2c17-3
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
namespace: Namespace to search in. Default will search in '' namespace. Returns: List of Documents most similar to the query and score for each """ docs_and_scores = self.similarity_search_with_score( query, k=k, filter=filter, namespace=namespace, **kwargs ) ...
ad46bbbb2c17-4
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
"Please install it with `pip install pinecone-client`." ) indexes = pinecone.list_indexes() # checks if provided index exists if index_name in indexes: index = pinecone.Index(index_name) elif len(indexes) == 0: raise ValueError( "No active ind...
ad46bbbb2c17-5
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
[docs] @classmethod def from_existing_index( cls, index_name: str, embedding: Embeddings, text_key: str = "text", namespace: Optional[str] = None, ) -> Pinecone: """Load pinecone vectorstore from index name.""" try: import pinecone e...
1c11890f5525-0
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
Source code for langchain.vectorstores.myscale """Wrapper around MyScale vector database.""" from __future__ import annotations import json import logging from hashlib import sha1 from threading import Thread from typing import Any, Dict, Iterable, List, Optional, Tuple from pydantic import BaseSettings from langchain....
1c11890f5525-1
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
'id': 'text_id', 'vector': 'text_embedding', 'text': 'text_plain', 'metadata': 'metadata_dictionary_in_json', } Defaults to identity map. """ ho...
1c11890f5525-2
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
"""MyScale Wrapper to LangChain embedding_function (Embeddings): config (MyScaleSettings): Configuration to MyScale Client Other keyword arguments will pass into [clickhouse-connect](https://docs.myscale.com/) """ try: from clickhouse_connect import get_cl...
1c11890f5525-3
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
{self.config.column_map['vector']} Array(Float32), {self.config.column_map['metadata']} JSON, CONSTRAINT cons_vec_len CHECK length(\ {self.config.column_map['vector']}) = {dim}, VECTOR INDEX vidx {self.config.column_map['vector']} \ ...
1c11890f5525-4
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
{','.join(_data)} """ return i_str def _insert(self, transac: Iterable, column_names: Iterable[str]) -> None: _i_str = self._build_istr(transac, column_names) self.client.command(_i_str) [docs] def add_texts( self, texts: Iterable[str], metadatas: O...
1c11890f5525-5
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
zip(*values), desc="Inserting data...", total=len(metadatas) ): assert len(v[keys.index(self.config.column_map["vector"])]) == self.dim transac.append(v) if len(transac) == batch_size: if t: t.join() ...
1c11890f5525-6
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
metadata (List[dict], optional): metadata to texts. Defaults to None. Other keyword arguments will pass into [clickhouse-connect](https://clickhouse.com/docs/en/integrations/python#clickhouse-connect-driver-api) Returns: MyScale Index """ ctx = cls(embeddi...
1c11890f5525-7
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
q_emb_str = ",".join(map(str, q_emb)) if where_str: where_str = f"PREWHERE {where_str}" else: where_str = "" q_str = f""" SELECT {self.config.column_map['text']}, {self.config.column_map['metadata']}, dist FROM {self.config.databas...
1c11890f5525-8
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
) -> List[Document]: """Perform a similarity search with MyScale by vectors Args: query (str): query string k (int, optional): Top K neighbors to retrieve. Defaults to 4. where_str (Optional[str], optional): where condition string. ...
1c11890f5525-9
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
NOTE: Please do not let end-user to fill this and always be aware of SQL injection. When dealing with metadatas, remember to use `{self.metadata_column}.attribute` instead of `attribute` alone. The default name for it is `metadata`. Returns: List...
c2e132d64ec0-0
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
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....
c2e132d64ec0-1
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
index = self.client.tvs_get_index(self.index_name) if index is not None: logger.info("Index already exists") return False self.client.tvs_create_index( self.index_name, dim, distance_type, index_type, data_type, ...
c2e132d64ec0-2
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
Returns: List[Document]: A list of documents that are most similar to the query text. """ # Creates embedding vector from user query embedding = self.embedding_function.embed_query(query) keys_and_scores = self.client.tvs_knnsearch( self.index_name, k, embedding, ...
c2e132d64ec0-3
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
index_type = tairvector.IndexType.HNSW if "index_type" in kwargs: index_type = kwargs.pop("index_type") data_type = tairvector.DataType.Float32 if "data_type" in kwargs: data_type = kwargs.pop("data_type") index_params = {} if "index_params" in kwargs: ...
c2e132d64ec0-4
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] return cls.from_texts( texts, embedding, metadatas, index_name, content_key, metadata_key, **kwargs ) [docs] @staticmethod def drop_index( index_name: str = "langchain", **k...
c2e132d64ec0-5
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
"""Connect to an existing Tair index.""" url = get_from_dict_or_env(kwargs, "tair_url", "TAIR_URL") search_params = {} if "search_params" in kwargs: search_params = kwargs.pop("search_params") return cls( embedding, url, index_name, ...
13e191bcb303-0
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
Source code for langchain.vectorstores.docarray.hnsw """Wrapper around Hnswlib store.""" from __future__ import annotations from typing import Any, List, Literal, Optional from langchain.embeddings.base import Embeddings from langchain.vectorstores.docarray.base import ( DocArrayIndex, _check_docarray_import, )...
13e191bcb303-1
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
max_elements (int): Maximum number of vectors that can be stored. Defaults to 1024. index (bool): Whether an index should be built for this field. Defaults to True. ef_construction (int): defines a construction time/accuracy trade-off. Defaults to ...
13e191bcb303-2
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
) -> DocArrayHnswSearch: """Create an DocArrayHnswSearch store and insert data. Args: texts (List[str]): Text data. embedding (Embeddings): Embedding function. metadatas (Optional[List[dict]]): Metadata for each text if it exists. Defaults to None. ...
b6ab57e324ac-0
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html
Source code for langchain.vectorstores.docarray.in_memory """Wrapper around in-memory storage.""" from __future__ import annotations from typing import Any, Dict, List, Literal, Optional from langchain.embeddings.base import Embeddings from langchain.vectorstores.docarray.base import ( DocArrayIndex, _check_doc...
b6ab57e324ac-1
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html
cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, **kwargs: Any, ) -> DocArrayInMemorySearch: """Create an DocArrayInMemorySearch store and insert data. Args: texts (List[str]): Text data. embedding...
66ced19d2d4a-0
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex.html
Source code for langchain.output_parsers.regex from __future__ import annotations import re from typing import Dict, List, Optional from langchain.schema import BaseOutputParser [docs]class RegexParser(BaseOutputParser): """Class to parse the output into a dictionary.""" regex: str output_keys: List[str] ...
a35fb67d736d-0
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html
Source code for langchain.output_parsers.retry from __future__ import annotations from typing import TypeVar from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.prompts.base import BasePromptTemplate from langchain.prompts.prompt import PromptTemplate from lang...
a35fb67d736d-1
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html
return cls(parser=parser, retry_chain=chain) [docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T: try: parsed_completion = self.parser.parse(completion) except OutputParserException: new_completion = self.retry_chain.run( prompt=...
a35fb67d736d-2
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html
return cls(parser=parser, retry_chain=chain) [docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T: try: parsed_completion = self.parser.parse(completion) except OutputParserException as e: new_completion = self.retry_chain.run( pr...
9b6fb847859f-0
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html
Source code for langchain.output_parsers.rail_parser from __future__ import annotations from typing import Any, Dict from langchain.schema import BaseOutputParser [docs]class GuardrailsOutputParser(BaseOutputParser): guard: Any @property def _type(self) -> str: return "guardrails" [docs] @classme...
3caa69652019-0
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html
Source code for langchain.output_parsers.list from __future__ import annotations from abc import abstractmethod from typing import List from langchain.schema import BaseOutputParser [docs]class ListOutputParser(BaseOutputParser): """Class to parse the output of an LLM call to a list.""" @property def _type(...
6f6a3e6afd4e-0
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html
Source code for langchain.output_parsers.structured from __future__ import annotations from typing import Any, List from pydantic import BaseModel from langchain.output_parsers.format_instructions import STRUCTURED_FORMAT_INSTRUCTIONS from langchain.output_parsers.json import parse_and_check_json_markdown from langchai...
a75e4e413257-0
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html
Source code for langchain.output_parsers.fix from __future__ import annotations from typing import TypeVar from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.output_parsers.prompts import NAIVE_FIX_PROMPT from langchain.prompts.base import BasePromptTemplate f...
b672b3cb2096-0
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html
Source code for langchain.output_parsers.pydantic import json import re from typing import Type, TypeVar from pydantic import BaseModel, ValidationError from langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS from langchain.schema import BaseOutputParser, OutputParserException T = TypeVar(...
b672b3cb2096-1
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html
return "pydantic" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
1c5f0bcc3004-0
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html
Source code for langchain.output_parsers.regex_dict from __future__ import annotations import re from typing import Dict, Optional from langchain.schema import BaseOutputParser [docs]class RegexDictParser(BaseOutputParser): """Class to parse the output into a dictionary.""" regex_pattern: str = r"{}:\s?([^.'\n'...
07ee397c6255-0
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html
Source code for langchain.output_parsers.datetime import random from datetime import datetime, timedelta from typing import List from langchain.schema import BaseOutputParser, OutputParserException from langchain.utils import comma_list def _generate_random_datetime_strings( pattern: str, n: int = 3, start_...
07ee397c6255-1
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html
def _type(self) -> str: return "datetime" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
5666daa205ee-0
https://python.langchain.com/en/latest/_modules/langchain/docstore/wikipedia.html
Source code for langchain.docstore.wikipedia """Wrapper around wikipedia API.""" from typing import Union from langchain.docstore.base import Docstore from langchain.docstore.document import Document [docs]class Wikipedia(Docstore): """Wrapper around wikipedia API.""" def __init__(self) -> None: """Chec...
99698d991c39-0
https://python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html
Source code for langchain.docstore.in_memory """Simple in memory docstore in the form of a dict.""" from typing import Dict, Union from langchain.docstore.base import AddableMixin, Docstore from langchain.docstore.document import Document [docs]class InMemoryDocstore(Docstore, AddableMixin): """Simple in memory doc...