id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
fe9d545ce648-1
*, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None, ) -> ApifyDatasetLoader: """Run an Actor on the Apify platform and wait for results to be ready. Args: actor_id (str): The ID or name of the Actor on the Apify...
https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
fe9d545ce648-2
memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None, ) -> ApifyDatasetLoader: """Run an Actor on the Apify platform and wait for results to be ready. Args: actor_id (str): The ID or name of the Actor on the Apify platform. run_input (Dict): The inp...
https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
7fdf084c9a19-0
Source code for langchain.utilities.twilio """Util that calls Twilio.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class TwilioAPIWrapper(BaseModel): """Sms Client using Twilio. To use, you should have the ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
7fdf084c9a19-1
that is enabled for the type of message you want to send. Phone numbers or [short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from Twilio also work here. You cannot, for example, spoof messages from a private cell phone number. If you are using `messaging_service_sid`, th...
https://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
7fdf084c9a19-2
characters in length. to: The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format for SMS/MMS or [Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses) for other 3rd-party chann...
https://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
f6b5ad050170-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
f6b5ad050170-1
Other methods are are available for convenience. :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 `accept...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
f6b5ad050170-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
f6b5ad050170-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
f6b5ad050170-4
.. code-block:: python from langchain.utilities import SearxSearchWrapper # note the unsecure parameter is not needed if you pass the url scheme as # http searx = SearxSearchWrapper(searx_host="http://localhost:8888", un...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
f6b5ad050170-5
if categories: values["params"]["categories"] = ",".join(categories) searx_host = get_from_dict_or_env(values, "searx_host", "SEARX_HOST") if not searx_host.startswith("http"): print( f"Warning: missing the url scheme on host \ ! assuming secure ht...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
f6b5ad050170-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
f6b5ad050170-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
f6b5ad050170-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
f6b5ad050170-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
f6b5ad050170-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
9a93ade63c1e-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
9a93ade63c1e-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
9a93ade63c1e-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
9a93ade63c1e-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 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
467341b6206f-0
Source code for langchain.utilities.wikipedia """Util that calls Wikipedia.""" import logging from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.schema import Document logger = logging.getLogger(__name__) WIKIPEDIA_MAX_QUERY_LENGTH = 300 [docs]class Wikiped...
https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
467341b6206f-1
summaries = [] for page_title in page_titles[: self.top_k_results]: if wiki_page := self._fetch_page(page_title): if summary := self._formatted_page_summary(page_title, wiki_page): summaries.append(summary) if not summaries: return "No good Wik...
https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
467341b6206f-2
except ( self.wiki_client.exceptions.PageError, self.wiki_client.exceptions.DisambiguationError, ): return None [docs] def load(self, query: str) -> List[Document]: """ Run Wikipedia search and get the article text plus the meta information. See ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
460c719e5711-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
460c719e5711-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
5fff2bc12059-0
Source code for langchain.utilities.google_serper """Util that calls Google Search using the Serper.dev API.""" from typing import Any, Dict, List, Optional import aiohttp import requests from pydantic.class_validators import root_validator from pydantic.main import BaseModel from typing_extensions import Literal from ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
5fff2bc12059-1
arbitrary_types_allowed = True @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key exists in environment.""" serper_api_key = get_from_dict_or_env( values, "serper_api_key", "SERPER_API_KEY" ) values["serper_api_key"] = serp...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
5fff2bc12059-2
"""Run query through GoogleSearch and parse result async.""" results = await self._async_google_serper_search_results( query, gl=self.gl, hl=self.hl, num=self.k, search_type=self.type, tbs=self.tbs, **kwargs, ) r...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
5fff2bc12059-3
return snippets def _parse_results(self, results: dict) -> str: return " ".join(self._parse_snippets(results)) def _google_serper_api_results( self, search_term: str, search_type: str = "search", **kwargs: Any ) -> dict: headers = { "X-API-KEY": self.serper_api_key or "",...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
5fff2bc12059-4
url, params=params, headers=headers, raise_for_status=True ) as response: search_results = await response.json() return search_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
f60f3b36a9de-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
f60f3b36a9de-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
95563a2d99d6-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
95563a2d99d6-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
95563a2d99d6-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 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
64377c3bb793-0
Source code for langchain.utilities.powerbi """Wrapper around a Power BI endpoint.""" from __future__ import annotations import asyncio import logging import os from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union import aiohttp import requests from aiohttp import ServerTimeoutError from pydanti...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
64377c3bb793-1
"""Fix the table names.""" return [fix_table_name(table) for table in table_names] @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" ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
64377c3bb793-2
"Could not get a token from the supplied credentials." ) from exc raise ClientAuthenticationError("No credential or token supplied.") [docs] def get_table_names(self) -> Iterable[str]: """Get names of tables available.""" return self.table_names [docs] def get_schemas(self)...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
64377c3bb793-3
if table_names not in self.table_names: _LOGGER.warning("Table %s not found in dataset.", table_names) return None return [fix_table_name(table_names)] return self.table_names def _get_tables_todo(self, tables_todo: List[str]) -> List[str]: """...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
64377c3bb793-4
await asyncio.gather(*[self._aget_schema(table) for table in tables_todo]) return self._get_schema_for_tables(tables_requested) def _get_schema(self, table: str) -> None: """Get the schema for a table.""" try: result = self.run( f"EVALUATE TOPN({self.sample_rows_i...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
64377c3bb793-5
def _create_json_content(self, command: str) -> dict[str, Any]: """Create the json content for the request.""" return { "queries": [{"query": rf"{command}"}], "impersonatedUserName": self.impersonated_user_name, "serializerSettings": {"includeNulls": True}, } ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
64377c3bb793-6
) -> str: """Converts a JSON object to a markdown table.""" output_md = "" headers = json_contents[0].keys() for header in headers: header.replace("[", ".").replace("]", "") if table_name: header.replace(f"{table_name}.", "") output_md += f"| {header} " output_md ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
b6c20e01b7c3-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
b6c20e01b7c3-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
b298705f4e34-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
b298705f4e34-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
b298705f4e34-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
921a4674d2f5-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
921a4674d2f5-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
921a4674d2f5-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
921a4674d2f5-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
9c0e129e090f-0
Source code for langchain.utilities.arxiv """Util that calls Arxiv.""" import logging import os 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 aroun...
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
9c0e129e090f-1
class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environment.""" try: import arxiv values["arxiv_search"] =...
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
9c0e129e090f-2
for result in results ] if docs: return "\n\n".join(docs)[: self.doc_content_chars_max] else: return "No good Arxiv Result was found" [docs] def load(self, query: str) -> List[Document]: """ Run Arxiv search and get the article texts plus the article me...
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
9c0e129e090f-3
"doi": result.doi, "primary_category": result.primary_category, "categories": result.categories, "links": [link.href for link in result.links], } else: extra_metadata = {} metadata = { "Pu...
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
c0493d7648ec-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, Tuple from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c0493d7648ec-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
c0493d7648ec-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
c0493d7648ec-3
"parameters": {"ef_construction": ef_construction, "m": m}, }, } } }, } def _default_approximate_search_query( query_vector: List[float], k: int = 4, vector_field: str = "vector_field", ) -> Dict: """For Approximate k-NN Search, this is the def...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c0493d7648ec-4
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: """For Script Scoring Search, this is the default query.""" return { "query": { "script_score":...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c0493d7648ec-5
source = __get_painless_scripting_source(space_type, query_vector) return { "query": { "script_score": { "query": pre_filter, "script": { "source": source, "params": { "field": vector_field, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c0493d7648ec-6
"""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: Bulk API request count; Default: 500 Returns: List ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c0493d7648ec-7
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. Also supports Script Scoring and Painless Scripting. Args...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c0493d7648ec-8
pre_filter: script_score query to pre-filter documents before identifying nearest neighbors; default: {"match_all": {}} Optional Args for Painless Scripting Search: search_type: "painless_scripting"; default: "approximate_search" space_type: "l2Squared", "l1Norm", "cosineSimi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c0493d7648ec-9
if search_type == "approximate_search": boolean_filter = _get_kwargs_value(kwargs, "boolean_filter", {}) subquery_clause = _get_kwargs_value(kwargs, "subquery_clause", "must") lucene_filter = _get_kwargs_value(kwargs, "lucene_filter", {}) if boolean_filter != {} and lucen...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c0493d7648ec-10
embedding, space_type, pre_filter, vector_field ) else: raise ValueError("Invalid `search_type` provided as an argument") response = self.client.search(index=self.index_name, body=search_query) hits = [hit for hit in response["hits"]["hits"][:k]] documents_with_sc...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c0493d7648ec-11
vector_field: Document field embeddings are stored in. Defaults to "vector_field". text_field: Document field the text of the document is stored in. Defaults to "text". Optional Keyword Args for Approximate Search: engine: "nmslib", "faiss", "lucene"; default: "nm...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c0493d7648ec-12
_validate_embeddings_and_bulk_size(len(embeddings), bulk_size) dim = len(embeddings[0]) # Get the index name from either from kwargs or ENV Variable # before falling back to random generation index_name = get_from_dict_or_env( kwargs, "index_name", "OPENSEARCH_INDEX_NAME", de...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
c0493d7648ec-13
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
1e3993815549-0
Source code for langchain.vectorstores.faiss """Wrapper around FAISS vector database.""" from __future__ import annotations import math import os 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 imp...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-1
return faiss def _default_relevance_score_fn(score: float) -> float: """Return a similarity score on a scale [0, 1].""" # The 'correct' relevance function # may differ depending on a few things, including: # - the distance / similarity metric used by the VectorStore # - the scale of your embeddings ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-2
self._normalize_L2 = normalize_L2 def __add( self, texts: Iterable[str], embeddings: Iterable[List[float]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: if not isinstance(self.docstore, AddableMixi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-3
return [_id for _, _id, _ in full_info] [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-4
ids: Optional list of unique IDs. Returns: List of ids from adding the texts into the vectorstore. """ if not isinstance(self.docstore, AddableMixin): raise ValueError( "If trying to add texts, the underlying docstore should support " f"add...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-5
docs.append((doc, scores[0][j])) return docs [docs] def similarity_search_with_score( self, query: str, k: int = 4 ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Docum...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-6
""" docs_and_scores = self.similarity_search_with_score(query, k) return [doc for doc, _ in docs_and_scores] [docs] def max_marginal_relevance_search_by_vector( self, embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwa...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-7
docs = [] for i in selected_indices: if i == -1: # This happens when not enough docs are returned. continue _id = self.index_to_docstore_id[i] doc = self.docstore.search(_id) if not isinstance(doc, Document): raise V...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-8
Add the target FAISS to the current one. Args: target: FAISS object you wish to merge into the current one Returns: None. """ if not isinstance(self.docstore, AddableMixin): raise ValueError("Cannot merge with this type of docstore") # Numerica...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-9
vector = np.array(embeddings, dtype=np.float32) if normalize_L2: faiss.normalize_L2(vector) index.add(vector) documents = [] if ids is None: ids = [str(uuid.uuid4()) for _ in texts] for i, text in enumerate(texts): metadata = metadatas[i] if me...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-10
return cls.__from( texts, embeddings, embedding, metadatas=metadatas, ids=ids, **kwargs, ) [docs] @classmethod def from_embeddings( cls, text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-11
Args: folder_path: folder path to save index, docstore, and index_to_docstore_id to. index_name: for saving with a specific index file name """ path = Path(folder_path) path.mkdir(exist_ok=True, parents=True) # save index separately since it is not...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
1e3993815549-12
docstore, index_to_docstore_id = pickle.load(f) return cls(embeddings.embed_query, index, docstore, index_to_docstore_id) def _similarity_search_with_relevance_scores( self, query: str, k: int = 4, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs a...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
9358d8948c4c-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
9358d8948c4c-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
9358d8948c4c-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
9358d8948c4c-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
9358d8948c4c-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
9358d8948c4c-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
9358d8948c4c-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
9358d8948c4c-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
00a02e02c1f5-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 importlib import json import math import os from abc import ABC, abstractmethod from typing import Any, Dict, Iterable, List, Lite...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
00a02e02c1f5-1
"""Serializes data in json using the json package from python standard library.""" @classmethod def extension(cls) -> str: return "json" def save(self, data: Any) -> None: with open(self.persist_path, "w") as fp: json.dump(data, fp) def load(self) -> Any: with open(se...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
00a02e02c1f5-2
if os.path.exists(self.persist_path): backup_path = str(self.persist_path) + "-backup" os.rename(self.persist_path, backup_path) try: self.pq.write_table(table, self.persist_path) except Exception as exc: os.rename(backup_path, self.persist...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
00a02e02c1f5-3
self._neighbors_fitted = False self._embedding_function = embedding self._persist_path = persist_path self._serializer: Optional[BaseSerializer] = None if self._persist_path is not None: serializer_cls = SERIALIZER_MAP[serializer] self._serializer = serializer_cls...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
00a02e02c1f5-4
self._ids = data["ids"] self._update_neighbors() [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: _texts = list(texts) _ids = ids or [str(uuid4(...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
00a02e02c1f5-5
for idx, dist in zip(neigh_idxs[0], neigh_dists[0]): _idx = int(idx) metadata = {"id": self._ids[_idx], **self._metadatas[_idx]} doc = Document(page_content=self._texts[_idx], metadata=metadata) res.append((doc, dist)) return res [docs] def similarity_search( ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
00a02e02c1f5-6
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html
658aeb7f3185-0
Source code for langchain.vectorstores.vectara """Wrapper around Vectara vector database.""" from __future__ import annotations import json import logging import os from hashlib import md5 from typing import Any, Iterable, List, Optional, Tuple, Type import requests from pydantic import Field from langchain.embeddings....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
658aeb7f3185-1
or self._vectara_api_key is None ): logging.warning( "Cant find Vectara credentials, customer_id or corpus_id in " "environment." ) else: logging.debug(f"Using corpus id {self._vectara_corpus_id}") self._session = requests.Sessi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
658aeb7f3185-2
f"{response.text}" ) return False return True def _index_doc(self, doc_id: str, text: str, metadata: dict) -> bool: request: dict[str, Any] = {} request["customer_id"] = self._vectara_customer_id request["corpus_id"] = self._vectara_corpus_id request["...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html