id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
117
c3da804ad8d4-1
""" Get or create a collection. 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, cmeta...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
c3da804ad8d4-2
""" VectorStore implementation using AnalyticDB. 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. - `c...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
c3da804ad8d4-3
engine = sqlalchemy.create_engine(self.connection_string) conn = engine.connect() return conn [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_col...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
c3da804ad8d4-4
""" if ids is None: ids = [str(uuid.uuid1()) for _ in texts] embeddings = self.embedding_function.embed_documents(list(texts)) if not metadatas: metadatas = [{} for _ in texts] with Session(self._conn) as session: collection = self.get_collection(sessi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
c3da804ad8d4-5
self, query: str, k: int = 4, filter: Optional[dict] = None, ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
c3da804ad8d4-6
) .filter(filter_by) .order_by(EmbeddingStore.embedding.op("<->")(embedding)) .join( CollectionStore, EmbeddingStore.collection_id == CollectionStore.uuid, ) .limit(k) .all() ) docs = [ ( ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
c3da804ad8d4-7
pre_delete_collection: bool = False, **kwargs: Any, ) -> AnalyticDB: """ Return VectorStore initialized from texts and embeddings. Postgres connection string is required Either pass it as a parameter or set the PGVECTOR_CONNECTION_STRING environment variable. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
c3da804ad8d4-8
or set the PGVECTOR_CONNECTION_STRING environment variable. """ texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] connection_string = cls.get_connection_string(kwargs) kwargs["connection_string"] = connection_string return cls.from_te...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
8e9ca2bfc256-0
Source code for langchain.vectorstores.pinecone """Wrapper around Pinecone vector database.""" from __future__ import annotations import logging import uuid from typing import Any, Callable, Iterable, List, Optional, Tuple from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
8e9ca2bfc256-1
f"got {type(index)}" ) self._index = index 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: Opt...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
8e9ca2bfc256-2
k: int = 4, filter: Optional[dict] = None, namespace: Optional[str] = None, ) -> 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 r...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
8e9ca2bfc256-3
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 namespace: Namespace to search in. Default will search in '' namespace. Returns: List of Documen...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
8e9ca2bfc256-4
pinecone = Pinecone.from_texts( texts, embeddings, index_name="langchain-demo" ) """ try: import pinecone except ImportError: raise ValueError( "Could not import pinecone python pa...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
8e9ca2bfc256-5
for j, line in enumerate(lines_batch): metadata[j][text_key] = line to_upsert = zip(ids_batch, embeds, metadata) # upsert to Pinecone index.upsert(vectors=list(to_upsert), namespace=namespace) return cls(index, embedding.embed_query, text_key, namespace) [docs...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
4a78a37cded8-0
Source code for langchain.vectorstores.myscale """Wrapper around MyScale vector database.""" from __future__ import annotations import json import logging from hashlib import sha1 from threading import Thread from typing import Any, Dict, Iterable, List, Optional, Tuple from pydantic import BaseSettings from langchain....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
4a78a37cded8-1
.. code-block:: python { 'id': 'text_id', 'vector': 'text_embedding', 'text': 'text_plain', 'metadata': 'metadata_dictionary_in_json', ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
4a78a37cded8-2
config: Optional[MyScaleSettings] = None, **kwargs: Any, ) -> None: """MyScale Wrapper to LangChain embedding_function (Embeddings): config (MyScaleSettings): Configuration to MyScale Client Other keyword arguments will pass into [clickhouse-connect](https://docs....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
4a78a37cded8-3
CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}( {self.config.column_map['id']} String, {self.config.column_map['text']} String, {self.config.column_map['vector']} Array(Float32), {self.config.column_map['metadata']} JSON, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
4a78a37cded8-4
_data.append(f"({n})") i_str = f""" INSERT INTO TABLE {self.config.database}.{self.config.table}({ks}) VALUES {','.join(_data)} """ return i_str def _insert(self, transac: Iterable, column_names: Iterable[str]) -> N...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
4a78a37cded8-5
column_names[colmap_["metadata"]] = map(json.dumps, metadatas) assert len(set(colmap_) - set(column_names)) >= 0 keys, values = zip(*column_names.items()) try: t = None for v in self.pgbar( zip(*values), desc="Inserting data...", total=len(metadatas) ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
4a78a37cded8-6
texts (Iterable[str]): List or tuple of strings to be added config (MyScaleSettings, Optional): Myscale configuration text_ids (Optional[Iterable], optional): IDs for the texts. Defaults to None. batch_size (int, optional): Batchsi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
4a78a37cded8-7
).named_results(): _repr += ( f"|\033[94m{r['name']:24s}\033[0m|\033[96m{r['type']:24s}\033[0m|\n" ) _repr += "-" * 51 + "\n" return _repr def _build_qstr( self, q_emb: List[float], topk: int, where_str: Optional[str] = None ) -> str: q_emb...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
4a78a37cded8-8
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[Document]: List of Documents """ return self.similarity_search_by_v...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
4a78a37cded8-9
] except Exception as e: logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") return [] [docs] def similarity_search_with_relevance_scores( self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any ) -> List[Tuple[Document, float]]: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
4a78a37cded8-10
return [] [docs] def drop(self) -> None: """ Helper function: Drop data """ self.client.command( f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}" ) @property def metadata_column(self) -> str: return self.config.column_map["metadata...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
ae0a6cc91d2e-0
Source code for langchain.vectorstores.atlas """Wrapper around Atlas by Nomic.""" from __future__ import annotations import logging import uuid from typing import Any, Iterable, List, Optional, Type import numpy as np from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
ae0a6cc91d2e-1
is_public (bool): Whether your project is publicly accessible. True by default. reset_project_if_exists (bool): Whether to reset this project if it already exists. Default False. Generally userful during development and testing. """ try: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
ae0a6cc91d2e-2
metadatas (Optional[List[dict]], optional): Optional list of metadatas. ids (Optional[List[str]]): An optional list of ids. refresh(bool): Whether or not to refresh indices with the updated data. Default True. Returns: List[str]: List of IDs of the added texts...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
ae0a6cc91d2e-3
else: if metadatas is None: data = [ {"text": text, AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i]} for i, text in enumerate(texts) ] else: for i, text in enumerate(texts): metadatas[i]["text"] =...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
ae0a6cc91d2e-4
""" if self._embedding_function is None: raise NotImplementedError( "AtlasDB requires an embedding_function for text similarity search!" ) _embedding = self._embedding_function.embed_documents([query])[0] embedding = np.array(_embedding).reshape(1, -1) ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
ae0a6cc91d2e-5
ids (Optional[List[str]]): Optional list of document IDs. If None, ids will be auto created description (str): A description for your project. is_public (bool): Whether your project is publicly accessible. True by default. reset_project_if_exists (bool...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
ae0a6cc91d2e-6
ids: Optional[List[str]] = None, name: Optional[str] = None, api_key: Optional[str] = None, persist_directory: Optional[str] = None, description: str = "A description for your project", is_public: bool = True, reset_project_if_exists: bool = False, index_kwargs: O...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
ae0a6cc91d2e-7
return cls.from_texts( name=name, api_key=api_key, texts=texts, embedding=embedding, metadatas=metadatas, ids=ids, description=description, is_public=is_public, reset_project_if_exists=reset_project_if_exists, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
e4522d97411b-0
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...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
e4522d97411b-1
*, typesense_collection_name: Optional[str] = None, text_key: str = "text", ): """Initialize with Typesense client.""" try: from typesense import Client except ImportError: raise ValueError( "Could not import typesense python package. "...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
e4522d97411b-2
] def _create_collection(self, num_dim: int) -> None: fields = [ {"name": "vec", "type": "float[]", "num_dim": num_dim}, {"name": f"{self._text_key}", "type": "string"}, {"name": ".*", "type": "auto"}, ] self._typesense_client.collections.create( ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
e4522d97411b-3
self, query: str, k: int = 4, filter: Optional[str] = "", ) -> List[Tuple[Document, float]]: """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. De...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
e4522d97411b-4
k: Number of Documents to return. Defaults to 4. filter: typesense filter_by expression to filter documents on Returns: List of Documents most similar to the query and score for each """ docs_and_score = self.similarity_search_with_score(query, k=k, filter=filter) ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
e4522d97411b-5
} typesense_api_key = typesense_api_key or get_from_env( "typesense_api_key", "TYPESENSE_API_KEY" ) client_config = { "nodes": [node], "api_key": typesense_api_key, "connection_timeout_seconds": connection_timeout_seconds, } return ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
75098c4652e7-0
Source code for langchain.vectorstores.base """Interface for vector stores.""" from __future__ import annotations import asyncio import warnings from abc import ABC, abstractmethod from functools import partial from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, TypeVar from pydantic import BaseModel, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
75098c4652e7-1
Args: documents (List[Document]: Documents to add to the vectorstore. Returns: List[str]: List of IDs of the added texts. """ # TODO: Handle the case where the user doesn't provide ids on the Collection texts = [doc.page_content for doc in documents] metad...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
75098c4652e7-2
self, query: str, search_type: str, **kwargs: Any ) -> List[Document]: """Return docs most similar to query using specified search type.""" if search_type == "similarity": return await self.asimilarity_search(query, **kwargs) elif search_type == "mmr": return await se...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
75098c4652e7-3
query, k=k, **kwargs ) if any( similarity < 0.0 or similarity > 1.0 for _, similarity in docs_and_similarities ): warnings.warn( "Relevance scores must be between" f" 0 and 1, got {docs_and_similarities}" ) s...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
75098c4652e7-4
return await asyncio.get_event_loop().run_in_executor(None, func) [docs] async def asimilarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs most similar to query.""" # This is a temporary workaround to make the similarity search # asynchr...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
75098c4652e7-5
self, query: str, 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 amon...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
75098c4652e7-6
[docs] def max_marginal_relevance_search_by_vector( self, 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 marg...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
75098c4652e7-7
texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] return cls.from_texts(texts, embedding, metadatas=metadatas, **kwargs) [docs] @classmethod async def afrom_documents( cls: Type[VST], documents: List[Document], embedding: Embeddings, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
75098c4652e7-8
vectorstore: VectorStore search_type: str = "similarity" search_kwargs: dict = Field(default_factory=dict) class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True @root_validator() def validate_search_type(cls, values: Dict) -> Dict: """Vali...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
75098c4652e7-9
raise ValueError(f"search_type of {self.search_type} not allowed.") return docs async def aget_relevant_documents(self, query: str) -> List[Document]: if self.search_type == "similarity": docs = await self.vectorstore.asimilarity_search( query, **self.search_kwargs ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
8d47fcdc9b0a-0
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...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-1
returns: 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.ar...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-2
embeddings = OpenAIEmbeddings() 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, embedd...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-3
if self.verbose: print( 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"] ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-4
**kwargs: Any, ) -> List[str]: """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]], opti...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-5
if batch_size == 0: return [] batched = [ elements[i : i + batch_size] for i in range(0, len(elements), batch_size) ] ingest().eval( batched, self.ds, num_workers=min(self.num_workers, len(batched) // max(self.num_workers, 1)), ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-6
take [Deep Lake filter] (https://docs.deeplake.ai/en/latest/deeplake.core.dataset.html#deeplake.core.dataset.Dataset.filter) Defaults to None. maximal_marginal_relevance: Whether to use maximal marginal relevance. Defaults to False. fetch_k: Number of ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-7
distance_metric=distance_metric.lower(), ) view = view[indices] if use_maximal_marginal_relevance: lambda_mult = kwargs.get("lambda_mult", 0.5) indices = maximal_marginal_relevance( query_emb, embeddings[indices]...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-8
maximal_marginal_relevance: Whether to use maximal marginal relevance. 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: Lis...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-9
k (int): Number of results to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List[Tuple[Document, float]]: List of documents most similar to the query text with distance in float. """ return self._s...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-10
) [docs] def max_marginal_relevance_search( self, query: str, 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 optim...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-11
**kwargs: Any, ) -> DeepLake: """Create a Deep Lake dataset from a raw documents. If a dataset_path is specified, the dataset will be persisted in that location, otherwise by default at `./deeplake` Args: path (str, pathlib.Path): - The full path to the dataset. Can be: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-12
dataset_path=dataset_path, embedding_function=embedding, **kwargs ) deeplake_dataset.add_texts(texts=texts, metadatas=metadatas, ids=ids) return deeplake_dataset [docs] def delete( self, ids: Any[List[str], None] = None, filter: Any[Dict[str, str], None] = None, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
8d47fcdc9b0a-13
try: import deeplake except ImportError: raise ValueError( "Could not import deeplake python package. " "Please install it with `pip install deeplake`." ) deeplake.delete(path, large_ok=True, force=True) [docs] def delete_dataset(sel...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
2dd424202175-0
Source code for langchain.vectorstores.lancedb """Wrapper around LanceDB vector database""" from __future__ import annotations import uuid from typing import Any, Iterable, List, Optional from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain.vectorstores.base i...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html
2dd424202175-1
self._id_key = id_key self._text_key = text_key [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: """Turn texts into embedding and add it to the database...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html
2dd424202175-2
""" embedding = self._embedding.embed_query(query) docs = self._connection.search(embedding).limit(k).to_df() return [ Document( page_content=row[self._text_key], metadata=row[docs.columns != self._text_key], ) for _, row in doc...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html
32b203bf2841-0
Source code for langchain.vectorstores.sklearn """ Wrapper around scikit-learn NearestNeighbors implementation. The vector store can be persisted in json, bson or parquet format. """ import json import math import os from abc import ABC, abstractmethod from typing import Any, Dict, Iterable, List, Literal, Optional, Tu...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
32b203bf2841-1
with open(self.persist_path, "r") as fp: return json.load(fp) class BsonSerializer(BaseSerializer): """Serializes data in binary json using the bson python package.""" def __init__(self, persist_path: str) -> None: super().__init__(persist_path) self.bson = guard_import("bson") @...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
32b203bf2841-2
raise exc else: os.remove(backup_path) else: self.pq.write_table(table, self.persist_path) def load(self) -> Any: table = self.pq.read_table(self.persist_path) df = table.to_pandas() return {col: series.tolist() for col, series in df.items()} S...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
32b203bf2841-3
# data properties self._embeddings: List[List[float]] = [] self._texts: List[str] = [] self._metadatas: List[dict] = [] self._ids: List[str] = [] # cache properties self._embeddings_np: Any = np.asarray([]) if self._persist_path is not None and os.path.isfile(self...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
32b203bf2841-4
) -> List[str]: _texts = list(texts) _ids = ids or [str(uuid4()) for _ in _texts] self._texts.extend(_texts) self._embeddings.extend(self._embedding_function.embed_documents(_texts)) self._metadatas.extend(metadatas or ([{}] * len(_texts))) self._ids.extend(_ids) ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
32b203bf2841-5
query_embedding = self._embedding_function.embed_query(query) indices_dists = self._similarity_index_search_with_score( query_embedding, k=k, **kwargs ) return [ ( Document( page_content=self._texts[idx], metadata={"...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
32b203bf2841-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
32b203bf2841-7
among selected documents. 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 ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
7208e2189b9e-0
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...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html
7208e2189b9e-1
[docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, **kwargs: Any, ) -> DocArrayInMemorySearch: """Create an DocArrayInMemorySearch store and insert data. Args: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html
eadfa296f8f3-0
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, )...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
eadfa296f8f3-1
"cosine", "ip", and "l2". Defaults to "cosine". 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 constr...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
eadfa296f8f3-2
work_dir: Optional[str] = None, n_dim: Optional[int] = None, **kwargs: Any, ) -> DocArrayHnswSearch: """Create an DocArrayHnswSearch store and insert data. Args: texts (List[str]): Text data. embedding (Embeddings): Embedding function. metadatas (O...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
bb95ba0f0019-0
Source code for langchain.utilities.google_search """Util that calls Google Search.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class GoogleSearchAPIWrapper(BaseModel): """Wrapper for Google Search API. ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
bb95ba0f0019-1
- Under Search engine ID you’ll find the search-engine-ID. 4. Enable the Custom Search API - Navigate to the APIs & Services→Dashboard panel in Cloud Console. - Click Enable APIs and Services. - Search for Custom Search API and click on it. - Click Enable. URL for it: https://console.cloud.googl...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
bb95ba0f0019-2
except ImportError: raise ImportError( "google-api-python-client is not installed. " "Please install it with `pip install google-api-python-client`" ) service = build("customsearch", "v1", developerKey=google_api_key) values["search_engine"] = serv...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
bb95ba0f0019-3
metadata_result["snippet"] = result["snippet"] metadata_results.append(metadata_result) return metadata_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
a62bf6257e32-0
Source code for langchain.utilities.metaphor_search """Util that calls Metaphor Search API. In order to set this up, follow instructions at: """ import json from typing import Dict, List import aiohttp import requests from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env...
https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
a62bf6257e32-1
"""Run query through Metaphor Search and return metadata. Args: query: The query to search for. num_results: The number of results to return. Returns: A list of dictionaries with the following keys: title - The title of the url - The ur...
https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
a62bf6257e32-2
for result in raw_search_results: cleaned_results.append( { "title": result["title"], "url": result["url"], "author": result["author"], "date_created": result["dateCreated"], } ) ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
848d134415ca-0
Source code for langchain.utilities.awslambda """Util that calls Lambda.""" import json from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator [docs]class LambdaWrapper(BaseModel): """Wrapper for AWS Lambda SDK. Docs for using: 1. pip install boto3 2. Create a lambd...
https://python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html
848d134415ca-1
answer = json.loads(payload_string)["body"] except StopIteration: return "Failed to parse response from Lambda" if answer is None or answer == "": # We don't want to return the assumption alone if answer is empty return "Request failed." else: retu...
https://python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html
eb4dbeac9a03-0
Source code for langchain.utilities.google_places_api """Chain that calls Google Places API. """ import logging from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class GooglePlacesAPIWrapper(BaseModel): """Wrapper arou...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
eb4dbeac9a03-1
except ImportError: raise ImportError( "Could not import googlemaps python package. " "Please install it with `pip install googlemaps`." ) return values [docs] def run(self, query: str) -> str: """Run Places search and get k number of places tha...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
eb4dbeac9a03-2
"formatted_address", "Unknown" ) phone_number = place_details.get("result", {}).get( "formatted_phone_number", "Unknown" ) website = place_details.get("result", {}).get("website", "Unknown") formatted_details = ( f"{name}\nAddre...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
0f3b0510e408-0
Source code for langchain.utilities.bing_search """Util that calls Bing Search. In order to set this up, follow instructions at: https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e """ from typing import Dict, List import requests from pydantic import BaseModel, Extra, ro...
https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
0f3b0510e408-1
bing_subscription_key = get_from_dict_or_env( values, "bing_subscription_key", "BING_SUBSCRIPTION_KEY" ) values["bing_subscription_key"] = bing_subscription_key bing_search_url = get_from_dict_or_env( values, "bing_search_url", "BING_SEARCH_URL", ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
0f3b0510e408-2
"snippet": result["snippet"], "title": result["name"], "link": result["url"], } metadata_results.append(metadata_result) return metadata_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
d1cee340e36e-0
Source code for langchain.utilities.openweathermap """Util that calls OpenWeatherMap using PyOWM.""" from typing import Any, Dict, Optional from pydantic import Extra, root_validator from langchain.tools.base import BaseModel from langchain.utils import get_from_dict_or_env [docs]class OpenWeatherMapAPIWrapper(BaseMode...
https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
d1cee340e36e-1
heat_index = w.heat_index clouds = w.clouds return ( f"In {location}, the current weather is as follows:\n" f"Detailed status: {detailed_status}\n" f"Wind speed: {wind['speed']} m/s, direction: {wind['deg']}°\n" f"Humidity: {humidity}%\n" f"Tem...
https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
e5b2d309cf90-0
Source code for langchain.utilities.searx_search """Utility for using SearxNG meta search API. SearxNG is a privacy-friendly free metasearch engine that aggregates results from `multiple search engines <https://docs.searxng.org/admin/engines/configured_engines.html>`_ and databases and supports the `OpenSearch <https:/...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
e5b2d309cf90-1
:class:`SearxResults` is a convenience wrapper around the raw json result. Example usage of the ``run`` method to make a search: .. code-block:: python s.run(query="what is the best search engine?") Engine Parameters ----------------- You can pass any `accepted searx search API <https://docs.searxng.org/dev...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
e5b2d309cf90-2
.. code-block:: python # select the github engine and pass the search suffix s = SearchWrapper("langchain library", query_suffix="!gh") s = SearchWrapper("langchain library") # select github the conventional google search syntax s.run("large language models", query_suffix="site:g...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
e5b2d309cf90-3
return {"language": "en", "format": "json"} [docs]class SearxResults(dict): """Dict like wrapper around search api results.""" _data = "" def __init__(self, data: str): """Take a raw result from Searx and make it into a dict like object.""" json_data = json.loads(data) super().__init...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html