id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
50
116
9dd0ae5d44fd-6
) as response: if not response.ok: raise ValueError("Searx API returned an error: ", response.text) result = SearxResults(await response.text()) self._result = result else: async with self.aiosession.get( ...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
9dd0ae5d44fd-7
searx.run("what is the weather in France ?", engine="qwant") # the same result can be achieved using the `!` syntax of searx # to select the engine using `query_suffix` searx.run("what is the weather in France ?", query_suffix="!qwant") """ _params = { ...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
9dd0ae5d44fd-8
) -> str: """Asynchronously version of `run`.""" _params = { "q": query, } params = {**self.params, **_params, **kwargs} if self.query_suffix and len(self.query_suffix) > 0: params["q"] += " " + self.query_suffix if isinstance(query_suffix, str) an...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
9dd0ae5d44fd-9
categories: List of categories to use for the query. **kwargs: extra parameters to pass to the searx API. Returns: Dict with the following keys: { snippet: The description of the result. title: The title of the result. link: T...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
9dd0ae5d44fd-10
self, query: str, num_results: int, engines: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> List[Dict]: """Asynchronously query with json results. Uses aiohttp. See `results` for more info. """ _params = { ...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
ec9608d72fe9-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
ec9608d72fe9-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
ec9608d72fe9-2
from googleapiclient.discovery import build 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=go...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
ec9608d72fe9-3
if "snippet" in result: metadata_result["snippet"] = result["snippet"] metadata_results.append(metadata_result) return metadata_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
ab9c094b5bba-0
Source code for langchain.utilities.wikipedia """Util that calls Wikipedia.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator WIKIPEDIA_MAX_QUERY_LENGTH = 300 [docs]class WikipediaAPIWrapper(BaseModel): """Wrapper around WikipediaAPI. To use, you should have the ``w...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
ab9c094b5bba-1
summary = self.fetch_formatted_page_summary(search_results[i]) if summary is not None: summaries.append(summary) return "\n\n".join(summaries) [docs] def fetch_formatted_page_summary(self, page: str) -> Optional[str]: try: wiki_page = self.wiki_client.page(titl...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
cf04dfff9faf-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
cf04dfff9faf-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
cc4af407f36c-0
Source code for langchain.utilities.google_serper """Util that calls Google Search using the Serper.dev API.""" from typing import Dict, Optional import requests from pydantic.class_validators import root_validator from pydantic.main import BaseModel from langchain.utils import get_from_dict_or_env [docs]class GoogleSe...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
cc4af407f36c-1
snippets = [] if results.get("answerBox"): answer_box = results.get("answerBox", {}) if answer_box.get("answer"): return answer_box.get("answer") elif answer_box.get("snippet"): return answer_box.get("snippet").replace("\n", " ") el...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
cc4af407f36c-2
) response.raise_for_status() search_results = response.json() return search_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
512b6d37fded-0
Source code for langchain.utilities.wolfram_alpha """Util that calls WolframAlpha.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class WolframAlphaAPIWrapper(BaseModel): """Wrapper for Wolfram Alpha. Docs fo...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
512b6d37fded-1
res = self.wolfram_client.query(query) try: assumption = next(res.pods).text answer = next(res.results).text except StopIteration: return "Wolfram Alpha wasn't able to answer it" if answer is None or answer == "": # We don't want to return the assu...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
aaf05089460b-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
aaf05089460b-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
aaf05089460b-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 May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
c602dceabb1a-0
Source code for langchain.utilities.powerbi """Wrapper around a Power BI endpoint.""" from __future__ import annotations import logging import os from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union import aiohttp import requests from aiohttp import ServerTimeoutError from pydantic import BaseMo...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
c602dceabb1a-1
arbitrary_types_allowed = True @root_validator(pre=True, allow_reuse=True) def token_or_credential_present(cls, values: Dict[str, Any]) -> Dict[str, Any]: """Validate that at least one of token and credentials is present.""" if "token" in values or "credential" in values: return valu...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
c602dceabb1a-2
"""Get names of tables available.""" return self.table_names [docs] def get_schemas(self) -> str: """Get the available schema's.""" if self.schemas: return ", ".join([f"{key}: {value}" for key, value in self.schemas.items()]) return "No known schema's yet. Use the schema_p...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
c602dceabb1a-3
) -> str: """Get information about specified tables.""" tables_requested = self._get_tables_to_query(table_names) tables_todo = self._get_tables_todo(tables_requested) for table in tables_todo: try: result = self.run( f"EVALUATE TOPN({self....
https:///python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
c602dceabb1a-4
if "bad request" in str(exc).lower(): return SCHEMA_ERROR_RESPONSE if "unauthorized" in str(exc).lower(): return UNAUTHORIZED_RESPONSE return str(exc) self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"]) r...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
c602dceabb1a-5
) as response: response.raise_for_status() response_json = await response.json() return response_json def json_to_md( json_contents: List[Dict[str, Union[str, int, float]]], table_name: Optional[str] = None, ) -> str: """Converts a JSON object to a markdown ta...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
6c50f17d7abe-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
6c50f17d7abe-1
temperature = w.temperature("celsius") rain = w.rain 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...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
53ab34c44db7-0
Source code for langchain.utilities.serpapi """Chain that calls SerpAPI. Heavily borrowed from https://github.com/ofirpress/self-ask """ import os import sys from typing import Any, Dict, Optional, Tuple import aiohttp from pydantic import BaseModel, Extra, Field, root_validator from langchain.utils import get_from_dic...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
53ab34c44db7-1
aiosession: Optional[aiohttp.ClientSession] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python packag...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
53ab34c44db7-2
"""Use aiohttp to run query through SerpAPI and return the results async.""" def construct_url_and_params() -> Tuple[str, Dict[str, str]]: params = self.get_params(query) params["source"] = "python" if self.serpapi_api_key: params["serp_api_key"] = self.serpap...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
53ab34c44db7-3
toret = res["answer_box"]["snippet"] elif ( "answer_box" in res.keys() and "snippet_highlighted_words" in res["answer_box"].keys() ): toret = res["answer_box"]["snippet_highlighted_words"][0] elif ( "sports_results" in res.keys() and "g...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
223c6275e671-0
Source code for langchain.utilities.arxiv """Util that calls Arxiv.""" import logging from typing import Any, Dict, List from pydantic import BaseModel, Extra, root_validator from langchain.schema import Document logger = logging.getLogger(__name__) [docs]class ArxivAPIWrapper(BaseModel): """Wrapper around ArxivAPI...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
223c6275e671-1
"""Validate that the python package exists in environment.""" try: import arxiv values["arxiv_search"] = arxiv.Search values["arxiv_exceptions"] = ( arxiv.ArxivError, arxiv.UnexpectedEmptyPageError, arxiv.HTTPError, ...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
223c6275e671-2
""" Run Arxiv search and get the PDF documents plus the meta information. See https://lukasschwab.me/arxiv.py/index.html#Search Returns: a list of documents with the document.page_content in PDF format """ try: import fitz except ImportError: raise...
https:///python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
223c6275e671-3
**add_meta, } ), ) docs.append(doc) except FileNotFoundError as f_ex: logger.debug(f_ex) return docs except self.arxiv_exceptions as ex: logger....
https:///python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
d55e98ec5bee-0
Source code for langchain.vectorstores.opensearch_vector_search """Wrapper around OpenSearch vector database.""" from __future__ import annotations import uuid from typing import Any, Dict, Iterable, List, Optional from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from la...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-1
try: opensearch = _import_opensearch() client = opensearch(opensearch_url, **kwargs) except ValueError as e: raise ValueError( f"OpenSearch client string provided is not in proper format. " f"Got error: {e} " ) return client def _validate_embeddings_and_bu...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-2
request = { "_op_type": "index", "_index": index_name, vector_field: embeddings[i], text_field: text, "metadata": metadata, "_id": _id, } requests.append(request) ids.append(_id) bulk(client, requests) client.indices...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-3
"parameters": {"ef_construction": ef_construction, "m": m}, }, } } }, } def _default_approximate_search_query( query_vector: List[float], size: int = 4, k: int = 4, vector_field: str = "vector_field", ) -> Dict: """For Approximate k-NN Sear...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-4
query_vector, size, k, vector_field ) search_query["query"]["knn"][vector_field]["filter"] = lucene_filter return search_query def _default_script_query( query_vector: List[float], space_type: str = "l2", pre_filter: Dict = MATCH_ALL_QUERY, vector_field: str = "vector_field", ) -> Dict: ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-5
vector_field: str = "vector_field", ) -> Dict: """For Painless Scripting Search, this is the default query.""" source = __get_painless_scripting_source(space_type, query_vector) return { "query": { "script_score": { "query": pre_filter, "script": { ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-6
bulk_size: int = 500, **kwargs: Any, ) -> List[str]: """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. bulk_size...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-7
texts, metadatas, vector_field, text_field, mapping, ) [docs] def similarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs most similar to query. By default supports Approximate Search. ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-8
search_type: "script_scoring"; default: "approximate_search" space_type: "l2", "l1", "linf", "cosinesimil", "innerproduct", "hammingbit"; default: "l2" pre_filter: script_score query to pre-filter documents before identifying nearest neighbors; default: {"match_all": {}} ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-9
"is invalid" ) if boolean_filter != {}: search_query = _approximate_search_query_with_boolean_filter( embedding, boolean_filter, size, k, vector_field, subquery_clause ) elif lucene_filter != {}: search_query = _...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-10
for hit in hits ] return documents [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, bulk_size: int = 500, **kwargs: Any, ) -> OpenSearchVectorSearch: """Construct O...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-11
ef_construction: Size of the dynamic list used during k-NN graph creation. Higher values lead to more accurate graph but slower indexing speed; default: 512 m: Number of bidirectional links created for each new element. Large impact on memory consumption. Between 2 and 10...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
d55e98ec5bee-12
if is_appx_search: engine = _get_kwargs_value(kwargs, "engine", "nmslib") space_type = _get_kwargs_value(kwargs, "space_type", "l2") ef_search = _get_kwargs_value(kwargs, "ef_search", 512) ef_construction = _get_kwargs_value(kwargs, "ef_construction", 512) m =...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
ac1e8e89d96c-0
Source code for langchain.vectorstores.faiss """Wrapper around FAISS vector database.""" from __future__ import annotations import math import pickle import uuid from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple import numpy as np from langchain.docstore.base import Addabl...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
ac1e8e89d96c-1
[docs]class FAISS(VectorStore): """Wrapper around FAISS vector database. To use, you should have the ``faiss`` python package installed. Example: .. code-block:: python from langchain import FAISS faiss = FAISS(embedding_function, index, docstore, index_to_docstore_id) ""...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
ac1e8e89d96c-2
starting_len = len(self.index_to_docstore_id) self.index.add(np.array(embeddings, dtype=np.float32)) # Get list of index, id, and docs. full_info = [ (starting_len + i, str(uuid.uuid4()), doc) for i, doc in enumerate(documents) ] # Add information to docst...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
ac1e8e89d96c-3
self, text_embeddings: Iterable[Tuple[str, List[float]]], metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: text_embeddings: Iterable pairs of string and embedding to ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
ac1e8e89d96c-4
# 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): raise ValueError(f"Could not find document for id {_id}, got {doc}") docs.append...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
ac1e8e89d96c-5
"""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. """ docs_and_scores = self.similarity_search_with_score(quer...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
ac1e8e89d96c-6
np.array([embedding], dtype=np.float32), embeddings, k=k, lambda_mult=lambda_mult, ) selected_indices = [indices[0][i] for i in mmr_selected] docs = [] for i in selected_indices: if i == -1: # This happens when not enough do...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
ac1e8e89d96c-7
embedding, k, fetch_k, lambda_mult=lambda_mult ) return docs [docs] def merge_from(self, target: FAISS) -> None: """Merge another FAISS object with the current one. Add the target FAISS to the current one. Args: target: FAISS object you wish to merge into the curre...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
ac1e8e89d96c-8
) -> FAISS: faiss = dependable_faiss_import() index = faiss.IndexFlatL2(len(embeddings[0])) index.add(np.array(embeddings, dtype=np.float32)) documents = [] for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} documents.append(Docu...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
ac1e8e89d96c-9
metadatas, **kwargs, ) [docs] @classmethod def from_embeddings( cls, text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> FAISS: """Construct FAISS wrapper from ra...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
ac1e8e89d96c-10
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_name}.faiss".format(index_name=index_name)) ) # save docstore...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
ac1e8e89d96c-11
self, query: str, k: int = 4, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs and their similarity scores on a scale from 0 to 1.""" if self.relevance_score_fn is None: raise ValueError( "normalize_score_fn must be provided to" ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
dfdeefff4be2-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
dfdeefff4be2-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
dfdeefff4be2-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
dfdeefff4be2-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
dfdeefff4be2-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
dfdeefff4be2-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
dfdeefff4be2-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
dfdeefff4be2-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
799c5787f375-0
Source code for langchain.vectorstores.zilliz from __future__ import annotations import logging from typing import Any, List, Optional from langchain.embeddings.base import Embeddings from langchain.vectorstores.milvus import Milvus logger = logging.getLogger(__name__) [docs]class Zilliz(Milvus): def _create_index(...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
799c5787f375-1
"Failed to create an index on collection: %s", self.collection_name ) raise e [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = "LangChainCollecti...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
799c5787f375-2
Zilliz: Zilliz Vector Store """ vector_db = cls( embedding_function=embedding, collection_name=collection_name, connection_args=connection_args, consistency_level=consistency_level, index_params=index_params, search_params=search_pa...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
7c3ca04c2244-0
Source code for langchain.vectorstores.base """Interface for vector stores.""" from __future__ import annotations import asyncio from abc import ABC, abstractmethod from functools import partial from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, TypeVar from pydantic import BaseModel, Field, root_vali...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
7c3ca04c2244-1
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] metadatas = [doc.metada...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
7c3ca04c2244-2
) -> 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 self.amax_marginal_relevance_search(query, **kwargs) ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
7c3ca04c2244-3
k: int = 4, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs and relevance scores, normalized on a scale from 0 to 1. 0 is dissimilar, 1 is most similar. """ raise NotImplementedError [docs] async def asimilarity_search( self, query: str, k: int = 4...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
7c3ca04c2244-4
# asynchronous in the vector store implementations. func = partial(self.similarity_search_by_vector, embedding, k, **kwargs) return await asyncio.get_event_loop().run_in_executor(None, func) [docs] def max_marginal_relevance_search( self, query: str, k: int = 4, fetch_...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
7c3ca04c2244-5
# asynchronous in the vector store implementations. func = partial( self.max_marginal_relevance_search, query, k, fetch_k, lambda_mult, **kwargs ) return await asyncio.get_event_loop().run_in_executor(None, func) [docs] def max_marginal_relevance_search_by_vector( self, ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
7c3ca04c2244-6
[docs] @classmethod def from_documents( cls: Type[VST], documents: List[Document], embedding: Embeddings, **kwargs: Any, ) -> VST: """Return VectorStore initialized from documents and embeddings.""" texts = [d.page_content for d in documents] metadatas ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
7c3ca04c2244-7
"""Return VectorStore initialized from texts and embeddings.""" raise NotImplementedError [docs] def as_retriever(self, **kwargs: Any) -> BaseRetriever: return VectorStoreRetriever(vectorstore=self, **kwargs) class VectorStoreRetriever(BaseRetriever, BaseModel): vectorstore: VectorStore searc...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
7c3ca04c2244-8
docs = await self.vectorstore.amax_marginal_relevance_search( query, **self.search_kwargs ) else: raise ValueError(f"search_type of {self.search_type} not allowed.") return docs def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]: ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
ee8f39f95e54-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
ee8f39f95e54-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
ee8f39f95e54-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
8265c4c4da77-0
Source code for langchain.vectorstores.annoy """Wrapper around Annoy vector database.""" from __future__ import annotations import os import pickle import uuid from configparser import ConfigParser from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple import numpy as np from l...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
8265c4c4da77-1
): """Initialize with necessary components.""" self.embedding_function = embedding_function self.index = index self.metric = metric self.docstore = docstore self.index_to_docstore_id = index_to_docstore_id [docs] def add_texts( self, texts: Iterable[str...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
8265c4c4da77-2
Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. search_k: inspect up to search_k nodes which defaults to n_trees * n if not provided Returns: List of Documents most similar to the query and score ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
8265c4c4da77-3
k: Number of Documents to return. Defaults to 4. search_k: inspect up to search_k nodes which defaults to n_trees * n if not provided Returns: List of Documents most similar to the query and score for each """ embedding = self.embedding_function(query) ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
8265c4c4da77-4
Returns: List of Documents most similar to the embedding. """ docs_and_scores = self.similarity_search_with_score_by_index( docstore_index, k, search_k ) return [doc for doc, _ in docs_and_scores] [docs] def similarity_search( self, query: str, k: int =...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
8265c4c4da77-5
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. """ idxs = self.index.get_nns_by_vector( ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
8265c4c4da77-6
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 corresponding to maximum diversity...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
8265c4c4da77-7
documents = [] for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} documents.append(Document(page_content=text, metadata=metadata)) index_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))} docstore = InMemoryDocstore( {inde...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
8265c4c4da77-8
from langchain import Annoy from langchain.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings() index = Annoy.from_texts(texts, embeddings) """ embeddings = embedding.embed_documents(texts) return cls.__from( texts, embedd...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
8265c4c4da77-9
embeddings = OpenAIEmbeddings() text_embeddings = embeddings.embed_documents(texts) text_embedding_pairs = list(zip(texts, text_embeddings)) db = Annoy.from_embeddings(text_embedding_pairs, embeddings) """ texts = [t[0] for t in text_embeddings] em...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
8265c4c4da77-10
Args: folder_path: folder path to load index, docstore, and index_to_docstore_id from. embeddings: Embeddings to use when generating queries. """ path = Path(folder_path) # load index separately since it is not picklable annoy = dependable_annoy_im...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html
ae72e5742c75-0
Source code for langchain.vectorstores.redis """Wrapper around Redis vector database.""" from __future__ import annotations import json import logging import uuid from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Mapping, Optional, Tuple, Type, ) import num...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
ae72e5742c75-1
"Please refer to Redis Stack docs: https://redis.io/docs/stack/" ) logging.error(error_message) raise ValueError(error_message) def _check_index_exists(client: RedisType, index_name: str) -> bool: """Check if Redis index exists.""" try: client.ft(index_name).info() except: # noqa: E722 ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
ae72e5742c75-2
vector_key: str = "content_vector", relevance_score_fn: Optional[ Callable[[float], float] ] = _default_relevance_score, **kwargs: Any, ): """Initialize with necessary components.""" try: import redis except ImportError: raise Value...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html
ae72e5742c75-3
schema = ( TextField(name=self.content_key), TextField(name=self.metadata_key), VectorField( self.vector_key, "FLAT", { "TYPE": "FLOAT32", "DIM": dim, ...
https:///python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html