id
stringlengths
14
15
text
stringlengths
49
2.47k
source
stringlengths
61
166
ebb015d4a065-0
Source code for langchain.utilities.pubmed import json import logging import time import urllib.error import urllib.request from typing import Any, Dict, Iterator, List from pydantic import BaseModel from pydantic.class_validators import root_validator from langchain.schema import Document logger = logging.getLogger(__...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html
ebb015d4a065-1
email: str = "your_email@example.com" @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environment.""" try: import xmltodict values["parse"] = xmltodict.parse except ImportError: raise...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html
ebb015d4a065-2
""" url = ( self.base_url_esearch + "db=pubmed&term=" + str({urllib.parse.quote(query)}) + f"&retmode=json&retmax={self.top_k_results}&usehistory=y" ) result = urllib.request.urlopen(url) text = result.read().decode("utf-8") json_te...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html
ebb015d4a065-3
try: result = urllib.request.urlopen(url) break except urllib.error.HTTPError as e: if e.code == 429 and retry < self.max_retry: # Too Many Requests errors # wait for an exponentially increasing amount of time ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html
8d4f195fb632-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
8d4f195fb632-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
f6543abf5f97-0
Source code for langchain.utilities.spark_sql from __future__ import annotations from typing import TYPE_CHECKING, Any, Iterable, List, Optional if TYPE_CHECKING: from pyspark.sql import DataFrame, Row, SparkSession [docs]class SparkSQL: [docs] def __init__( self, spark_session: Optional[SparkSes...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
f6543abf5f97-1
raise ValueError( f"ignore_tables {missing_tables} not found in database" ) usable_tables = self.get_usable_table_names() self._usable_tables = set(usable_tables) if usable_tables else self._all_tables if not isinstance(sample_rows_in_table_info, int): ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
f6543abf5f97-2
statement = ( self._spark.sql(f"SHOW CREATE TABLE {table}").collect()[0].createtab_stmt ) # Ignore the data source provider and options to reduce the number of tokens. using_clause_index = statement.find("USING") return statement[:using_clause_index] + ";" [docs] def get_t...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
f6543abf5f97-3
except Exception: sample_rows_str = "" return ( f"{self._sample_rows_in_table_info} rows from {table} table:\n" f"{columns_str}\n" f"{sample_rows_str}" ) def _convert_row_as_tuple(self, row: Row) -> tuple: return tuple(map(str, row.asDict().val...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
f6543abf5f97-4
If the statement returns rows, a string of the results is returned. If the statement returns no rows, an empty string is returned. If the statement throws an error, the error message is returned. """ try: from pyspark.errors import PySparkException except ImportError:...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
bec67fb15ff0-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
bec67fb15ff0-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
bec67fb15ff0-2
except ImportError: raise ImportError( "google-api-python-client is not installed. " "Please install it with `pip install google-api-python-client`" ) service = build("customsearch", "v1", developerKey=google_api_key) values["search_engine"] = serv...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
bec67fb15ff0-3
for result in results: metadata_result = { "title": result["title"], "link": result["link"], } if "snippet" in result: metadata_result["snippet"] = result["snippet"] metadata_results.append(metadata_result) return me...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
0791f68536d4-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
0791f68536d4-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
0791f68536d4-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
0791f68536d4-3
return ["No good Google Search Result was found"] 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: heade...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
0791f68536d4-4
else: async with self.aiosession.post( url, params=params, headers=headers, raise_for_status=True ) as response: search_results = await response.json() return search_results
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
f7b9c4be654e-0
Source code for langchain.utilities.requests """Lightweight wrapper around requests library, with async support.""" from contextlib import asynccontextmanager from typing import Any, AsyncGenerator, Dict, Optional import aiohttp import requests from pydantic import BaseModel, Extra [docs]class Requests(BaseModel): ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html
f7b9c4be654e-1
"""PUT the URL and return the text.""" return requests.put( url, json=data, headers=self.headers, auth=self.auth, **kwargs ) [docs] def delete(self, url: str, **kwargs: Any) -> requests.Response: """DELETE the URL and return the text.""" return requests.delete(url, headers...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html
f7b9c4be654e-2
async with self._arequest( "POST", url, json=data, auth=self.auth, **kwargs ) as response: yield response [docs] @asynccontextmanager async def apatch( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """PAT...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html
f7b9c4be654e-3
auth: Optional[Any] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def requests(self) -> Requests: return Requests( headers=self.headers, aiosession=self.aiosession, auth=self.auth ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html
f7b9c4be654e-4
return await response.text() [docs] async def apost(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """POST to the URL and return the text asynchronously.""" async with self.requests.apost(url, data, **kwargs) as response: return await response.text() [docs] async def apat...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html
53c948c7b757-0
Source code for langchain.utilities.python import functools import logging import multiprocessing import sys from io import StringIO from typing import Dict, Optional from pydantic import BaseModel, Field logger = logging.getLogger(__name__) @functools.lru_cache(maxsize=None) def warn_once() -> None: """Warn once a...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/python.html
53c948c7b757-1
# create a Process p = multiprocessing.Process( target=self.worker, args=(command, self.globals, self.locals, queue) ) # start it p.start() # wait for the process to finish or kill it after timeout seconds p.join(timeout) ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/python.html
942c4222da1f-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
942c4222da1f-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
942c4222da1f-2
"snippet": result["snippet"], "title": result["name"], "link": result["url"], } metadata_results.append(metadata_result) return metadata_results
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
edcdce27712b-0
Source code for langchain.utilities.google_places_api """Chain that calls Google Places API. """ import logging from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class GooglePlacesAPIWrapper(BaseModel): """Wrapper arou...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
edcdce27712b-1
except ImportError: raise ImportError( "Could not import googlemaps python package. " "Please install it with `pip install googlemaps`." ) return values [docs] def run(self, query: str) -> str: """Run Places search and get k number of places tha...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
edcdce27712b-2
"formatted_address", "Unknown" ) phone_number = place_details.get("result", {}).get( "formatted_phone_number", "Unknown" ) website = place_details.get("result", {}).get("website", "Unknown") place_id = place_details.get("result", {}).get("place...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
c8c641347a0b-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. To use, you should have the ``boto3`` package installed an...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html
c8c641347a0b-1
result. Args: query: an input to passed to the lambda function as the ``body`` of a JSON object. """ # noqa: E501 res = self.lambda_client.invoke( FunctionName=self.function_name, InvocationType="RequestResponse", P...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html
589163dc47fe-0
Source code for langchain.utilities.wikipedia """Util that calls Wikipedia.""" import logging from typing import Any, Dict, List, Optional from pydantic import BaseModel, root_validator from langchain.schema import Document logger = logging.getLogger(__name__) WIKIPEDIA_MAX_QUERY_LENGTH = 300 [docs]class WikipediaAPIWr...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
589163dc47fe-1
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_chars_max] @staticmethod def _formatted_page_summary(...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
589163dc47fe-2
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 Returns: a list of documents. """ page_titles = sel...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
61ba19f23a41-0
Source code for langchain.utilities.loading """Utilities for loading configurations from langchain-hub.""" import os import re import tempfile from pathlib import Path, PurePosixPath from typing import Any, Callable, Optional, Set, TypeVar, Union from urllib.parse import urljoin import requests DEFAULT_REF = os.environ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/loading.html
61ba19f23a41-1
# when working with URLs that use forward slashes as the path separator. # Instead, use PurePosixPath to ensure that forward slashes are used as the # path separator, regardless of the operating system. full_url = urljoin(URL_BASE.format(ref=ref), PurePosixPath(remote_path).__str__()) r = requests.get(f...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/loading.html
4e65d30f0975-0
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...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
4e65d30f0975-1
return ["No good DuckDuckGo Search Result was found"] snippets = [] for i, res in enumerate(results, 1): if res is not None: snippets.append(res["body"]) if len(snippets) == self.max_results: break return snippets [d...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
4e65d30f0975-2
"link": result["url"], } return { "snippet": result["body"], "title": result["title"], "link": result["href"], } formatted_results = [] for i, res in enumerate(results, 1): ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
2980619baffa-0
Source code for langchain.utilities.redis from __future__ import annotations import logging from typing import ( TYPE_CHECKING, Any, ) from urllib.parse import urlparse if TYPE_CHECKING: from redis.client import Redis as RedisType logger = logging.getLogger(__name__) [docs]def get_client(redis_url: str, **k...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html
2980619baffa-1
.. code-block:: python from langchain.utilities.redis import get_client redis_client = get_client( redis_url="redis+sentinel://username:password@sentinelhost:26379/mymaster/0" index_name="my-index", embedding_function=embeddings.embed_query, ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html
2980619baffa-2
to use different data for authentication on booth systems. """ import redis parsed_url = urlparse(redis_url) # sentinel needs list with (host, port) tuple, use default port if none available sentinel_list = [(parsed_url.hostname or "localhost", parsed_url.port or 26379)] if parsed_url.path: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html
2980619baffa-3
sentinel_client.execute_command("ping") except redis.exceptions.AuthenticationError as ae: if "no password is set" in ae.args[0]: logger.warning( "Redis sentinel connection configured with password but Sentinel \ answered NO PASSWORD NEEDED - Please check Sentinel configuration" ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html
4f19bbbd8a4f-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, Optional import aiohttp import requests from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_d...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
4f19bbbd8a4f-1
"useAutoprompt": use_autoprompt, } response = requests.post( # type: ignore f"{METAPHOR_API_URL}/search", headers=headers, json=params, ) response.raise_for_status() search_results = response.json() return search_results["re...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
4f19bbbd8a4f-2
start_crawl_date: If specified, only pages we crawled after start_crawl_date will be returned. end_crawl_date: If specified, only pages we crawled before end_crawl_date will be returned. start_published_date: If specified, only pages published after start_published_date will be returned. ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
4f19bbbd8a4f-3
end_published_date: Optional[str] = None, use_autoprompt: Optional[bool] = None, ) -> List[Dict]: """Get results from the Metaphor Search API asynchronously.""" # Function to perform the API call async def fetch() -> str: headers = {"X-Api-Key": self.metaphor_api_key} ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
d616531287d9-0
Source code for langchain.utilities.vertexai """Utilities to init Vertex AI.""" from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from google.auth.credentials import Credentials [docs]def raise_vertex_import_error(minimum_expected_version: str = "1.26.1") -> None: """Raise ImportError related to Vert...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/vertexai.html
dba00f94a383-0
Source code for langchain.utilities.golden_query """Util that calls Golden.""" import json from typing import Dict, Optional import requests from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env GOLDEN_BASE_URL = "https://golden.com" GOLDEN_TIMEOUT = 5000 [docs]class Gol...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/golden_query.html
dba00f94a383-1
content = json.loads(response.content) query_id = content["id"] response = requests.get( ( f"{GOLDEN_BASE_URL}/api/v2/public/queries/{query_id}/results/" "?pageSize=10" ), headers=headers, timeout=GOLDEN_TIMEOUT, ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/golden_query.html
8a9845f9afc2-0
Source code for langchain.utilities.scenexplain """Util that calls SceneXplain. In order to set this up, you need API key for the SceneXplain API. You can obtain a key by following the steps below. - Sign up for a free account at https://scenex.jina.ai/. - Navigate to the API Access page (https://scenex.jina.ai/api) an...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html
8a9845f9afc2-1
"languages": ["en"], } ] } response = requests.post(self.scenex_api_url, headers=headers, json=payload) response.raise_for_status() result = response.json().get("result", []) img = result[0] if result else {} return img.get("text", "") @roo...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html
b426d027bd77-0
Source code for langchain.utilities.max_compute from __future__ import annotations from typing import TYPE_CHECKING, Iterator, List, Optional from langchain.utils import get_from_env if TYPE_CHECKING: from odps import ODPS [docs]class MaxComputeAPIWrapper: """Interface for querying Alibaba Cloud MaxCompute tabl...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html
b426d027bd77-1
"https://pyodps.readthedocs.io/." ) from ex access_id = access_id or get_from_env("access_id", "MAX_COMPUTE_ACCESS_ID") secret_access_key = secret_access_key or get_from_env( "secret_access_key", "MAX_COMPUTE_SECRET_ACCESS_KEY" ) client = ODPS( access_...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html
8b4fcdb12aaa-0
Source code for langchain.utilities.dataforseo_api_search import base64 from typing import Dict, Optional from urllib.parse import quote import aiohttp import requests from pydantic import BaseModel, Extra, Field, root_validator from langchain.utils import get_from_dict_or_env [docs]class DataForSeoAPIWrapper(BaseModel...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html
8b4fcdb12aaa-1
"""Validate that login and password exists in environment.""" login = get_from_dict_or_env(values, "api_login", "DATAFORSEO_LOGIN") password = get_from_dict_or_env(values, "api_password", "DATAFORSEO_PASSWORD") values["api_login"] = login values["api_password"] = password return ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html
8b4fcdb12aaa-2
data = [obj] _url = ( f"https://api.dataforseo.com/v3/serp/{obj['se_name']}" f"/{obj['se_type']}/live/advanced" ) return { "url": _url, "headers": headers, "data": data, } def _check_response(self, response: dict) -> dict: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html
8b4fcdb12aaa-3
request_details["url"], headers=request_details["headers"], json=request_details["data"], ) as response: res = await response.json() return self._check_response(res) def _filter_results(self, res: dict) -> list: output = [] types = ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html
8b4fcdb12aaa-4
return d def _process_response(self, res: dict) -> str: """Process response from DataForSEO SERP API.""" toret = "No good search result found" for task in res.get("tasks", []): for result in task.get("result", []): item_types = result.get("item_types") ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html
7ae992da6e07-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): """Messaging Client using Twilio. To use, you should hav...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
7ae992da6e07-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
7ae992da6e07-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
e333fa840a4f-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
e333fa840a4f-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
e333fa840a4f-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
e333fa840a4f-3
toret = res["answer_box"]["answer"] elif "answer_box" in res.keys() and "snippet" in res["answer_box"].keys(): toret = res["answer_box"]["snippet"] elif ( "answer_box" in res.keys() and "snippet_highlighted_words" in res["answer_box"].keys() ): tor...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
74e8cb33e00c-0
Source code for langchain.utilities.brave_search import json from typing import List import requests from pydantic import BaseModel, Field from langchain.schema import Document [docs]class BraveSearchWrapper(BaseModel): """Wrapper around the Brave search engine.""" api_key: str """The API key to use for the...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/brave_search.html
74e8cb33e00c-1
) for item in results ] def _search_request(self, query: str) -> List[dict]: headers = { "X-Subscription-Token": self.api_key, "Accept": "application/json", } req = requests.PreparedRequest() params = {**self.search_kwargs, **{"q": query}} ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/brave_search.html
d6b678789e4b-0
Source code for langchain.utilities.zapier """Util that can interact with Zapier NLA. Full docs here: https://nla.zapier.com/start/ Note: this wrapper currently only implemented the `api_key` auth method for testing and server-side production use cases (using the developer's connected accounts on Zapier.com) For use-ca...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
d6b678789e4b-1
your own provider and generate credentials. """ zapier_nla_api_key: str zapier_nla_oauth_access_token: str zapier_nla_api_base: str = "https://nla.zapier.com/api/v1/" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def _format_headers(self) -> Dic...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
d6b678789e4b-2
{ "instructions": instructions, } ) if preview_only: data.update({"preview_only": True}) return data def _create_action_url(self, action_id: str) -> str: """Create a url for an action.""" return self.zapier_nla_api_base + f"exposed/{act...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
d6b678789e4b-3
return values [docs] async def alist(self) -> List[Dict]: """Returns a list of all exposed (enabled) actions associated with current user (associated with the set api_key). Change your exposed actions here: https://nla.zapier.com/demo/start/ The return list can be empty if no actions ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
d6b678789e4b-4
""" session = self._get_session() try: response = session.get(self.zapier_nla_api_base + "exposed/") response.raise_for_status() except requests.HTTPError as http_err: if response.status_code == 401: if self.zapier_nla_oauth_access_token: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
d6b678789e4b-5
) -> Dict: """Executes an action that is identified by action_id, must be exposed (enabled) by the current user (associated with the set api_key). Change your exposed actions here: https://nla.zapier.com/demo/start/ The return JSON is guaranteed to be less than ~500 words (350 to...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
d6b678789e4b-6
response = await self._arequest( "POST", self._create_action_url(action_id), json=self._create_action_payload(instructions, params, preview_only=True), ) return response["result"] [docs] def run_as_str(self, *args, **kwargs) -> str: # type: ignore[no-untyped-def] ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
d6b678789e4b-7
"""Same as list, but returns a stringified version of the JSON for insertting back into an LLM.""" actions = self.list() return json.dumps(actions) [docs] async def alist_as_str(self) -> str: # type: ignore[no-untyped-def] """Same as list, but returns a stringified version of the JSO...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
d0fcb01caa78-0
Source code for langchain.utilities.bash """Wrapper around subprocess to run commands.""" from __future__ import annotations import platform import re import subprocess from typing import TYPE_CHECKING, List, Union from uuid import uuid4 if TYPE_CHECKING: import pexpect [docs]class BashProcess: """ Wrapper ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html
d0fcb01caa78-1
self.process = None if persistent: self.prompt = str(uuid4()) self.process = self._initialize_persistent_process(self, self.prompt) @staticmethod def _lazy_import_pexpect() -> pexpect: """Import pexpect only when needed.""" if platform.system() == "Windows": ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html
d0fcb01caa78-2
execute in the session """ # noqa: E501 if isinstance(commands, str): commands = [commands] commands = ";".join(commands) if self.process is not None: return self._run_persistent( commands, ) else: return self._run(...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html
d0fcb01caa78-3
pexpect = self._lazy_import_pexpect() if self.process is None: raise ValueError("Process not initialized") self.process.sendline(command) # Clear the output with an empty string self.process.expect(self.prompt, timeout=10) self.process.sendline("") try: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html
c22237a8d52c-0
Source code for langchain.utilities.jira """Util that calls Jira.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env # TODO: think about error handling, more specific api specs, and jql/project limits [docs]class JiraAPI...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
c22237a8d52c-1
) jira = Jira( url=jira_instance_url, username=jira_username, password=jira_api_token, cloud=True, ) confluence = Confluence( url=jira_instance_url, username=jira_username, password=jira_api_token, cl...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
c22237a8d52c-2
parsed.append( { "key": key, "summary": summary, "created": created, "assignee": assignee, "priority": priority, "status": status, "related_issues": rel_issues, ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
c22237a8d52c-3
) params = json.loads(query) return self.jira.issue_create(fields=dict(params)) [docs] def page_create(self, query: str) -> str: try: import json except ImportError: raise ImportError( "json is not installed. Please install it with `pip install ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
09de49cb97ce-0
Source code for langchain.utilities.github """Util that calls GitHub.""" from __future__ import annotations import json from typing import TYPE_CHECKING, Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env if TYPE_CHECKING: from github.Iss...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html
09de49cb97ce-1
try: from github import Auth, GithubIntegration except ImportError: raise ImportError( "PyGithub is not installed. " "Please install it with `pip install PyGithub`" ) with open(github_app_private_key, "r") as f: private_key ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html
09de49cb97ce-2
and each issue's title and number. """ issues = self.github_repo_instance.get_issues(state="open") if issues.totalCount > 0: parsed_issues = self.parse_issues(issues) parsed_issues_str = ( "Found " + str(len(parsed_issues)) + " issues:\n" + str(parsed_issu...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html
09de49cb97ce-3
in the string, and the body are the rest of the string. For example, "Updated README\nmade changes to add info" Returns: str: A success or failure message """ if self.github_base_branch == self.github_branch: return """Cannot make a pull request because ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html
09de49cb97ce-4
return "Unable to make comment due to error:\n" + str(e) [docs] def create_file(self, file_query: str) -> str: """ Creates a new file on the Github repo Parameters: file_query(str): a string which contains the file path and the file contents. The file path is the first...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html
09de49cb97ce-5
""" Updates a file with new content. Parameters: file_query(str): Contains the file path and the file contents. The old file contents is wrapped in OLD <<<< and >>>> OLD The new file contents is wrapped in NEW <<<< and >>>> NEW For example: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html
09de49cb97ce-6
""" Deletes a file from the repo Parameters: file_path(str): Where the file is Returns: str: Success or failure message """ try: file = self.github_repo_instance.get_contents(file_path) self.github_repo_instance.delete_file( ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html
1396f7bbe358-0
Source code for langchain.utilities.openweathermap """Util that calls OpenWeatherMap using PyOWM.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class OpenWeatherMapAPIWrapper(BaseModel): """Wrapper for OpenWeath...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
1396f7bbe358-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
d95854e69880-0
Source code for langchain.utilities.portkey import json import os from typing import Dict, Optional [docs]class Portkey: base = "https://api.portkey.ai/v1/proxy" [docs] @staticmethod def Config( api_key: str, trace_id: Optional[str] = None, environment: Optional[str] = None, u...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/portkey.html
d95854e69880-1
headers["x-portkey-trace-id"] = trace_id if retry_count: headers["x-portkey-retry-count"] = str(retry_count) if cache: headers["x-portkey-cache"] = cache if cache_force_refresh: headers["x-portkey-cache-force-refresh"] = cache_force_refresh if cache_ag...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/portkey.html
d25444482d96-0
Source code for langchain.utilities.tensorflow_datasets import logging from typing import Any, Callable, Dict, Iterator, List, Optional from pydantic import BaseModel, root_validator from langchain.schema import Document logger = logging.getLogger(__name__) [docs]class TensorflowDatasets(BaseModel): """Access to th...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html