id stringlengths 14 16 | source stringlengths 49 117 | text stringlengths 16 2.73k |
|---|---|---|
9563fec48070-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html | "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 that exists that match."""
search_results = self.google_map_cl... |
9563fec48070-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html | "formatted_phone_number", "Unknown"
)
website = place_details.get("result", {}).get("website", "Unknown")
formatted_details = (
f"{name}\nAddress: {address}\n"
f"Phone: {phone_number}\nWebsite: {website}\n\n"
)
return formatted_... |
3caf9a6a52e5-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html | Source code for langchain.utilities.graphql
import json
from typing import Any, Callable, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
[docs]class GraphQLAPIWrapper(BaseModel):
"""Wrapper around GraphQL API.
To use, you should have the ``gql`` python package installed.
This wrapper w... |
3caf9a6a52e5-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html | def _execute_query(self, query: str) -> Dict[str, Any]:
"""Execute a GraphQL query and return the results."""
document_node = self.gql_function(query)
result = self.gql_client.execute(document_node)
return result
By Harrison Chase
© Copyright 2023, Harrison Chase.
Las... |
2f7b61be0025-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html | Source code for langchain.utilities.duckduckgo_search
"""Util that calls DuckDuckGo Search.
No setup required. Free.
https://pypi.org/project/duckduckgo-search/
"""
from typing import Dict, List, Optional
from pydantic import BaseModel, Extra
from pydantic.class_validators import root_validator
[docs]class DuckDuckGoSe... |
2f7b61be0025-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html | return ["No good DuckDuckGo Search Result was found"]
snippets = [result["body"] for result in results]
return snippets
[docs] def run(self, query: str) -> str:
snippets = self.get_snippets(query)
return " ".join(snippets)
[docs] def results(self, query: str, num_results: int) -> L... |
b91fc335bafb-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html | Source code for langchain.utilities.apify
from typing import Any, Callable, Dict, Optional
from pydantic import BaseModel, root_validator
from langchain.document_loaders import ApifyDatasetLoader
from langchain.document_loaders.base import Document
from langchain.utils import get_from_dict_or_env
[docs]class ApifyWrapp... |
b91fc335bafb-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html | 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... |
b91fc335bafb-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html | ) -> 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 input object of the Actor that you're trying to run.
dataset_mapping_functio... |
3e0dc7c7b266-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html | 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 ... |
3e0dc7c7b266-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html | [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`, this parameter
must be empty.
""" # noqa: E501
class Config:
... |
3e0dc7c7b266-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html | [Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses)
for other 3rd-party channels.
""" # noqa: E501
message = self.client.messages.create(to, from_=self.from_number, body=body)
return message.sid
By Harrison Chase
© Copyright 2023, Harris... |
19ce9e5ae33d-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html | 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:/... |
19ce9e5ae33d-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html | 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/search_api.html>`_ parameters to the
:py:class:`SearxSearchWrapper` instan... |
19ce9e5ae33d-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html | # select github the conventional google search syntax
s.run("large language models", query_suffix="site:github.com")
*NOTE*: A search suffix can be defined on both the instance and the method level.
The resulting query will be the concatenation of the two with the former taking
precedence.
See `SearxNG Configur... |
19ce9e5ae33d-3 | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html | """Take a raw result from Searx and make it into a dict like object."""
json_data = json.loads(data)
super().__init__(json_data)
self.__dict__ = self
def __str__(self) -> str:
"""Text representation of searx result."""
return self._data
@property
def results(self) -> ... |
19ce9e5ae33d-4 | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html | _result: SearxResults = PrivateAttr()
searx_host: str = ""
unsecure: bool = False
params: dict = Field(default_factory=_get_default_params)
headers: Optional[dict] = None
engines: Optional[List[str]] = []
categories: Optional[List[str]] = []
query_suffix: Optional[str] = ""
k: int = 10
... |
19ce9e5ae33d-5 | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html | elif searx_host.startswith("http://"):
values["unsecure"] = True
cls.disable_ssl_warnings(True)
values["searx_host"] = searx_host
return values
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
def _searx_api_query(self, para... |
19ce9e5ae33d-6 | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html | raise ValueError("Searx API returned an error: ", response.text)
result = SearxResults(await response.text())
self._result = result
return result
[docs] def run(
self,
query: str,
engines: Optional[List[str]] = None,
categories: Optional[List[st... |
19ce9e5ae33d-7 | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html | if self.query_suffix and len(self.query_suffix) > 0:
params["q"] += " " + self.query_suffix
if isinstance(query_suffix, str) and len(query_suffix) > 0:
params["q"] += " " + query_suffix
if isinstance(engines, list) and len(engines) > 0:
params["engines"] = ",".join(en... |
19ce9e5ae33d-8 | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html | if isinstance(engines, list) and len(engines) > 0:
params["engines"] = ",".join(engines)
res = await self._asearx_api_query(params)
if len(res.answers) > 0:
toret = res.answers[0]
# only return the content of the results list
elif len(res.results) > 0:
... |
19ce9e5ae33d-9 | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html | }
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) and len(query_suffix) > 0:
params["q"] += " " + query_suffix
if isinstance(engines, list) a... |
19ce9e5ae33d-10 | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html | params["q"] += " " + self.query_suffix
if isinstance(query_suffix, str) and len(query_suffix) > 0:
params["q"] += " " + query_suffix
if isinstance(engines, list) and len(engines) > 0:
params["engines"] = ",".join(engines)
results = (await self._asearx_api_query(params)).r... |
60f5fdf1fa31-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html | 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.
... |
60f5fdf1fa31-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html | 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.google.com/apis/library/customsearch.googleapis
.com
"""
... |
60f5fdf1fa31-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html | "Please install it with `pip install google-api-python-client`"
)
service = build("customsearch", "v1", developerKey=google_api_key)
values["search_engine"] = service
return values
[docs] def run(self, query: str) -> str:
"""Run query through GoogleSearch and parse result.... |
60f5fdf1fa31-3 | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html | Last updated on Jun 04, 2023. |
12ae5f121400-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html | 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... |
12ae5f121400-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html | 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 Wikipedia Search Result was found"
return "\n\n".join(summaries)[: self.doc_content... |
12ae5f121400-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html | [docs] def load(self, query: str) -> List[Document]:
"""
Run Wikipedia search and get the article text plus the meta information.
See
Returns: a list of documents.
"""
page_titles = self.wiki_client.search(query[:WIKIPEDIA_MAX_QUERY_LENGTH])
docs = []
f... |
60a3bcd731fa-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html | 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... |
60a3bcd731fa-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html | 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:
return f"Result: {answer}"
By Harrison Chase
© Copyright 2023, Harrison Chase.
... |
631996eefe56-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html | 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 ... |
631996eefe56-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html | 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"] = serper_api_key
return values
[docs] def results(se... |
631996eefe56-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html | 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,
)
return self._parse_results(results)
def _parse_snippets(self, resu... |
631996eefe56-3 | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html | 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 "",
"Content-Type": "application/json",
}
params = ... |
631996eefe56-4 | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
72eb2045e73c-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html | 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... |
72eb2045e73c-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html | 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 assumption alone if answer is empty
ret... |
903eac7c8a90-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html | 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... |
903eac7c8a90-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html | 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",
# default="https://api.bing.microsoft.com/v7.0/... |
903eac7c8a90-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html | metadata_results.append(metadata_result)
return metadata_results
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
6b729b19d51e-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html | 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... |
6b729b19d51e-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html | 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" in values or "credential" in values... |
6b729b19d51e-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html | 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) -> str:
"""Get the available schema's."""
if self.schemas:
re... |
6b729b19d51e-3 | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html | return None
return [fix_table_name(table_names)]
return self.table_names
def _get_tables_todo(self, tables_todo: List[str]) -> List[str]:
"""Get the tables that still need to be queried."""
return [table for table in tables_todo if table not in self.schemas]
def _get_sche... |
6b729b19d51e-4 | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html | """Get the schema for a table."""
try:
result = self.run(
f"EVALUATE TOPN({self.sample_rows_in_table_info}, {table})"
)
self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"])
except Timeout:
_LOGGER.warning("Timeout whi... |
6b729b19d51e-5 | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html | }
[docs] def run(self, command: str) -> Any:
"""Execute a DAX command and return a json representing the results."""
_LOGGER.debug("Running command: %s", command)
result = requests.post(
self.request_url,
json=self._create_json_content(command),
headers=sel... |
6b729b19d51e-6 | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html | for row in json_contents:
for value in row.values():
output_md += f"| {value} "
output_md += "|\n"
return output_md
def fix_table_name(table: str) -> str:
"""Add single quotes around table names that contain spaces."""
if " " in table and not table.startswith("'") and not table.e... |
732d2e1fbcbd-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html | 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... |
732d2e1fbcbd-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html | 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"Temperature: \n"
f" - Current: {temperature['temp'... |
52240d76c587-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html | 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... |
52240d76c587-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html | """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... |
52240d76c587-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html | "title": result["title"],
"url": result["url"],
"author": result["author"],
"date_created": result["dateCreated"],
}
)
return cleaned_results
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updat... |
c7ede578f60a-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html | 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... |
c7ede578f60a-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html | """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 package exists in environment."""
serpapi_api_key = get_from_dict_or_env(
... |
c7ede578f60a-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html | params = self.get_params(query)
params["source"] = "python"
if self.serpapi_api_key:
params["serp_api_key"] = self.serpapi_api_key
params["output"] = "json"
url = "https://serpapi.com/search"
return url, params
url, params = construct_u... |
c7ede578f60a-3 | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html | toret = res["answer_box"]["snippet_highlighted_words"][0]
elif (
"sports_results" in res.keys()
and "game_spotlight" in res["sports_results"].keys()
):
toret = res["sports_results"]["game_spotlight"]
elif (
"shopping_results" in res.keys()
... |
ef2cd8c5060b-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html | Source code for langchain.utilities.pupmed
import json
import logging
import time
import urllib.error
import urllib.request
from typing import List
from pydantic import BaseModel, Extra
from langchain.schema import Document
logger = logging.getLogger(__name__)
[docs]class PubMedAPIWrapper(BaseModel):
"""
Wrappe... |
ef2cd8c5060b-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html | """
Run PubMed search and get the article meta information.
See https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch
It uses only the most informative fields of article meta information.
"""
try:
# Retrieve the top-k results for the query
docs = [... |
ef2cd8c5060b-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html | def _transform_doc(self, doc: dict) -> Document:
summary = doc.pop("summary")
return Document(page_content=summary, metadata=doc)
[docs] def load_docs(self, query: str) -> List[Document]:
document_dicts = self.load(query=query)
return [self._transform_doc(d) for d in document_dicts]
[... |
ef2cd8c5060b-3 | https://python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html | if "<AbstractText>" in xml_text and "</AbstractText>" in xml_text:
start_tag = "<AbstractText>"
end_tag = "</AbstractText>"
abstract = xml_text[
xml_text.index(start_tag) + len(start_tag) : xml_text.index(end_tag)
]
# Get publication date
p... |
907d58a26986-0 | https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html | 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... |
907d58a26986-1 | https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html | 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"] = arxiv.Search
values["arxiv_exceptions"] = (
arx... |
907d58a26986-2 | https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html | 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 meta information.
See https://lukasschwab.me/arxiv.py/index.html#Search
Returns: a list of documents with the document.page_cont... |
907d58a26986-3 | https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html | metadata = {
"Published": str(result.updated.date()),
"Title": result.title,
"Authors": ", ".join(a.name for a in result.authors),
"Summary": result.summary,
**extra_metadata,
}
doc = Document(
page_c... |
1d753b2de670-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | 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
... |
1d753b2de670-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | 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_bulk_size(embeddings_length: int, bulk_size: int) -> None... |
1d753b2de670-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | text_field: text,
"metadata": metadata,
"_id": _id,
}
requests.append(request)
ids.append(_id)
bulk(client, requests)
client.indices.refresh(index=index_name)
return ids
def _default_scripting_text_mapping(
dim: int,
vector_field: str = "vector_field",... |
1d753b2de670-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | query_vector: List[float],
k: int = 4,
vector_field: str = "vector_field",
) -> Dict:
"""For Approximate k-NN Search, this is the default query."""
return {
"size": k,
"query": {"knn": {vector_field: {"vector": query_vector, "k": k}}},
}
def _approximate_search_query_with_boolean_fil... |
1d753b2de670-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | vector_field: str = "vector_field",
) -> Dict:
"""For Script Scoring Search, this is the default query."""
return {
"query": {
"script_score": {
"query": pre_filter,
"script": {
"source": "knn_score",
"lang": "knn",
... |
1d753b2de670-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | "field": vector_field,
"query_value": query_vector,
},
},
}
}
}
def _get_kwargs_value(kwargs: Any, key: str, default_value: Any) -> Any:
"""Get the value of the key if present. Else get the default_value."""
if key in kwargs:
... |
1d753b2de670-6 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | List of ids from adding the texts into the vectorstore.
Optional Args:
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".
"""
embe... |
1d753b2de670-7 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most similar to the query.
Optional Args:
vector_field: Document field embeddings are stored in. Defaults to
"vector_field".
text_field: Document field the text of the document is ... |
1d753b2de670-8 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | nearest neighbors; default: {"match_all": {}}
"""
docs_with_scores = self.similarity_search_with_score(query, k, **kwargs)
return [doc[0] for doc in docs_with_scores]
[docs] def similarity_search_with_score(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[Document, flo... |
1d753b2de670-9 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | search_query = _approximate_search_query_with_boolean_filter(
embedding,
boolean_filter,
k=k,
vector_field=vector_field,
subquery_clause=subquery_clause,
)
elif lucene_filter != {}:
... |
1d753b2de670-10 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | )
for hit in hits
]
return documents_with_scores
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
bulk_size: int = 500,
**kwargs: Any,
) -> OpenSearchVectorSear... |
1d753b2de670-11 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | 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 100; default: 16
Keyword Args for Script Scoring or Painless Scripting:
... |
1d753b2de670-12 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html | 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 = _get_kwargs_value(kwargs, "m", 16)
mapping = _default_text_mapping(
d... |
10caea1e10ff-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | 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... |
10caea1e10ff-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | """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 (OpenAI's are unit normed. Many others are not!)
# - embedding dimens... |
10caea1e10ff-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | embeddings: Iterable[List[float]],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
if not isinstance(self.docstore, AddableMixin):
raise ValueError(
"If trying to add texts, the underlying docstore sh... |
10caea1e10ff-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | ids: Optional[List[str]] = None,
**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.
... |
10caea1e10ff-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | f"adding items, which {self.docstore} does not"
)
# Embed and create the documents.
texts, embeddings = zip(*text_embeddings)
return self.__add(texts, embeddings, metadatas=metadatas, ids=ids, **kwargs)
[docs] def similarity_search_with_score_by_vector(
self, embedding: Li... |
10caea1e10ff-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most similar to the query and score for each
"""
embedding = self.embedding_function(query)
docs = self.similarity_search_with_score_by_vector(embedding, k)
return docs
[docs] def similarit... |
10caea1e10ff-6 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | """Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
... |
10caea1e10ff-7 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
query:... |
10caea1e10ff-8 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | for i, target_id in target.index_to_docstore_id.items():
doc = target.docstore.search(target_id)
if not isinstance(doc, Document):
raise ValueError("Document should be returned")
full_info.append((starting_len + i, target_id, doc))
# Add information to docstor... |
10caea1e10ff-9 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | normalize_L2=normalize_L2,
**kwargs,
)
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> FAISS:
"""Construct... |
10caea1e10ff-10 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | This is intended to be a quick way to get started.
Example:
.. code-block:: python
from langchain import FAISS
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text_embeddings = embeddings.embed_document... |
10caea1e10ff-11 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | def load_local(
cls, folder_path: str, embeddings: Embeddings, index_name: str = "index"
) -> FAISS:
"""Load FAISS index, docstore, and index_to_docstore_id from disk.
Args:
folder_path: folder path to load index, docstore,
and index_to_docstore_id from.
... |
10caea1e10ff-12 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html | © Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
e08c16c4f1fb-0 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html | 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... |
e08c16c4f1fb-1 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html | 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:
import nomic
from nomic import AtlasProject
except Im... |
e08c16c4f1fb-2 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html | refresh(bool): Whether or not to refresh indices with the updated data.
Default True.
Returns:
List[str]: List of IDs of the added texts.
"""
if (
metadatas is not None
and len(metadatas) > 0
and "text" in metadatas[0].keys()
... |
e08c16c4f1fb-3 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html | metadatas[i]["text"] = texts
metadatas[i][AtlasDB._ATLAS_DEFAULT_ID_FIELD] = ids[i]
data = metadatas
self.project._validate_map_data_inputs(
[], id_field=AtlasDB._ATLAS_DEFAULT_ID_FIELD, data=data
)
with self.project.wait_for_projec... |
e08c16c4f1fb-4 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html | neighbors, _ = self.project.projections[0].vector_search(
queries=embedding, k=k
)
datas = self.project.get_data(ids=neighbors[0])
docs = [
Document(page_content=datas[i]["text"], metadata=datas[i])
for i, neighbor in enumerate(neighbors)
]... |
e08c16c4f1fb-5 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html | already exists. Default False.
Generally userful during development and testing.
index_kwargs (Optional[dict]): Dict of kwargs for index creation.
See https://docs.nomic.ai/atlas_api.html
Returns:
AtlasDB: Nomic's neural database and finest rhizomatic inst... |
e08c16c4f1fb-6 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html | **kwargs: Any,
) -> AtlasDB:
"""Create an AtlasDB vectorstore from a list of documents.
Args:
name (str): Name of the collection to create.
api_key (str): Your nomic API key,
documents (List[Document]): List of documents to add to the vectorstore.
embe... |
e08c16c4f1fb-7 | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html | Last updated on Jun 04, 2023. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.