id
stringlengths
14
15
text
stringlengths
44
2.47k
source
stringlengths
61
181
20a3d774d986-1
} if isinstance(input, dict): # the input could be a dict[string, string], so we sanitize the values values = list() # get the values from the dict for key in input: values.append(input[key]) # sanitize the values sanitize_values_response: op.SanitizeRespo...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/opaqueprompts.html
cb8ca617d8e6-0
Source code for langchain.utilities.searchapi from typing import Any, Dict, Optional import aiohttp import requests from langchain.pydantic_v1 import BaseModel, root_validator from langchain.utils import get_from_dict_or_env [docs]class SearchApiAPIWrapper(BaseModel): """ Wrapper around SearchApi API. To us...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html
cb8ca617d8e6-1
results = await self.aresults(query, **kwargs) return self._result_as_string(results) [docs] def results(self, query: str, **kwargs: Any) -> dict: results = self._search_api_results(query, **kwargs) return results [docs] async def aresults(self, query: str, **kwargs: Any) -> dict: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html
cb8ca617d8e6-2
url=request_details["url"], headers=request_details["headers"], params=request_details["params"], raise_for_status=True, ) as response: results = await response.json() else: async with self.aiosession.get...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html
cb8ca617d8e6-3
if "title" in r.keys() ] toret = "\n".join(videos) elif "images" in result.keys(): images = [ f"""Title: "{r["title"]}" Link: {r["original"]["link"]}""" for r in result["images"] if "original" in r.keys() ] ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html
ab0093303f90-0
Source code for langchain.utilities.graphql import json from typing import Any, Callable, Dict, Optional from langchain.pydantic_v1 import BaseModel, Extra, root_validator [docs]class GraphQLAPIWrapper(BaseModel): """Wrapper around GraphQL API. To use, you should have the ``gql`` python package installed. T...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html
ab0093303f90-1
return json.dumps(result, indent=2) 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
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html
0689df1216d2-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
0689df1216d2-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
323b72aded72-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 request...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
323b72aded72-1
def fix_table_names(cls, table_names: List[str]) -> List[str]: """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 a...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
323b72aded72-2
raise ClientAuthenticationError( "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.""" re...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
323b72aded72-3
if isinstance(table_names, str) and table_names != "": 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 _g...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
323b72aded72-4
tables_todo = self._get_tables_todo(tables_requested) 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 =...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
323b72aded72-5
self.schemas[table] = "unknown" 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"...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
323b72aded72-6
async with session.post( self.request_url, headers=self.headers, json=self._create_json_content(command), timeout=10, ) as response: if response.status == 403: return "TokenError: Could not login to PowerBI, ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
c821b40fdf4c-0
Source code for langchain.utilities.jira """Util that calls Jira.""" from typing import Any, Dict, List, Optional from langchain.pydantic_v1 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]...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
c821b40fdf4c-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
c821b40fdf4c-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
c821b40fdf4c-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
5059197b311b-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 langchain.pydantic_v1 import BaseModel, Extra [docs]class Requests(Bas...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html
5059197b311b-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
5059197b311b-2
yield response [docs] @asynccontextmanager async def apatch( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """PATCH the URL and return the text asynchronously.""" async with self._arequest("PATCH", url, json=data, **kwargs) as r...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html
5059197b311b-3
headers=self.headers, aiosession=self.aiosession, auth=self.auth ) [docs] def get(self, url: str, **kwargs: Any) -> str: """GET the URL and return the text.""" return self.requests.get(url, **kwargs).text [docs] def post(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html
5059197b311b-4
return await response.text() [docs] async def apatch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PATCH the URL and return the text asynchronously.""" async with self.requests.apatch(url, data, **kwargs) as response: return await response.text() [docs] async def aput...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html
7af2dfaf0172-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
7af2dfaf0172-1
:class:`SearxResults` is a convenience wrapper around the raw json result. Example usage of the ``run`` method to make a search: .. code-block:: python s.run(query="what is the best search engine?") Engine Parameters ----------------- You can pass any `accepted searx search API <https://docs.searxng.org/dev...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
7af2dfaf0172-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
7af2dfaf0172-3
validator, ) from langchain.utils import get_from_dict_or_env def _get_default_params() -> dict: return {"language": "en", "format": "json"} [docs]class SearxResults(dict): """Dict like wrapper around search api results.""" _data: str = "" [docs] def __init__(self, data: str): """Take a raw resul...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
7af2dfaf0172-4
Example with SSL disabled: .. 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", ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
7af2dfaf0172-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
7af2dfaf0172-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
7af2dfaf0172-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
7af2dfaf0172-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
7af2dfaf0172-9
engines: List of engines to use for the query. 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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
7af2dfaf0172-10
] [docs] async def aresults( 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 i...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
9cf789cb8418-0
Source code for langchain.utilities.portkey import json import os from typing import Dict, Optional [docs]class Portkey: """Portkey configuration. Attributes: base: The base URL for the Portkey API. Default: "https://api.portkey.ai/v1/proxy" """ base = "https://api.portkey.ai/v1/proxy"...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/portkey.html
9cf789cb8418-1
headers = { "x-portkey-api-key": api_key, "x-portkey-mode": "proxy openai", } if trace_id: headers["x-portkey-trace-id"] = trace_id if retry_count: headers["x-portkey-retry-count"] = str(retry_count) if cache: headers["x-portkey...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/portkey.html
14c9c0fbe5ae-0
Source code for langchain.utilities.wolfram_alpha """Util that calls WolframAlpha.""" from typing import Any, Dict, Optional from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class WolframAlphaAPIWrapper(BaseModel): """Wrapper for Wolfram Alpha...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
14c9c0fbe5ae-1
"""Run query through WolframAlpha and parse result.""" 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
99ab2a9fa808-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
99ab2a9fa808-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
99ab2a9fa808-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
99ab2a9fa808-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
99ab2a9fa808-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
99ab2a9fa808-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
99ab2a9fa808-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
99ab2a9fa808-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
7d2a22a86d6c-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 langchain.pydantic_v1 import BaseModel, root_validator from langchain.schema import Document logger = logging.getLogger(__name__) [docs]class PubM...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html
7d2a22a86d6c-1
doc_content_chars_max: int = 2000 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html
7d2a22a86d6c-2
Return an iterator of dictionaries containing the document metadata. """ 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.requ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html
7d2a22a86d6c-3
) retry = 0 while True: 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 a...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html
275f3f0c661a-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: """SparkSQL is a utility class for interacting with Spark SQL.""" [docs] ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
275f3f0c661a-1
) if catalog is not None: self._spark.catalog.setCurrentCatalog(catalog) if schema is not None: self._spark.catalog.setCurrentDatabase(schema) self._all_tables = set(self._get_all_table_names()) self._include_tables = set(include_tables) if include_tables else set...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
275f3f0c661a-2
) spark = SparkSession.builder.remote(database_uri).getOrCreate() return cls(spark, **kwargs) [docs] def get_usable_table_names(self) -> Iterable[str]: """Get names of tables available.""" if self._include_tables: return self._include_tables # sorting the result ca...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
275f3f0c661a-3
table_info += "*/" tables.append(table_info) final_str = "\n\n".join(tables) return final_str def _get_sample_spark_rows(self, table: str) -> str: query = f"SELECT * FROM {table} LIMIT {self._sample_rows_in_table_info}" df = self._spark.sql(query) columns_str = "\...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
275f3f0c661a-4
Follows best practices as specified in: Rajkumar et al, 2022 (https://arxiv.org/abs/2204.00498) If `sample_rows_in_table_info`, the specified number of sample rows will be appended to each table description. This can increase performance as demonstrated in the paper. """ ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
c1ae8fc0b57d-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
c1ae8fc0b57d-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
c1ae8fc0b57d-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
c1ae8fc0b57d-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
120ec40cb05c-0
Source code for langchain.utilities.google_search """Util that calls Google Search.""" from typing import Any, Dict, List, Optional from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class GoogleSearchAPIWrapper(BaseModel): """Wrapper for Google...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
120ec40cb05c-1
- Create a custom search engine here: https://programmablesearchengine.google.com/. - In `What to search` to search, pick the `Search the entire Web` option. After search engine is created, you can click on it and find `Search engine ID` on the Overview page. """ search_engine: Any #: :meta priva...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
120ec40cb05c-2
raise ImportError( "google-api-python-client is not installed. " "Please install it with `pip install google-api-python-client" ">=2.100.0`" ) service = build("customsearch", "v1", developerKey=google_api_key) values["search_engine"] = service ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
120ec40cb05c-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
dddbd98e4a6a-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 langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator from langchain.utils import...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
dddbd98e4a6a-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
dddbd98e4a6a-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
dddbd98e4a6a-3
if isinstance(answer_box, list): answer_box = answer_box[0] if "result" in answer_box.keys(): return answer_box["result"] elif "answer" in answer_box.keys(): return answer_box["answer"] elif "snippet" in answer_box.keys(): ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
dddbd98e4a6a-4
): return res["popular_destinations"]["destinations"] elif "top_sights" in res.keys() and "sights" in res["top_sights"].keys(): return res["top_sights"]["sights"] elif ( "images_results" in res.keys() and "thumbnail" in res["images_results"][0].keys() ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
dddbd98e4a6a-5
snippets.append(first_organic_result["rich_snippet_table"]) elif "link" in first_organic_result.keys(): snippets.append(first_organic_result["link"]) if "buying_guide" in res.keys(): snippets.append(res["buying_guide"]) if "local_results" in res.keys() and "places...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
b24e5bdc2374-0
Source code for langchain.utilities.twilio """Util that calls Twilio.""" from typing import Any, Dict, Optional from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class TwilioAPIWrapper(BaseModel): """Messaging Client using Twilio. To use, y...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
b24e5bdc2374-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
b24e5bdc2374-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
f6535c65808d-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 langchain.pydantic_v1 import BaseModel, Extra, root_validator [docs]class DuckDuckGoSearchAPIWrapper(BaseModel...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
f6535c65808d-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
f6535c65808d-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
a5d9a77f532b-0
Source code for langchain.utilities.brave_search import json from typing import List import requests from langchain.pydantic_v1 import BaseModel, Field from langchain.schema import Document [docs]class BraveSearchWrapper(BaseModel): """Wrapper around the Brave search engine.""" api_key: str """The API key t...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/brave_search.html
a5d9a77f532b-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
f6f3246e6746-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 langchain.pydantic_v1 import BaseMod...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
f6f3246e6746-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
f6f3246e6746-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
c0acdbba54fd-0
Source code for langchain.utilities.dalle_image_generator """Utility that calls OpenAI's Dall-E Image Generator.""" from typing import Any, Dict, Optional from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class DallEAPIWrapper(BaseModel): """Wr...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dalle_image_generator.html
c0acdbba54fd-1
"Please it install it with `pip install openai`." ) return values [docs] def run(self, query: str) -> str: """Run query through OpenAI and parse result.""" image_url = self._dalle_image_url(query) if image_url is None or image_url == "": # We don't want to retu...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dalle_image_generator.html
528674918111-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 typing_extensions import Literal from langchain.pydantic_v1 import BaseModel, root_validator from langchain.utils import get_fr...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
528674918111-1
@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"] = serper_api_key return values [d...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
528674918111-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
528674918111-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
528674918111-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
45b6a0b3f275-0
Source code for langchain.utilities.alpha_vantage """Util that calls AlphaVantage for Currency Exchange Rate.""" from typing import Any, Dict, List, Optional import requests from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class AlphaVantageAPIWra...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/alpha_vantage.html
45b6a0b3f275-1
data = response.json() if "Error Message" in data: raise ValueError(f"API Error: {data['Error Message']}") return data @property def standard_currencies(self) -> List[str]: return ["USD", "EUR", "GBP", "JPY", "CHF", "CAD", "AUD", "NZD"] [docs] def run(self, from_currency: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/alpha_vantage.html
4bac12b3e9ac-0
Source code for langchain.utilities.openweathermap """Util that calls OpenWeatherMap using PyOWM.""" from typing import Any, Dict, Optional from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class OpenWeatherMapAPIWrapper(BaseModel): """Wrapper ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
4bac12b3e9ac-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
0291ecb19016-0
Source code for langchain.utilities.google_places_api """Chain that calls Google Places API. """ import logging from typing import Any, Dict, Optional from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class GooglePlacesAPIWrapper(BaseModel): ""...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
0291ecb19016-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
0291ecb19016-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
e97c5b29247c-0
Source code for langchain.utilities.redis from __future__ import annotations import logging import re from typing import TYPE_CHECKING, Any, List, Optional, Pattern from urllib.parse import urlparse import numpy as np logger = logging.getLogger(__name__) if TYPE_CHECKING: from redis.client import Redis as RedisType...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html
e97c5b29247c-1
"""Check if the correct Redis modules are installed.""" installed_modules = client.module_list() installed_modules = { module[b"name"].decode("utf-8"): module for module in installed_modules } for module in required_modules: if module["name"] in installed_modules and int( ins...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html
e97c5b29247c-2
needed holding the name of the redis service within the sentinels to get the correct redis server connection. The default service name is "mymaster". The optional second part of the path is the redis db number to connect to. An optional username or password is used for booth connections to the rediserver ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html
e97c5b29247c-3
if _check_for_cluster(redis_client): redis_client.close() redis_client = _redis_cluster_client(redis_url, **kwargs) return redis_client def _redis_sentinel_client(redis_url: str, **kwargs: Any) -> RedisType: """helper method to parse an (un-official) redis+sentinel url and create a S...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html