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(__name__) [docs]class PubMedAPIWrapper(BaseModel): """ Wrapper around PubMed API. This wrapper will use the PubMed API to conduct searches and fetch document summaries. By default, it will return the document summaries of the top-k results of an input search. Parameters: top_k_results: number of the top-scored document used for the PubMed tool MAX_QUERY_LENGTH: maximum length of the query. Default is 300 characters. doc_content_chars_max: maximum length of the document content. Content will be truncated if it exceeds this length. Default is 2000 characters. max_retry: maximum number of retries for a request. Default is 5. sleep_time: time to wait between retries. Default is 0.2 seconds. email: email address to be used for the PubMed API. """ parse: Any #: :meta private: base_url_esearch = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" base_url_efetch = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?" max_retry = 5 sleep_time = 0.2 # Default values for the parameters top_k_results: int = 3 MAX_QUERY_LENGTH = 300 doc_content_chars_max: int = 2000 email: str = "your_email@example.com" @root_validator()
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 ImportError( "Could not import xmltodict python package. " "Please install it with `pip install xmltodict`." ) return values [docs] def run(self, query: str) -> str: """ 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 = [ f"Published: {result['Published']}\n" f"Title: {result['Title']}\n" f"Copyright Information: {result['Copyright Information']}\n" f"Summary::\n{result['Summary']}" for result in self.load(query[: self.MAX_QUERY_LENGTH]) ] # Join the results and limit the character count return ( "\n\n".join(docs)[: self.doc_content_chars_max] if docs else "No good PubMed Result was found" ) except Exception as ex: return f"PubMed exception: {ex}" [docs] def lazy_load(self, query: str) -> Iterator[dict]: """ Search PubMed for documents matching the query. Return an iterator of dictionaries containing the document metadata. """ url = ( self.base_url_esearch
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_text = json.loads(text) webenv = json_text["esearchresult"]["webenv"] for uid in json_text["esearchresult"]["idlist"]: yield self.retrieve_article(uid, webenv) [docs] def load(self, query: str) -> List[dict]: """ Search PubMed for documents matching the query. Return a list of dictionaries containing the document metadata. """ return list(self.lazy_load(query)) def _dict2document(self, doc: dict) -> Document: summary = doc.pop("Summary") return Document(page_content=summary, metadata=doc) [docs] def lazy_load_docs(self, query: str) -> Iterator[Document]: for d in self.lazy_load(query=query): yield self._dict2document(d) [docs] def load_docs(self, query: str) -> List[Document]: return list(self.lazy_load_docs(query=query)) [docs] def retrieve_article(self, uid: str, webenv: str) -> dict: url = ( self.base_url_efetch + "db=pubmed&retmode=xml&id=" + uid + "&webenv=" + webenv ) retry = 0 while True: try: result = urllib.request.urlopen(url) break
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 print( f"Too Many Requests, " f"waiting for {self.sleep_time:.2f} seconds..." ) time.sleep(self.sleep_time) self.sleep_time *= 2 retry += 1 else: raise e xml_text = result.read().decode("utf-8") text_dict = self.parse(xml_text) return self._parse_article(uid, text_dict) def _parse_article(self, uid: str, text_dict: dict) -> dict: ar = text_dict["PubmedArticleSet"]["PubmedArticle"]["MedlineCitation"][ "Article" ] summary = "\n".join( [ f"{txt['@Label']}: {txt['#text']}" for txt in ar.get("Abstract", {}).get("AbstractText", []) if "#text" in txt and "@Label" in txt ] ) a_d = ar.get("ArticleDate", {}) pub_date = "-".join( [a_d.get("Year", ""), a_d.get("Month", ""), a_d.get("Day", "")] ) return { "uid": uid, "Title": ar.get("ArticleTitle", ""), "Published": pub_date, "Copyright Information": ar.get("Abstract", {}).get( "CopyrightInformation", "" ), "Summary": summary, }
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 for using: 1. Go to wolfram alpha and sign up for a developer account 2. Create an app and get your APP ID 3. Save your APP ID into WOLFRAM_ALPHA_APPID env variable 4. pip install wolframalpha """ wolfram_client: Any #: :meta private: wolfram_alpha_appid: Optional[str] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" wolfram_alpha_appid = get_from_dict_or_env( values, "wolfram_alpha_appid", "WOLFRAM_ALPHA_APPID" ) values["wolfram_alpha_appid"] = wolfram_alpha_appid try: import wolframalpha except ImportError: raise ImportError( "wolframalpha is not installed. " "Please install it with `pip install wolframalpha`" ) client = wolframalpha.Client(wolfram_alpha_appid) values["wolfram_client"] = client return values [docs] def run(self, query: str) -> str: """Run query through WolframAlpha and parse result.""" res = self.wolfram_client.query(query)
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 assumption alone if answer is empty return "No good Wolfram Alpha Result was found" else: return f"Assumption: {assumption} \nAnswer: {answer}"
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[SparkSession] = None, catalog: Optional[str] = None, schema: Optional[str] = None, ignore_tables: Optional[List[str]] = None, include_tables: Optional[List[str]] = None, sample_rows_in_table_info: int = 3, ): try: from pyspark.sql import SparkSession except ImportError: raise ValueError( "pyspark is not installed. Please install it with `pip install pyspark`" ) self._spark = ( spark_session if spark_session else SparkSession.builder.getOrCreate() ) 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() if self._include_tables: missing_tables = self._include_tables - self._all_tables if missing_tables: raise ValueError( f"include_tables {missing_tables} not found in database" ) self._ignore_tables = set(ignore_tables) if ignore_tables else set() if self._ignore_tables: missing_tables = self._ignore_tables - self._all_tables if missing_tables: raise ValueError( f"ignore_tables {missing_tables} not found in database"
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): raise TypeError("sample_rows_in_table_info must be an integer") self._sample_rows_in_table_info = sample_rows_in_table_info [docs] @classmethod def from_uri( cls, database_uri: str, engine_args: Optional[dict] = None, **kwargs: Any ) -> SparkSQL: """Creating a remote Spark Session via Spark connect. For example: SparkSQL.from_uri("sc://localhost:15002") """ try: from pyspark.sql import SparkSession except ImportError: raise ValueError( "pyspark is not installed. Please install it with `pip install pyspark`" ) 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 can help LLM understanding it. return sorted(self._all_tables - self._ignore_tables) def _get_all_table_names(self) -> Iterable[str]: rows = self._spark.sql("SHOW TABLES").select("tableName").collect() return list(map(lambda row: row.tableName, rows)) def _get_create_table_stmt(self, table: str) -> str: statement = (
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_table_info(self, table_names: Optional[List[str]] = None) -> str: all_table_names = self.get_usable_table_names() if table_names is not None: missing_tables = set(table_names).difference(all_table_names) if missing_tables: raise ValueError(f"table_names {missing_tables} not found in database") all_table_names = table_names tables = [] for table_name in all_table_names: table_info = self._get_create_table_stmt(table_name) if self._sample_rows_in_table_info: table_info += "\n\n/*" table_info += f"\n{self._get_sample_spark_rows(table_name)}\n" 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 = "\t".join(list(map(lambda f: f.name, df.schema.fields))) try: sample_rows = self._get_dataframe_results(df) # save the sample rows in string format sample_rows_str = "\n".join(["\t".join(row) for row in sample_rows]) except Exception: sample_rows_str = ""
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().values())) def _get_dataframe_results(self, df: DataFrame) -> list: return list(map(self._convert_row_as_tuple, df.collect())) [docs] def run(self, command: str, fetch: str = "all") -> str: df = self._spark.sql(command) if fetch == "one": df = df.limit(1) return str(self._get_dataframe_results(df)) [docs] def get_table_info_no_throw(self, table_names: Optional[List[str]] = None) -> str: """Get information about specified tables. 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. """ try: return self.get_table_info(table_names) except ValueError as e: """Format the error message""" return f"Error: {e}" [docs] def run_no_throw(self, command: str, fetch: str = "all") -> str: """Execute a SQL command and return a string representing the results. If the statement returns rows, a string of the results is returned.
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: raise ValueError( "pyspark is not installed. Please install it with `pip install pyspark`" ) try: return self.run(command, fetch) except PySparkException as e: """Format the error message""" return f"Error: {e}"
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. Adapted from: Instructions adapted from https://stackoverflow.com/questions/ 37083058/ programmatically-searching-google-in-python-using-custom-search TODO: DOCS for using it 1. Install google-api-python-client - If you don't already have a Google account, sign up. - If you have never created a Google APIs Console project, read the Managing Projects page and create a project in the Google API Console. - Install the library using pip install google-api-python-client The current version of the library is 2.70.0 at this time 2. To create an API key: - Navigate to the APIs & Services→Credentials panel in Cloud Console. - Select Create credentials, then select API key from the drop-down menu. - The API key created dialog box displays your newly created key. - You now have an API_KEY 3. Setup Custom Search Engine so you can search the entire web - Create a custom search engine in this link. - In Sites to search, add any valid URL (i.e. www.stackoverflow.com). - That’s all you have to fill up, the rest doesn’t matter. In the left-side menu, click Edit search engine → {your search engine name} → Setup Set Search the entire web to ON. Remove the URL you added from the list of Sites to search. - Under Search engine ID you’ll find the search-engine-ID.
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.google.com/apis/library/customsearch.googleapis .com """ search_engine: Any #: :meta private: google_api_key: Optional[str] = None google_cse_id: Optional[str] = None k: int = 10 siterestrict: bool = False class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def _google_search_results(self, search_term: str, **kwargs: Any) -> List[dict]: cse = self.search_engine.cse() if self.siterestrict: cse = cse.siterestrict() res = cse.list(q=search_term, cx=self.google_cse_id, **kwargs).execute() return res.get("items", []) @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" google_api_key = get_from_dict_or_env( values, "google_api_key", "GOOGLE_API_KEY" ) values["google_api_key"] = google_api_key google_cse_id = get_from_dict_or_env(values, "google_cse_id", "GOOGLE_CSE_ID") values["google_cse_id"] = google_cse_id try: from googleapiclient.discovery import build except ImportError: raise ImportError(
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"] = service return values [docs] def run(self, query: str) -> str: """Run query through GoogleSearch and parse result.""" snippets = [] results = self._google_search_results(query, num=self.k) if len(results) == 0: return "No good Google Search Result was found" for result in results: if "snippet" in result: snippets.append(result["snippet"]) return " ".join(snippets) [docs] def results( self, query: str, num_results: int, search_params: Optional[Dict[str, str]] = None, ) -> List[Dict]: """Run query through GoogleSearch and return metadata. Args: query: The query to search for. num_results: The number of results to return. search_params: Parameters to be passed on search Returns: A list of dictionaries with the following keys: snippet - The description of the result. title - The title of the result. link - The link to the result. """ metadata_results = [] results = self._google_search_results( query, num=num_results, **(search_params or {}) ) if len(results) == 0: return [{"Result": "No good Google Search Result was found"}] for result in results: metadata_result = {
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 metadata_results
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 langchain.utils import get_from_dict_or_env [docs]class GoogleSerperAPIWrapper(BaseModel): """Wrapper around the Serper.dev Google Search API. You can create a free API key at https://serper.dev. To use, you should have the environment variable ``SERPER_API_KEY`` set with your API key, or pass `serper_api_key` as a named parameter to the constructor. Example: .. code-block:: python from langchain import GoogleSerperAPIWrapper google_serper = GoogleSerperAPIWrapper() """ k: int = 10 gl: str = "us" hl: str = "en" # "places" and "images" is available from Serper but not implemented in the # parser of run(). They can be used in results() type: Literal["news", "search", "places", "images"] = "search" result_key_for_type = { "news": "news", "places": "places", "images": "images", "search": "organic", } tbs: Optional[str] = None serper_api_key: Optional[str] = None aiosession: Optional[aiohttp.ClientSession] = None class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True @root_validator()
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"] = serper_api_key return values [docs] def results(self, query: str, **kwargs: Any) -> Dict: """Run query through GoogleSearch.""" return self._google_serper_api_results( query, gl=self.gl, hl=self.hl, num=self.k, tbs=self.tbs, search_type=self.type, **kwargs, ) [docs] def run(self, query: str, **kwargs: Any) -> str: """Run query through GoogleSearch and parse result.""" results = self._google_serper_api_results( query, gl=self.gl, hl=self.hl, num=self.k, tbs=self.tbs, search_type=self.type, **kwargs, ) return self._parse_results(results) [docs] async def aresults(self, query: str, **kwargs: Any) -> Dict: """Run query through GoogleSearch.""" 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 results [docs] async def arun(self, query: str, **kwargs: Any) -> str:
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, ) return self._parse_results(results) def _parse_snippets(self, results: dict) -> List[str]: snippets = [] if results.get("answerBox"): answer_box = results.get("answerBox", {}) if answer_box.get("answer"): return [answer_box.get("answer")] elif answer_box.get("snippet"): return [answer_box.get("snippet").replace("\n", " ")] elif answer_box.get("snippetHighlighted"): return answer_box.get("snippetHighlighted") if results.get("knowledgeGraph"): kg = results.get("knowledgeGraph", {}) title = kg.get("title") entity_type = kg.get("type") if entity_type: snippets.append(f"{title}: {entity_type}.") description = kg.get("description") if description: snippets.append(description) for attribute, value in kg.get("attributes", {}).items(): snippets.append(f"{title} {attribute}: {value}.") for result in results[self.result_key_for_type[self.type]][: self.k]: if "snippet" in result: snippets.append(result["snippet"]) for attribute, value in result.get("attributes", {}).items(): snippets.append(f"{attribute}: {value}.") if len(snippets) == 0: return ["No good Google Search Result was found"] return snippets
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: headers = { "X-API-KEY": self.serper_api_key or "", "Content-Type": "application/json", } params = { "q": search_term, **{key: value for key, value in kwargs.items() if value is not None}, } response = requests.post( f"https://google.serper.dev/{search_type}", headers=headers, params=params ) response.raise_for_status() search_results = response.json() return search_results async def _async_google_serper_search_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", } url = f"https://google.serper.dev/{search_type}" params = { "q": search_term, **{key: value for key, value in kwargs.items() if value is not None}, } if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.post( url, params=params, headers=headers, raise_for_status=False ) as response: search_results = await response.json() else: async with self.aiosession.post(
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): """Wrapper around requests to handle auth and async. The main purpose of this wrapper is to handle authentication (by saving headers) and enable easy async methods on the same base object. """ headers: Optional[Dict[str, str]] = None aiosession: Optional[aiohttp.ClientSession] = None auth: Optional[Any] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True [docs] def get(self, url: str, **kwargs: Any) -> requests.Response: """GET the URL and return the text.""" return requests.get(url, headers=self.headers, auth=self.auth, **kwargs) [docs] def post(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response: """POST to the URL and return the text.""" return requests.post( url, json=data, headers=self.headers, auth=self.auth, **kwargs ) [docs] def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response: """PATCH the URL and return the text.""" return requests.patch( url, json=data, headers=self.headers, auth=self.auth, **kwargs ) [docs] def put(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response:
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=self.headers, auth=self.auth, **kwargs) @asynccontextmanager async def _arequest( self, method: str, url: str, **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """Make an async request.""" if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.request( method, url, headers=self.headers, auth=self.auth, **kwargs ) as response: yield response else: async with self.aiosession.request( method, url, headers=self.headers, auth=self.auth, **kwargs ) as response: yield response [docs] @asynccontextmanager async def aget( self, url: str, **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """GET the URL and return the text asynchronously.""" async with self._arequest("GET", url, auth=self.auth, **kwargs) as response: yield response [docs] @asynccontextmanager async def apost( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """POST to the URL and return the text asynchronously.""" async with self._arequest(
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]: """PATCH the URL and return the text asynchronously.""" async with self._arequest( "PATCH", url, json=data, auth=self.auth, **kwargs ) as response: yield response [docs] @asynccontextmanager async def aput( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """PUT the URL and return the text asynchronously.""" async with self._arequest( "PUT", url, json=data, auth=self.auth, **kwargs ) as response: yield response [docs] @asynccontextmanager async def adelete( self, url: str, **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """DELETE the URL and return the text asynchronously.""" async with self._arequest("DELETE", url, auth=self.auth, **kwargs) as response: yield response [docs]class TextRequestsWrapper(BaseModel): """Lightweight wrapper around requests library. The main purpose of this wrapper is to always return a text output. """ headers: Optional[Dict[str, str]] = None aiosession: Optional[aiohttp.ClientSession] = None auth: Optional[Any] = None class Config:
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 ) [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: """POST to the URL and return the text.""" return self.requests.post(url, data, **kwargs).text [docs] def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PATCH the URL and return the text.""" return self.requests.patch(url, data, **kwargs).text [docs] def put(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PUT the URL and return the text.""" return self.requests.put(url, data, **kwargs).text [docs] def delete(self, url: str, **kwargs: Any) -> str: """DELETE the URL and return the text.""" return self.requests.delete(url, **kwargs).text [docs] async def aget(self, url: str, **kwargs: Any) -> str: """GET the URL and return the text asynchronously.""" async with self.requests.aget(url, **kwargs) as response: return await response.text()
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 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(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PUT the URL and return the text asynchronously.""" async with self.requests.aput(url, data, **kwargs) as response: return await response.text() [docs] async def adelete(self, url: str, **kwargs: Any) -> str: """DELETE the URL and return the text asynchronously.""" async with self.requests.adelete(url, **kwargs) as response: return await response.text() # For backwards compatibility RequestsWrapper = TextRequestsWrapper
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 about the dangers of PythonREPL.""" logger.warning("Python REPL can execute arbitrary code. Use with caution.") [docs]class PythonREPL(BaseModel): """Simulates a standalone Python REPL.""" globals: Optional[Dict] = Field(default_factory=dict, alias="_globals") locals: Optional[Dict] = Field(default_factory=dict, alias="_locals") [docs] @classmethod def worker( cls, command: str, globals: Optional[Dict], locals: Optional[Dict], queue: multiprocessing.Queue, ) -> None: old_stdout = sys.stdout sys.stdout = mystdout = StringIO() try: exec(command, globals, locals) sys.stdout = old_stdout queue.put(mystdout.getvalue()) except Exception as e: sys.stdout = old_stdout queue.put(repr(e)) [docs] def run(self, command: str, timeout: Optional[int] = None) -> str: """Run command with own globals/locals and returns anything printed. Timeout after the specified number of seconds.""" # Warn against dangers of PythonREPL warn_once() queue: multiprocessing.Queue = multiprocessing.Queue() # Only use multiprocessing if we are enforcing a timeout if timeout is not None: # create a Process p = multiprocessing.Process(
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) if p.is_alive(): p.terminate() return "Execution timed out" else: self.worker(command, self.globals, self.locals, queue) # get the result from the worker function return queue.get()
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, root_validator from langchain.utils import get_from_dict_or_env [docs]class BingSearchAPIWrapper(BaseModel): """Wrapper for Bing Search API. 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 """ bing_subscription_key: str bing_search_url: str k: int = 10 class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def _bing_search_results(self, search_term: str, count: int) -> List[dict]: headers = {"Ocp-Apim-Subscription-Key": self.bing_subscription_key} params = { "q": search_term, "count": count, "textDecorations": True, "textFormat": "HTML", } response = requests.get( self.bing_search_url, headers=headers, params=params # type: ignore ) response.raise_for_status() search_results = response.json() return search_results["webPages"]["value"] @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and endpoint exists in environment.""" bing_subscription_key = get_from_dict_or_env(
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", # default="https://api.bing.microsoft.com/v7.0/search", ) values["bing_search_url"] = bing_search_url return values [docs] def run(self, query: str) -> str: """Run query through BingSearch and parse result.""" snippets = [] results = self._bing_search_results(query, count=self.k) if len(results) == 0: return "No good Bing Search Result was found" for result in results: snippets.append(result["snippet"]) return " ".join(snippets) [docs] def results(self, query: str, num_results: int) -> List[Dict]: """Run query through BingSearch 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: snippet - The description of the result. title - The title of the result. link - The link to the result. """ metadata_results = [] results = self._bing_search_results(query, count=num_results) if len(results) == 0: return [{"Result": "No good Bing Search Result was found"}] for result in results: metadata_result = { "snippet": result["snippet"], "title": result["name"],
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 around Google Places API. To use, you should have the ``googlemaps`` python package installed, **an API key for the google maps platform**, and the environment variable ''GPLACES_API_KEY'' set with your API key , or pass 'gplaces_api_key' as a named parameter to the constructor. By default, this will return the all the results on the input query. You can use the top_k_results argument to limit the number of results. Example: .. code-block:: python from langchain import GooglePlacesAPIWrapper gplaceapi = GooglePlacesAPIWrapper() """ gplaces_api_key: Optional[str] = None google_map_client: Any #: :meta private: top_k_results: Optional[int] = 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 is in your environment variable.""" gplaces_api_key = get_from_dict_or_env( values, "gplaces_api_key", "GPLACES_API_KEY" ) values["gplaces_api_key"] = gplaces_api_key try: import googlemaps values["google_map_client"] = googlemaps.Client(gplaces_api_key) except ImportError: raise ImportError(
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 that exists that match.""" search_results = self.google_map_client.places(query)["results"] num_to_return = len(search_results) places = [] if num_to_return == 0: return "Google Places did not find any places that match the description" num_to_return = ( num_to_return if self.top_k_results is None else min(num_to_return, self.top_k_results) ) for i in range(num_to_return): result = search_results[i] details = self.fetch_place_details(result["place_id"]) if details is not None: places.append(details) return "\n".join([f"{i+1}. {item}" for i, item in enumerate(places)]) [docs] def fetch_place_details(self, place_id: str) -> Optional[str]: try: place_details = self.google_map_client.place(place_id) place_details["place_id"] = place_id formatted_details = self.format_place_details(place_details) return formatted_details except Exception as e: logging.error(f"An Error occurred while fetching place details: {e}") return None [docs] def format_place_details(self, place_details: Dict[str, Any]) -> Optional[str]: try: name = place_details.get("result", {}).get("name", "Unknown") address = place_details.get("result", {}).get( "formatted_address", "Unknown"
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_id", "Unknown") formatted_details = ( f"{name}\nAddress: {address}\n" f"Google place ID: {place_id}\n" f"Phone: {phone_number}\nWebsite: {website}\n\n" ) return formatted_details except Exception as e: logging.error(f"An error occurred while formatting place details: {e}") return None
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 and a lambda functions built from the AWS Console or CLI. Set up your AWS credentials with ``aws configure`` Example: .. code-block:: bash pip install boto3 aws configure """ lambda_client: Any #: :meta private: """The configured boto3 client""" function_name: Optional[str] = None """The name of your lambda function""" awslambda_tool_name: Optional[str] = None """If passing to an agent as a tool, the tool name""" awslambda_tool_description: Optional[str] = None """If passing to an agent as a tool, the description""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that python package exists in environment.""" try: import boto3 except ImportError: raise ImportError( "boto3 is not installed. Please install it with `pip install boto3`" ) values["lambda_client"] = boto3.client("lambda") values["function_name"] = values["function_name"] return values [docs] def run(self, query: str) -> str: """ Invokes the lambda function and returns the result. Args: query: an input to passed to the lambda
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", Payload=json.dumps({"body": query}), ) try: payload_stream = res["Payload"] payload_string = payload_stream.read().decode("utf-8") answer = json.loads(payload_string)["body"] except StopIteration: return "Failed to parse response from Lambda" if answer is None or answer == "": # We don't want to return the assumption alone if answer is empty return "Request failed." else: return f"Result: {answer}"
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 WikipediaAPIWrapper(BaseModel): """Wrapper around WikipediaAPI. To use, you should have the ``wikipedia`` python package installed. This wrapper will use the Wikipedia API to conduct searches and fetch page summaries. By default, it will return the page summaries of the top-k results. It limits the Document content by doc_content_chars_max. """ wiki_client: Any #: :meta private: top_k_results: int = 3 lang: str = "en" load_all_available_meta: bool = False doc_content_chars_max: int = 4000 @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environment.""" try: import wikipedia wikipedia.set_lang(values["lang"]) values["wiki_client"] = wikipedia except ImportError: raise ImportError( "Could not import wikipedia python package. " "Please install it with `pip install wikipedia`." ) return values [docs] def run(self, query: str) -> str: """Run Wikipedia search and get page summaries.""" page_titles = self.wiki_client.search(query[:WIKIPEDIA_MAX_QUERY_LENGTH]) summaries = [] for page_title in page_titles[: self.top_k_results]: if wiki_page := self._fetch_page(page_title): if summary := self._formatted_page_summary(page_title, wiki_page):
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(page_title: str, wiki_page: Any) -> Optional[str]: return f"Page: {page_title}\nSummary: {wiki_page.summary}" def _page_to_document(self, page_title: str, wiki_page: Any) -> Document: main_meta = { "title": page_title, "summary": wiki_page.summary, "source": wiki_page.url, } add_meta = ( { "categories": wiki_page.categories, "page_url": wiki_page.url, "image_urls": wiki_page.images, "related_titles": wiki_page.links, "parent_id": wiki_page.parent_id, "references": wiki_page.references, "revision_id": wiki_page.revision_id, "sections": wiki_page.sections, } if self.load_all_available_meta else {} ) doc = Document( page_content=wiki_page.content[: self.doc_content_chars_max], metadata={ **main_meta, **add_meta, }, ) return doc def _fetch_page(self, page: str) -> Optional[str]: try: return self.wiki_client.page(title=page, auto_suggest=False) except ( self.wiki_client.exceptions.PageError, self.wiki_client.exceptions.DisambiguationError, ): return None
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 = self.wiki_client.search(query[:WIKIPEDIA_MAX_QUERY_LENGTH]) docs = [] for page_title in page_titles[: self.top_k_results]: if wiki_page := self._fetch_page(page_title): if doc := self._page_to_document(page_title, wiki_page): docs.append(doc) return docs
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.get("LANGCHAIN_HUB_DEFAULT_REF", "master") URL_BASE = os.environ.get( "LANGCHAIN_HUB_URL_BASE", "https://raw.githubusercontent.com/hwchase17/langchain-hub/{ref}/", ) HUB_PATH_RE = re.compile(r"lc(?P<ref>@[^:]+)?://(?P<path>.*)") T = TypeVar("T") [docs]def try_load_from_hub( path: Union[str, Path], loader: Callable[[str], T], valid_prefix: str, valid_suffixes: Set[str], **kwargs: Any, ) -> Optional[T]: """Load configuration from hub. Returns None if path is not a hub path.""" if not isinstance(path, str) or not (match := HUB_PATH_RE.match(path)): return None ref, remote_path_str = match.groups() ref = ref[1:] if ref else DEFAULT_REF remote_path = Path(remote_path_str) if remote_path.parts[0] != valid_prefix: return None if remote_path.suffix[1:] not in valid_suffixes: raise ValueError("Unsupported file type.") # Using Path with URLs is not recommended, because on Windows # the backslash is used as the path separator, which can cause issues # when working with URLs that use forward slashes as the path separator.
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(full_url, timeout=5) if r.status_code != 200: raise ValueError(f"Could not find file at {full_url}") with tempfile.TemporaryDirectory() as tmpdirname: file = Path(tmpdirname) / remote_path.name with open(file, "wb") as f: f.write(r.content) return loader(str(file), **kwargs)
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 DuckDuckGoSearchAPIWrapper(BaseModel): """Wrapper for DuckDuckGo Search API. Free and does not require any setup. """ region: Optional[str] = "wt-wt" safesearch: str = "moderate" time: Optional[str] = "y" max_results: int = 5 class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that python package exists in environment.""" try: from duckduckgo_search import DDGS # noqa: F401 except ImportError: raise ValueError( "Could not import duckduckgo-search python package. " "Please install it with `pip install duckduckgo-search`." ) return values [docs] def get_snippets(self, query: str) -> List[str]: """Run query through DuckDuckGo and return concatenated results.""" from duckduckgo_search import DDGS with DDGS() as ddgs: results = ddgs.text( query, region=self.region, safesearch=self.safesearch, timelimit=self.time, ) if results is None: return ["No good DuckDuckGo Search Result was found"] snippets = []
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 [docs] def run(self, query: str) -> str: snippets = self.get_snippets(query) return " ".join(snippets) [docs] def results( self, query: str, num_results: int, backend: str = "api" ) -> List[Dict[str, str]]: """Run query through DuckDuckGo 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: snippet - The description of the result. title - The title of the result. link - The link to the result. """ from duckduckgo_search import DDGS with DDGS() as ddgs: results = ddgs.text( query, region=self.region, safesearch=self.safesearch, timelimit=self.time, backend=backend, ) if results is None: return [{"Result": "No good DuckDuckGo Search Result was found"}] def to_metadata(result: Dict) -> Dict[str, str]: if backend == "news": return { "date": result["date"], "title": result["title"], "snippet": result["body"], "source": result["source"], "link": result["url"], }
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): if res is not None: formatted_results.append(to_metadata(res)) if len(formatted_results) == num_results: break return formatted_results
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, **kwargs: Any) -> RedisType: """Get a redis client from the connection url given. This helper accepts urls for Redis server (TCP with/without TLS or UnixSocket) as well as Redis Sentinel connections. Redis Cluster is not supported. Before creating a connection the existence of the database driver is checked an and ValueError raised otherwise To use, you should have the ``redis`` python package installed. Example: .. code-block:: python from langchain.utilities.redis import get_client redis_client = get_client( redis_url="redis://username:password@localhost:6379" index_name="my-index", embedding_function=embeddings.embed_query, ) To use a redis replication setup with multiple redis server and redis sentinels set "redis_url" to "redis+sentinel://" scheme. With this url format a path is 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 and the sentinel, different passwords for server and sentinel are not supported. And as another constraint only one sentinel instance can be given: Example: .. code-block:: python from langchain.utilities.redis import get_client
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, ) """ # Initialize with necessary components. try: import redis except ImportError: raise ValueError( "Could not import redis python package. " "Please install it with `pip install redis>=4.1.0`." ) # check if normal redis:// or redis+sentinel:// url if redis_url.startswith("redis+sentinel"): redis_client = _redis_sentinel_client(redis_url, **kwargs) if redis_url.startswith("rediss+sentinel"): # sentinel with TLS support enables kwargs["ssl"] = True if "ssl_cert_reqs" not in kwargs: kwargs["ssl_cert_reqs"] = "none" redis_client = _redis_sentinel_client(redis_url, **kwargs) else: # connect to redis server from url redis_client = redis.from_url(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 Sentinel connection to fetch the final redis client connection to a replica-master for read-write operations. If username and/or password for authentication is given the same credentials are used for the Redis Sentinel as well as Redis Server. With this implementation using a redis url only it is not possible to use different data for authentication on booth systems. """
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: # "/mymaster/0" first part is service name, optional second part is db number path_parts = parsed_url.path.split("/") service_name = path_parts[1] or "mymaster" if len(path_parts) > 2: kwargs["db"] = path_parts[2] else: service_name = "mymaster" sentinel_args = {} if parsed_url.password: sentinel_args["password"] = parsed_url.password kwargs["password"] = parsed_url.password if parsed_url.username: sentinel_args["username"] = parsed_url.username kwargs["username"] = parsed_url.username # check for all SSL related properties and copy them into sentinel_kwargs too, # add client_name also for arg in kwargs: if arg.startswith("ssl") or arg == "client_name": sentinel_args[arg] = kwargs[arg] # sentinel user/pass is part of sentinel_kwargs, user/pass for redis server # connection as direct parameter in kwargs sentinel_client = redis.sentinel.Sentinel( sentinel_list, sentinel_kwargs=sentinel_args, **kwargs ) # redis server might have password but not sentinel - fetch this error and try # again without pass, everything else cannot be handled here -> user needed try: sentinel_client.execute_command("ping") except redis.exceptions.AuthenticationError as ae:
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" ) sentinel_client = redis.sentinel.Sentinel(sentinel_list, **kwargs) else: raise ae return sentinel_client.master_for(service_name)
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_dict_or_env METAPHOR_API_URL = "https://api.metaphor.systems" [docs]class MetaphorSearchAPIWrapper(BaseModel): """Wrapper for Metaphor Search API.""" metaphor_api_key: str k: int = 10 class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def _metaphor_search_results( self, query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None, use_autoprompt: Optional[bool] = None, ) -> List[dict]: headers = {"X-Api-Key": self.metaphor_api_key} params = { "numResults": num_results, "query": query, "includeDomains": include_domains, "excludeDomains": exclude_domains, "startCrawlDate": start_crawl_date, "endCrawlDate": end_crawl_date, "startPublishedDate": start_published_date, "endPublishedDate": end_published_date, "useAutoprompt": use_autoprompt, }
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["results"] @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and endpoint exists in environment.""" metaphor_api_key = get_from_dict_or_env( values, "metaphor_api_key", "METAPHOR_API_KEY" ) values["metaphor_api_key"] = metaphor_api_key return values [docs] def results( self, query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None, use_autoprompt: Optional[bool] = None, ) -> List[Dict]: """Run query through Metaphor Search and return metadata. Args: query: The query to search for. num_results: The number of results to return. include_domains: A list of domains to include in the search. Only one of include_domains and exclude_domains should be defined. exclude_domains: A list of domains to exclude from the search. Only one of include_domains and exclude_domains should be defined.
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. end_published_date: If specified, only pages published before end_published_date will be returned. use_autoprompt: If true, we turn your query into a more Metaphor-friendly query. Adds latency. Returns: A list of dictionaries with the following keys: title - The title of the page url - The url author - Author of the content, if applicable. Otherwise, None. published_date - Estimated date published in YYYY-MM-DD format. Otherwise, None. """ # noqa: E501 raw_search_results = self._metaphor_search_results( query, num_results=num_results, include_domains=include_domains, exclude_domains=exclude_domains, start_crawl_date=start_crawl_date, end_crawl_date=end_crawl_date, start_published_date=start_published_date, end_published_date=end_published_date, use_autoprompt=use_autoprompt, ) return self._clean_results(raw_search_results) [docs] async def results_async( self, query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None,
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} params = { "numResults": num_results, "query": query, "includeDomains": include_domains, "excludeDomains": exclude_domains, "startCrawlDate": start_crawl_date, "endCrawlDate": end_crawl_date, "startPublishedDate": start_published_date, "endPublishedDate": end_published_date, "useAutoprompt": use_autoprompt, } async with aiohttp.ClientSession() as session: async with session.post( f"{METAPHOR_API_URL}/search", json=params, headers=headers ) as res: if res.status == 200: data = await res.text() return data else: raise Exception(f"Error {res.status}: {res.reason}") results_json_str = await fetch() results_json = json.loads(results_json_str) return self._clean_results(results_json["results"]) def _clean_results(self, raw_search_results: List[Dict]) -> List[Dict]: cleaned_results = [] for result in raw_search_results: cleaned_results.append( { "title": result["title"], "url": result["url"], "author": result["author"], "published_date": result["publishedDate"], } ) return cleaned_results
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 Vertex SDK being not available. Args: minimum_expected_version: The lowest expected version of the SDK. Raises: ImportError: an ImportError that mentions a required version of the SDK. """ raise ImportError( "Could not import VertexAI. Please, install it with " f"pip install google-cloud-aiplatform>={minimum_expected_version}" ) [docs]def init_vertexai( project: Optional[str] = None, location: Optional[str] = None, credentials: Optional["Credentials"] = None, ) -> None: """Init vertexai. Args: project: The default GCP project to use when making Vertex API calls. location: The default location to use when making API calls. credentials: The default custom credentials to use when making API calls. If not provided credentials will be ascertained from the environment. Raises: ImportError: If importing vertexai SDK did not succeed. """ try: import vertexai except ImportError: raise_vertex_import_error() vertexai.init( project=project, location=location, credentials=credentials, )
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 GoldenQueryAPIWrapper(BaseModel): """Wrapper for Golden. Docs for using: 1. Go to https://golden.com and sign up for an account 2. Get your API Key from https://golden.com/settings/api 3. Save your API Key into GOLDEN_API_KEY env variable """ golden_api_key: Optional[str] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" golden_api_key = get_from_dict_or_env( values, "golden_api_key", "GOLDEN_API_KEY" ) values["golden_api_key"] = golden_api_key return values [docs] def run(self, query: str) -> str: """Run query through Golden Query API and return the JSON raw result.""" headers = {"apikey": self.golden_api_key or ""} response = requests.post( f"{GOLDEN_BASE_URL}/api/v2/public/queries/", json={"prompt": query}, headers=headers, timeout=GOLDEN_TIMEOUT, ) if response.status_code != 201: return response.text content = json.loads(response.content) query_id = content["id"]
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, ) return response.text
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) and create a new API key. """ from typing import Dict import requests from pydantic import BaseModel, BaseSettings, Field, root_validator from langchain.utils import get_from_dict_or_env [docs]class SceneXplainAPIWrapper(BaseSettings, BaseModel): """Wrapper for SceneXplain API. 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) and create a new API key. """ scenex_api_key: str = Field(..., env="SCENEX_API_KEY") scenex_api_url: str = "https://api.scenex.jina.ai/v1/describe" def _describe_image(self, image: str) -> str: headers = { "x-api-key": f"token {self.scenex_api_key}", "content-type": "application/json", } payload = { "data": [ { "image": image, "algorithm": "Ember", "languages": ["en"], } ] }
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", "") @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key exists in environment.""" scenex_api_key = get_from_dict_or_env( values, "scenex_api_key", "SCENEX_API_KEY" ) values["scenex_api_key"] = scenex_api_key return values [docs] def run(self, image: str) -> str: """Run SceneXplain image explainer.""" description = self._describe_image(image) if not description: return "No description found." return description
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 tables.""" [docs] def __init__(self, client: ODPS): """Initialize MaxCompute document loader. Args: client: odps.ODPS MaxCompute client object. """ self.client = client [docs] @classmethod def from_params( cls, endpoint: str, project: str, *, access_id: Optional[str] = None, secret_access_key: Optional[str] = None, ) -> MaxComputeAPIWrapper: """Convenience constructor that builds the odsp.ODPS MaxCompute client from given parameters. Args: endpoint: MaxCompute endpoint. project: A project is a basic organizational unit of MaxCompute, which is similar to a database. access_id: MaxCompute access ID. Should be passed in directly or set as the environment variable `MAX_COMPUTE_ACCESS_ID`. secret_access_key: MaxCompute secret access key. Should be passed in directly or set as the environment variable `MAX_COMPUTE_SECRET_ACCESS_KEY`. """ try: from odps import ODPS except ImportError as ex: raise ImportError( "Could not import pyodps python package. " "Please install it with `pip install pyodps` or refer to " "https://pyodps.readthedocs.io/." ) from ex
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_id=access_id, secret_access_key=secret_access_key, project=project, endpoint=endpoint, ) if not client.exist_project(project): raise ValueError(f'The project "{project}" does not exist.') return cls(client) [docs] def lazy_query(self, query: str) -> Iterator[dict]: # Execute SQL query. with self.client.execute_sql(query).open_reader() as reader: if reader.count == 0: raise ValueError("Table contains no data.") for record in reader: yield {k: v for k, v in record} [docs] def query(self, query: str) -> List[dict]: return list(self.lazy_query(query))
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): """Wrapper around the DataForSeo API.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True default_params: dict = Field( default={ "location_name": "United States", "language_code": "en", "depth": 10, "se_name": "google", "se_type": "organic", } ) """Default parameters to use for the DataForSEO SERP API.""" params: dict = Field(default={}) """Additional parameters to pass to the DataForSEO SERP API.""" api_login: Optional[str] = None """The API login to use for the DataForSEO SERP API.""" api_password: Optional[str] = None """The API password to use for the DataForSEO SERP API.""" json_result_types: Optional[list] = None """The JSON result types.""" json_result_fields: Optional[list] = None """The JSON result fields.""" top_count: Optional[int] = None """The number of top results to return.""" aiosession: Optional[aiohttp.ClientSession] = None """The aiohttp session to use for the DataForSEO SERP API.""" @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that login and password exists in environment."""
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 values [docs] async def arun(self, url: str) -> str: """Run request to DataForSEO SERP API and parse result async.""" return self._process_response(await self._aresponse_json(url)) [docs] def run(self, url: str) -> str: """Run request to DataForSEO SERP API and parse result async.""" return self._process_response(self._response_json(url)) [docs] def results(self, url: str) -> list: res = self._response_json(url) return self._filter_results(res) [docs] async def aresults(self, url: str) -> list: res = await self._aresponse_json(url) return self._filter_results(res) def _prepare_request(self, keyword: str) -> dict: """Prepare the request details for the DataForSEO SERP API.""" if self.api_login is None or self.api_password is None: raise ValueError("api_login or api_password is not provided") cred = base64.b64encode( f"{self.api_login}:{self.api_password}".encode("utf-8") ).decode("utf-8") headers = {"Authorization": f"Basic {cred}", "Content-Type": "application/json"} obj = {"keyword": quote(keyword)} obj = {**obj, **self.default_params, **self.params} data = [obj]
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: """Check the response from the DataForSEO SERP API for errors.""" if response.get("status_code") != 20000: raise ValueError( f"Got error from DataForSEO SERP API: {response.get('status_message')}" ) return response def _response_json(self, url: str) -> dict: """Use requests to run request to DataForSEO SERP API and return results.""" request_details = self._prepare_request(url) response = requests.post( request_details["url"], headers=request_details["headers"], json=request_details["data"], ) response.raise_for_status() return self._check_response(response.json()) async def _aresponse_json(self, url: str) -> dict: """Use aiohttp to request DataForSEO SERP API and return results async.""" request_details = self._prepare_request(url) if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.post( request_details["url"], headers=request_details["headers"], json=request_details["data"], ) as response: res = await response.json() else: async with self.aiosession.post( request_details["url"], headers=request_details["headers"],
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 = self.json_result_types if self.json_result_types is not None else [] for task in res.get("tasks", []): for result in task.get("result", []): for item in result.get("items", []): if len(types) == 0 or item.get("type", "") in types: self._cleanup_unnecessary_items(item) if len(item) != 0: output.append(item) if self.top_count is not None and len(output) >= self.top_count: break return output def _cleanup_unnecessary_items(self, d: dict) -> dict: fields = self.json_result_fields if self.json_result_fields is not None else [] if len(fields) > 0: for k, v in list(d.items()): if isinstance(v, dict): self._cleanup_unnecessary_items(v) if len(v) == 0: del d[k] elif k not in fields: del d[k] if "xpath" in d: del d["xpath"] if "position" in d: del d["position"] if "rectangle" in d: del d["rectangle"] for k, v in list(d.items()): if isinstance(v, dict): self._cleanup_unnecessary_items(v) return d def _process_response(self, res: dict) -> str:
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") items = result.get("items", []) if "answer_box" in item_types: toret = next( item for item in items if item.get("type") == "answer_box" ).get("text") elif "knowledge_graph" in item_types: toret = next( item for item in items if item.get("type") == "knowledge_graph" ).get("description") elif "featured_snippet" in item_types: toret = next( item for item in items if item.get("type") == "featured_snippet" ).get("description") elif "shopping" in item_types: toret = next( item for item in items if item.get("type") == "shopping" ).get("price") elif "organic" in item_types: toret = next( item for item in items if item.get("type") == "organic" ).get("description") if toret: break return toret
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 have the ``twilio`` python package installed, and the environment variables ``TWILIO_ACCOUNT_SID``, ``TWILIO_AUTH_TOKEN``, and ``TWILIO_FROM_NUMBER``, or pass `account_sid`, `auth_token`, and `from_number` as named parameters to the constructor. Example: .. code-block:: python from langchain.utilities.twilio import TwilioAPIWrapper twilio = TwilioAPIWrapper( account_sid="ACxxx", auth_token="xxx", from_number="+10123456789" ) twilio.run('test', '+12484345508') """ client: Any #: :meta private: account_sid: Optional[str] = None """Twilio account string identifier.""" auth_token: Optional[str] = None """Twilio auth token.""" from_number: Optional[str] = None """A Twilio phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, an [alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id), or a [Channel Endpoint address](https://www.twilio.com/docs/sms/channels#channel-addresses) that is enabled for the type of message you want to send. Phone numbers or
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`, this parameter must be empty. """ # noqa: E501 class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = False @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" try: from twilio.rest import Client except ImportError: raise ImportError( "Could not import twilio python package. " "Please install it with `pip install twilio`." ) account_sid = get_from_dict_or_env(values, "account_sid", "TWILIO_ACCOUNT_SID") auth_token = get_from_dict_or_env(values, "auth_token", "TWILIO_AUTH_TOKEN") values["from_number"] = get_from_dict_or_env( values, "from_number", "TWILIO_FROM_NUMBER" ) values["client"] = Client(account_sid, auth_token) return values [docs] def run(self, body: str, to: str) -> str: """Run body through Twilio and respond with message sid. Args: body: The text of the message you want to send. Can be up to 1,600 characters in length. to: The destination phone number in
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 channels. """ # noqa: E501 message = self.client.messages.create(to, from_=self.from_number, body=body) return message.sid
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_dict_or_env [docs]class HiddenPrints: """Context manager to hide prints.""" def __enter__(self) -> None: """Open file to pipe stdout to.""" self._original_stdout = sys.stdout sys.stdout = open(os.devnull, "w") def __exit__(self, *_: Any) -> None: """Close file that stdout was piped to.""" sys.stdout.close() sys.stdout = self._original_stdout [docs]class SerpAPIWrapper(BaseModel): """Wrapper around SerpAPI. To use, you should have the ``google-search-results`` python package installed, and the environment variable ``SERPAPI_API_KEY`` set with your API key, or pass `serpapi_api_key` as a named parameter to the constructor. Example: .. code-block:: python from langchain.utilities import SerpAPIWrapper serpapi = SerpAPIWrapper() """ search_engine: Any #: :meta private: params: dict = Field( default={ "engine": "google", "google_domain": "google.com", "gl": "us", "hl": "en", } ) serpapi_api_key: Optional[str] = None aiosession: Optional[aiohttp.ClientSession] = None class Config:
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 package exists in environment.""" serpapi_api_key = get_from_dict_or_env( values, "serpapi_api_key", "SERPAPI_API_KEY" ) values["serpapi_api_key"] = serpapi_api_key try: from serpapi import GoogleSearch values["search_engine"] = GoogleSearch except ImportError: raise ValueError( "Could not import serpapi python package. " "Please install it with `pip install google-search-results`." ) return values [docs] async def arun(self, query: str, **kwargs: Any) -> str: """Run query through SerpAPI and parse result async.""" return self._process_response(await self.aresults(query)) [docs] def run(self, query: str, **kwargs: Any) -> str: """Run query through SerpAPI and parse result.""" return self._process_response(self.results(query)) [docs] def results(self, query: str) -> dict: """Run query through SerpAPI and return the raw result.""" params = self.get_params(query) with HiddenPrints(): search = self.search_engine(params) res = search.get_dict() return res [docs] async def aresults(self, query: str) -> dict: """Use aiohttp to run query through SerpAPI and return the results async."""
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.serpapi_api_key params["output"] = "json" url = "https://serpapi.com/search" return url, params url, params = construct_url_and_params() if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.get(url, params=params) as response: res = await response.json() else: async with self.aiosession.get(url, params=params) as response: res = await response.json() return res [docs] def get_params(self, query: str) -> Dict[str, str]: """Get parameters for SerpAPI.""" _params = { "api_key": self.serpapi_api_key, "q": query, } params = {**self.params, **_params} return params @staticmethod def _process_response(res: dict) -> str: """Process response from SerpAPI.""" if "error" in res.keys(): raise ValueError(f"Got error from SerpAPI: {res['error']}") if "answer_box" in res.keys() and type(res["answer_box"]) == list: res["answer_box"] = res["answer_box"][0] if "answer_box" in res.keys() and "answer" in res["answer_box"].keys():
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() ): 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() and "title" in res["shopping_results"][0].keys() ): toret = res["shopping_results"][:3] elif ( "knowledge_graph" in res.keys() and "description" in res["knowledge_graph"].keys() ): toret = res["knowledge_graph"]["description"] elif "snippet" in res["organic_results"][0].keys(): toret = res["organic_results"][0]["snippet"] elif "link" in res["organic_results"][0].keys(): toret = res["organic_results"][0]["link"] elif ( "images_results" in res.keys() and "thumbnail" in res["images_results"][0].keys() ): thumbnails = [item["thumbnail"] for item in res["images_results"][:10]] toret = thumbnails else: toret = "No good search result found" return toret
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 Brave search engine.""" search_kwargs: dict = Field(default_factory=dict) """Additional keyword arguments to pass to the search request.""" base_url = "https://api.search.brave.com/res/v1/web/search" """The base URL for the Brave search engine.""" [docs] def run(self, query: str) -> str: """Query the Brave search engine and return the results as a JSON string. Args: query: The query to search for. Returns: The results as a JSON string. """ web_search_results = self._search_request(query=query) final_results = [ { "title": item.get("title"), "link": item.get("url"), "snippet": item.get("description"), } for item in web_search_results ] return json.dumps(final_results) [docs] def download_documents(self, query: str) -> List[Document]: """Query the Brave search engine and return the results as a list of Documents. Args: query: The query to search for. Returns: The results as a list of Documents. """ results = self._search_request(query) return [ Document( page_content=item.get("description"), metadata={"title": item.get("title"), "link": item.get("url")}, ) for item in results ]
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}} req.prepare_url(self.base_url, params) if req.url is None: raise ValueError("prepared url is None, this should not happen") response = requests.get(req.url, headers=headers) if not response.ok: raise Exception(f"HTTP error {response.status_code}") return response.json().get("web", {}).get("results", [])
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-cases where LangChain + Zapier NLA is powering a user-facing application, and LangChain needs access to the end-user's connected accounts on Zapier.com, you'll need to use oauth. Review the full docs above and reach out to nla@zapier.com for developer support. """ import json from typing import Any, Dict, List, Optional import aiohttp import requests from pydantic import BaseModel, Extra, root_validator from requests import Request, Session from langchain.utils import get_from_dict_or_env [docs]class ZapierNLAWrapper(BaseModel): """Wrapper for Zapier NLA. Full docs here: https://nla.zapier.com/start/ This wrapper supports both API Key and OAuth Credential auth methods. API Key is the fastest way to get started using this wrapper. Call this wrapper with either `zapier_nla_api_key` or `zapier_nla_oauth_access_token` arguments, or set the `ZAPIER_NLA_API_KEY` environment variable. If both arguments are set, the Access Token will take precedence. For use-cases where LangChain + Zapier NLA is powering a user-facing application, and LangChain needs access to the end-user's connected accounts on Zapier.com, you'll need to use OAuth. Review the full docs above to learn how to create your own provider and generate credentials. """
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) -> Dict[str, str]: """Format headers for requests.""" headers = { "Accept": "application/json", "Content-Type": "application/json", } if self.zapier_nla_oauth_access_token: headers.update( {"Authorization": f"Bearer {self.zapier_nla_oauth_access_token}"} ) else: headers.update({"X-API-Key": self.zapier_nla_api_key}) return headers def _get_session(self) -> Session: session = requests.Session() session.headers.update(self._format_headers()) return session async def _arequest(self, method: str, url: str, **kwargs: Any) -> Dict[str, Any]: """Make an async request.""" async with aiohttp.ClientSession(headers=self._format_headers()) as session: async with session.request(method, url, **kwargs) as response: response.raise_for_status() return await response.json() def _create_action_payload( # type: ignore[no-untyped-def] self, instructions: str, params: Optional[Dict] = None, preview_only=False ) -> Dict: """Create a payload for an action.""" data = params if params else {} data.update( { "instructions": instructions, } )
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/{action_id}/execute/" def _create_action_request( # type: ignore[no-untyped-def] self, action_id: str, instructions: str, params: Optional[Dict] = None, preview_only=False, ) -> Request: data = self._create_action_payload(instructions, params, preview_only) return Request( "POST", self._create_action_url(action_id), json=data, ) @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key exists in environment.""" zapier_nla_api_key_default = None # If there is a oauth_access_key passed in the values # we don't need a nla_api_key it can be blank if "zapier_nla_oauth_access_token" in values: zapier_nla_api_key_default = "" else: values["zapier_nla_oauth_access_token"] = "" # we require at least one API Key zapier_nla_api_key = get_from_dict_or_env( values, "zapier_nla_api_key", "ZAPIER_NLA_API_KEY", zapier_nla_api_key_default, ) values["zapier_nla_api_key"] = zapier_nla_api_key return values
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 exposed. Else will contain a list of action objects: [{ "id": str, "description": str, "params": Dict[str, str] }] `params` will always contain an `instructions` key, the only required param. All others optional and if provided will override any AI guesses (see "understanding the AI guessing flow" here: https://nla.zapier.com/api/v1/docs) """ response = await self._arequest("GET", self.zapier_nla_api_base + "exposed/") return response["results"] [docs] def list(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 exposed. Else will contain a list of action objects: [{ "id": str, "description": str, "params": Dict[str, str] }] `params` will always contain an `instructions` key, the only required param. All others optional and if provided will override any AI guesses (see "understanding the AI guessing flow" here: https://nla.zapier.com/docs/using-the-api#ai-guessing) """
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: raise requests.HTTPError( f"An unauthorized response occurred. Check that your " f"access token is correct and doesn't need to be " f"refreshed. Err: {http_err}" ) raise requests.HTTPError( f"An unauthorized response occurred. Check that your api " f"key is correct. Err: {http_err}" ) raise http_err return response.json()["results"] [docs] def run( self, action_id: str, instructions: str, params: Optional[Dict] = None ) -> 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 tokens) making it safe to inject into the prompt of another LLM call. """ session = self._get_session() request = self._create_action_request(action_id, instructions, params) response = session.send(session.prepare_request(request)) response.raise_for_status() return response.json()["result"] [docs] async def arun( self, action_id: str, instructions: str, params: Optional[Dict] = None ) -> Dict:
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 tokens) making it safe to inject into the prompt of another LLM call. """ response = await self._arequest( "POST", self._create_action_url(action_id), json=self._create_action_payload(instructions, params), ) return response["result"] [docs] def preview( self, action_id: str, instructions: str, params: Optional[Dict] = None ) -> Dict: """Same as run, but instead of actually executing the action, will instead return a preview of params that have been guessed by the AI in case you need to explicitly review before executing.""" session = self._get_session() params = params if params else {} params.update({"preview_only": True}) request = self._create_action_request(action_id, instructions, params, True) response = session.send(session.prepare_request(request)) response.raise_for_status() return response.json()["input_params"] [docs] async def apreview( self, action_id: str, instructions: str, params: Optional[Dict] = None ) -> Dict: """Same as run, but instead of actually executing the action, will instead return a preview of params that have been guessed by the AI in case you need to explicitly review before executing.""" response = await self._arequest( "POST",
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] """Same as run, but returns a stringified version of the JSON for insertting back into an LLM.""" data = self.run(*args, **kwargs) return json.dumps(data) [docs] async def arun_as_str(self, *args, **kwargs) -> str: # type: ignore[no-untyped-def] """Same as run, but returns a stringified version of the JSON for insertting back into an LLM.""" data = await self.arun(*args, **kwargs) return json.dumps(data) [docs] def preview_as_str(self, *args, **kwargs) -> str: # type: ignore[no-untyped-def] """Same as preview, but returns a stringified version of the JSON for insertting back into an LLM.""" data = self.preview(*args, **kwargs) return json.dumps(data) [docs] async def apreview_as_str( # type: ignore[no-untyped-def] self, *args, **kwargs ) -> str: """Same as preview, but returns a stringified version of the JSON for insertting back into an LLM.""" data = await self.apreview(*args, **kwargs) return json.dumps(data) [docs] def list_as_str(self) -> 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 JSON for insertting back into an LLM.""" actions = await self.alist() return json.dumps(actions)
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 class for starting subprocesses. Uses the python built-in subprocesses.run() Persistent processes are **not** available on Windows systems, as pexpect makes use of Unix pseudoterminals (ptys). MacOS and Linux are okay. Example: .. code-block:: python from langchain.utilities.bash import BashProcess bash = BashProcess( strip_newlines = False, return_err_output = False, persistent = False ) bash.run('echo \'hello world\'') """ strip_newlines: bool = False """Whether or not to run .strip() on the output""" return_err_output: bool = False """Whether or not to return the output of a failed command, or just the error message and stacktrace""" persistent: bool = False """Whether or not to spawn a persistent session NOTE: Unavailable for Windows environments""" [docs] def __init__( self, strip_newlines: bool = False, return_err_output: bool = False, persistent: bool = False, ): """ Initializes with default settings """ self.strip_newlines = strip_newlines self.return_err_output = return_err_output self.prompt = "" self.process = None if persistent: self.prompt = str(uuid4())
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": raise ValueError( "Persistent bash processes are not yet supported on Windows." ) try: import pexpect except ImportError: raise ImportError( "pexpect required for persistent bash processes." " To install, run `pip install pexpect`." ) return pexpect @staticmethod def _initialize_persistent_process(self: BashProcess, prompt: str) -> pexpect.spawn: # Start bash in a clean environment # Doesn't work on windows """ Initializes a persistent bash setting in a clean environment. NOTE: Unavailable on Windows Args: Prompt(str): the bash command to execute """ # noqa: E501 pexpect = self._lazy_import_pexpect() process = pexpect.spawn( "env", ["-i", "bash", "--norc", "--noprofile"], encoding="utf-8" ) # Set the custom prompt process.sendline("PS1=" + prompt) process.expect_exact(prompt, timeout=10) return process [docs] def run(self, commands: Union[str, List[str]]) -> str: """ Run commands in either an existing persistent subprocess or on in a new subprocess environment. Args: commands(List[str]): a list of commands to execute in the session """ # noqa: E501
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(commands) def _run(self, command: str) -> str: """ Runs a command in a subprocess and returns the output. Args: command: The command to run """ # noqa: E501 try: output = subprocess.run( command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ).stdout.decode() except subprocess.CalledProcessError as error: if self.return_err_output: return error.stdout.decode() return str(error) if self.strip_newlines: output = output.strip() return output [docs] def process_output(self, output: str, command: str) -> str: """ Uses regex to remove the command from the output Args: output: a process' output string command: the executed command """ # noqa: E501 pattern = re.escape(command) + r"\s*\n" output = re.sub(pattern, "", output, count=1) return output.strip() def _run_persistent(self, command: str) -> str: """ Runs commands in a persistent environment and returns the output. Args: command: the command to execute """ # noqa: E501 pexpect = self._lazy_import_pexpect() if self.process is None:
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: self.process.expect([self.prompt, pexpect.EOF], timeout=10) except pexpect.TIMEOUT: return f"Timeout error while executing command {command}" if self.process.after == pexpect.EOF: return f"Exited with error status: {self.process.exitstatus}" output = self.process.before output = self.process_output(output, command) if self.strip_newlines: return output.strip() return output
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 JiraAPIWrapper(BaseModel): """Wrapper for Jira API.""" jira: Any #: :meta private: confluence: Any jira_username: Optional[str] = None jira_api_token: Optional[str] = None jira_instance_url: Optional[str] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" jira_username = get_from_dict_or_env(values, "jira_username", "JIRA_USERNAME") values["jira_username"] = jira_username jira_api_token = get_from_dict_or_env( values, "jira_api_token", "JIRA_API_TOKEN" ) values["jira_api_token"] = jira_api_token jira_instance_url = get_from_dict_or_env( values, "jira_instance_url", "JIRA_INSTANCE_URL" ) values["jira_instance_url"] = jira_instance_url try: from atlassian import Confluence, Jira except ImportError: raise ImportError( "atlassian-python-api is not installed. " "Please install it with `pip install atlassian-python-api`" ) jira = Jira( url=jira_instance_url,
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, cloud=True, ) values["jira"] = jira values["confluence"] = confluence return values [docs] def parse_issues(self, issues: Dict) -> List[dict]: parsed = [] for issue in issues["issues"]: key = issue["key"] summary = issue["fields"]["summary"] created = issue["fields"]["created"][0:10] priority = issue["fields"]["priority"]["name"] status = issue["fields"]["status"]["name"] try: assignee = issue["fields"]["assignee"]["displayName"] except Exception: assignee = "None" rel_issues = {} for related_issue in issue["fields"]["issuelinks"]: if "inwardIssue" in related_issue.keys(): rel_type = related_issue["type"]["inward"] rel_key = related_issue["inwardIssue"]["key"] rel_summary = related_issue["inwardIssue"]["fields"]["summary"] if "outwardIssue" in related_issue.keys(): rel_type = related_issue["type"]["outward"] rel_key = related_issue["outwardIssue"]["key"] rel_summary = related_issue["outwardIssue"]["fields"]["summary"] rel_issues = {"type": rel_type, "key": rel_key, "summary": rel_summary} parsed.append( { "key": key,
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, } ) return parsed [docs] def parse_projects(self, projects: List[dict]) -> List[dict]: parsed = [] for project in projects: id = project["id"] key = project["key"] name = project["name"] type = project["projectTypeKey"] style = project["style"] parsed.append( {"id": id, "key": key, "name": name, "type": type, "style": style} ) return parsed [docs] def search(self, query: str) -> str: issues = self.jira.jql(query) parsed_issues = self.parse_issues(issues) parsed_issues_str = ( "Found " + str(len(parsed_issues)) + " issues:\n" + str(parsed_issues) ) return parsed_issues_str [docs] def project(self) -> str: projects = self.jira.projects() parsed_projects = self.parse_projects(projects) parsed_projects_str = ( "Found " + str(len(parsed_projects)) + " projects:\n" + str(parsed_projects) ) return parsed_projects_str [docs] def issue_create(self, query: str) -> str: try: import json except ImportError: raise ImportError( "json is not installed. Please install it with `pip install json`" ) params = json.loads(query)
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 json`" ) params = json.loads(query) return self.confluence.create_page(**dict(params)) [docs] def other(self, query: str) -> str: try: import json except ImportError: raise ImportError( "json is not installed. Please install it with `pip install json`" ) params = json.loads(query) jira_function = getattr(self.jira, params["function"]) return jira_function(*params.get("args", []), **params.get("kwargs", {})) [docs] def run(self, mode: str, query: str) -> str: if mode == "jql": return self.search(query) elif mode == "get_projects": return self.project() elif mode == "create_issue": return self.issue_create(query) elif mode == "other": return self.other(query) elif mode == "create_page": return self.page_create(query) else: raise ValueError(f"Got unexpected mode {mode}")
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.Issue import Issue [docs]class GitHubAPIWrapper(BaseModel): """Wrapper for GitHub API.""" github: Any #: :meta private: github_repo_instance: Any #: :meta private: github_repository: Optional[str] = None github_app_id: Optional[str] = None github_app_private_key: Optional[str] = None github_branch: Optional[str] = None github_base_branch: Optional[str] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" github_repository = get_from_dict_or_env( values, "github_repository", "GITHUB_REPOSITORY" ) github_app_id = get_from_dict_or_env(values, "github_app_id", "GITHUB_APP_ID") github_app_private_key = get_from_dict_or_env( values, "github_app_private_key", "GITHUB_APP_PRIVATE_KEY" ) github_branch = get_from_dict_or_env( values, "github_branch", "GITHUB_BRANCH", default="master" ) github_base_branch = get_from_dict_or_env( values, "github_base_branch", "GITHUB_BASE_BRANCH", default="master" ) try: from github import Auth, GithubIntegration except ImportError:
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 = f.read() auth = Auth.AppAuth( github_app_id, private_key, ) gi = GithubIntegration(auth=auth) installation = gi.get_installations()[0] # create a GitHub instance: g = installation.get_github_for_installation() values["github"] = g values["github_repo_instance"] = g.get_repo(github_repository) values["github_repository"] = github_repository values["github_app_id"] = github_app_id values["github_app_private_key"] = github_app_private_key values["github_branch"] = github_branch values["github_base_branch"] = github_base_branch return values [docs] def parse_issues(self, issues: List[Issue]) -> List[dict]: """ Extracts title and number from each Issue and puts them in a dictionary Parameters: issues(List[Issue]): A list of Github Issue objects Returns: List[dict]: A dictionary of issue titles and numbers """ parsed = [] for issue in issues: title = issue.title number = issue.number parsed.append({"title": title, "number": number}) return parsed [docs] def get_issues(self) -> str: """ Fetches all open issues from the repo Returns: str: A plaintext report containing the number of issues and each issue's title and number. """
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_issues) ) return parsed_issues_str else: return "No open issues available" [docs] def get_issue(self, issue_number: int) -> Dict[str, Any]: """ Fetches a specific issue and its first 10 comments Parameters: issue_number(int): The number for the github issue Returns: dict: A doctionary containing the issue's title, body, and comments as a string """ issue = self.github_repo_instance.get_issue(number=issue_number) page = 0 comments: List[dict] = [] while len(comments) <= 10: comments_page = issue.get_comments().get_page(page) if len(comments_page) == 0: break for comment in comments_page: comments.append({"body": comment.body, "user": comment.user.login}) page += 1 return { "title": issue.title, "body": issue.body, "comments": str(comments), } [docs] def create_pull_request(self, pr_query: str) -> str: """ Makes a pull request from the bot's branch to the base branch Parameters: pr_query(str): a string which contains the PR title and the PR body. The title is the first line in the string, and the body are the rest of the string.
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 commits are already in the master branch""" else: try: title = pr_query.split("\n")[0] body = pr_query[len(title) + 2 :] pr = self.github_repo_instance.create_pull( title=title, body=body, head=self.github_branch, base=self.github_base_branch, ) return f"Successfully created PR number {pr.number}" except Exception as e: return "Unable to make pull request due to error:\n" + str(e) [docs] def comment_on_issue(self, comment_query: str) -> str: """ Adds a comment to a github issue Parameters: comment_query(str): a string which contains the issue number, two newlines, and the comment. for example: "1\n\nWorking on it now" adds the comment "working on it now" to issue 1 Returns: str: A success or failure message """ issue_number = int(comment_query.split("\n\n")[0]) comment = comment_query[len(str(issue_number)) + 2 :] try: issue = self.github_repo_instance.get_issue(number=issue_number) issue.create_comment(comment) return "Commented on issue " + str(issue_number) except Exception as e: return "Unable to make comment due to error:\n" + str(e)
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 line in the string, and the contents are the rest of the string. For example, "hello_world.md\n# Hello World!" Returns: str: A success or failure message """ file_path = file_query.split("\n")[0] file_contents = file_query[len(file_path) + 2 :] try: exists = self.github_repo_instance.get_contents(file_path) if exists is None: self.github_repo_instance.create_file( path=file_path, message="Create " + file_path, content=file_contents, branch=self.github_branch, ) return "Created file " + file_path else: return f"File already exists at {file_path}. Use update_file instead" except Exception as e: return "Unable to make file due to error:\n" + str(e) [docs] def read_file(self, file_path: str) -> str: """ Reads a file from the github repo Parameters: file_path(str): the file path Returns: str: The file decoded as a string """ file = self.github_repo_instance.get_contents(file_path) return file.decoded_content.decode("utf-8") [docs] def update_file(self, file_query: str) -> str: """ Updates a file with new content. Parameters:
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: /test/hello.txt OLD <<<< Hello Earth! >>>> OLD NEW <<<< Hello Mars! >>>> NEW Returns: A success or failure message """ try: file_path = file_query.split("\n")[0] old_file_contents = ( file_query.split("OLD <<<<")[1].split(">>>> OLD")[0].strip() ) new_file_contents = ( file_query.split("NEW <<<<")[1].split(">>>> NEW")[0].strip() ) file_content = self.read_file(file_path) updated_file_content = file_content.replace( old_file_contents, new_file_contents ) if file_content == updated_file_content: return ( "File content was not updated because old content was not found." "It may be helpful to use the read_file action to get " "the current file contents." ) self.github_repo_instance.update_file( path=file_path, message="Update " + file_path, content=updated_file_content, branch=self.github_branch, sha=self.github_repo_instance.get_contents(file_path).sha, ) return "Updated file " + file_path except Exception as e: return "Unable to update file due to error:\n" + str(e) [docs] def delete_file(self, file_path: str) -> str: """
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( path=file_path, message="Delete " + file_path, branch=self.github_branch, sha=file.sha, ) return "Deleted file " + file_path except Exception as e: return "Unable to delete file due to error:\n" + str(e) [docs] def run(self, mode: str, query: str) -> str: if mode == "get_issues": return self.get_issues() elif mode == "get_issue": return json.dumps(self.get_issue(int(query))) elif mode == "comment_on_issue": return self.comment_on_issue(query) elif mode == "create_file": return self.create_file(query) elif mode == "create_pull_request": return self.create_pull_request(query) elif mode == "read_file": return self.read_file(query) elif mode == "update_file": return self.update_file(query) elif mode == "delete_file": return self.delete_file(query) else: raise ValueError("Invalid mode" + mode)
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 OpenWeatherMap API using PyOWM. Docs for using: 1. Go to OpenWeatherMap and sign up for an API key 2. Save your API KEY into OPENWEATHERMAP_API_KEY env variable 3. pip install pyowm """ owm: Any openweathermap_api_key: Optional[str] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key exists in environment.""" openweathermap_api_key = get_from_dict_or_env( values, "openweathermap_api_key", "OPENWEATHERMAP_API_KEY" ) try: import pyowm except ImportError: raise ImportError( "pyowm is not installed. Please install it with `pip install pyowm`" ) owm = pyowm.OWM(openweathermap_api_key) values["owm"] = owm return values def _format_weather_info(self, location: str, w: Any) -> str: detailed_status = w.detailed_status wind = w.wind() humidity = w.humidity temperature = w.temperature("celsius") rain = w.rain heat_index = w.heat_index clouds = w.clouds return (
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"Temperature: \n" f" - Current: {temperature['temp']}°C\n" f" - High: {temperature['temp_max']}°C\n" f" - Low: {temperature['temp_min']}°C\n" f" - Feels like: {temperature['feels_like']}°C\n" f"Rain: {rain}\n" f"Heat index: {heat_index}\n" f"Cloud cover: {clouds}%" ) [docs] def run(self, location: str) -> str: """Get the current weather information for a specified location.""" mgr = self.owm.weather_manager() observation = mgr.weather_at_place(location) w = observation.weather return self._format_weather_info(location, w)
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, user: Optional[str] = None, organisation: Optional[str] = None, prompt: Optional[str] = None, retry_count: Optional[int] = None, cache: Optional[str] = None, cache_force_refresh: Optional[str] = None, cache_age: Optional[int] = None, ) -> Dict[str, str]: assert retry_count is None or retry_count in range( 1, 6 ), "retry_count must be an integer and in range [1, 2, 3, 4, 5]" assert cache is None or cache in [ "simple", "semantic", ], "cache must be 'simple' or 'semantic'" assert cache_force_refresh is None or ( isinstance(cache_force_refresh, str) and cache_force_refresh in ["True", "False"] ), "cache_force_refresh must be 'True' or 'False'" assert cache_age is None or isinstance( cache_age, int ), "cache_age must be an integer" os.environ["OPENAI_API_BASE"] = Portkey.base 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:
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_age: headers["Cache-Control"] = f"max-age:{str(cache_age)}" metadata = {} if environment: metadata["_environment"] = environment if user: metadata["_user"] = user if organisation: metadata["_organisation"] = organisation if prompt: metadata["_prompt"] = prompt if metadata: headers.update({"x-portkey-metadata": json.dumps(metadata)}) return headers
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 the TensorFlow Datasets. The Current implementation can work only with datasets that fit in a memory. `TensorFlow Datasets` is a collection of datasets ready to use, with TensorFlow or other Python ML frameworks, such as Jax. All datasets are exposed as `tf.data.Datasets`. To get started see the Guide: https://www.tensorflow.org/datasets/overview and the list of datasets: https://www.tensorflow.org/datasets/catalog/ overview#all_datasets You have to provide the sample_to_document_function: a function that a sample from the dataset-specific format to the Document. Attributes: dataset_name: the name of the dataset to load split_name: the name of the split to load. Defaults to "train". load_max_docs: a limit to the number of loaded documents. Defaults to 100. sample_to_document_function: a function that converts a dataset sample to a Document Example: .. code-block:: python from langchain.utilities import TensorflowDatasets def mlqaen_example_to_document(example: dict) -> Document: return Document( page_content=decode_to_str(example["context"]), metadata={ "id": decode_to_str(example["id"]), "title": decode_to_str(example["title"]), "question": decode_to_str(example["question"]), "answer": decode_to_str(example["answers"]["text"][0]), }, )
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html