id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
3b989edf2637-8
) -> str: """Asynchronously version of `run`.""" _params = { "q": query, } params = {**self.params, **_params, **kwargs} if self.query_suffix and len(self.query_suffix) > 0: params["q"] += " " + self.query_suffix if isinstance(query_suffix, str) and len(query_suffix) > 0: params["q"] += " " + query_suffix if isinstance(engines, list) and len(engines) > 0: params["engines"] = ",".join(engines) res = await self._asearx_api_query(params) if len(res.answers) > 0: toret = res.answers[0] # only return the content of the results list elif len(res.results) > 0: toret = "\n\n".join([r.get("content", "") for r in res.results[: self.k]]) else: toret = "No good search result found" return toret [docs] def results( self, query: str, num_results: int, engines: Optional[List[str]] = None, categories: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> List[Dict]: """Run query through Searx API and returns the results with metadata. Args: query: The query to search for. query_suffix: Extra suffix appended to the query. num_results: Limit the number of results to return. engines: List of engines to use for the query.
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
3b989edf2637-9
engines: List of engines to use for the query. categories: List of categories to use for the query. **kwargs: extra parameters to pass to the searx API. Returns: Dict with the following keys: { snippet: The description of the result. title: The title of the result. link: The link to the result. engines: The engines used for the result. category: Searx category of the result. } """ _params = { "q": query, } params = {**self.params, **_params, **kwargs} if self.query_suffix and len(self.query_suffix) > 0: params["q"] += " " + self.query_suffix if isinstance(query_suffix, str) and len(query_suffix) > 0: params["q"] += " " + query_suffix if isinstance(engines, list) and len(engines) > 0: params["engines"] = ",".join(engines) if isinstance(categories, list) and len(categories) > 0: params["categories"] = ",".join(categories) results = self._searx_api_query(params).results[:num_results] if len(results) == 0: return [{"Result": "No good Search Result was found"}] return [ { "snippet": result.get("content", ""), "title": result["title"], "link": result["url"], "engines": result["engines"], "category": result["category"], } for result in results ] [docs] async def aresults( self,
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
3b989edf2637-10
] [docs] async def aresults( self, query: str, num_results: int, engines: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> List[Dict]: """Asynchronously query with json results. Uses aiohttp. See `results` for more info. """ _params = { "q": query, } params = {**self.params, **_params, **kwargs} if self.query_suffix and len(self.query_suffix) > 0: params["q"] += " " + self.query_suffix if isinstance(query_suffix, str) and len(query_suffix) > 0: params["q"] += " " + query_suffix if isinstance(engines, list) and len(engines) > 0: params["engines"] = ",".join(engines) results = (await self._asearx_api_query(params)).results[:num_results] if len(results) == 0: return [{"Result": "No good Search Result was found"}] return [ { "snippet": result.get("content", ""), "title": result["title"], "link": result["url"], "engines": result["engines"], "category": result["category"], } for result in results ] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
65732cf5e956-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://python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
65732cf5e956-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}" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
56f2766f87ff-0
Source code for langchain.utilities.powerbi """Wrapper around a Power BI endpoint.""" from __future__ import annotations import asyncio import logging import os from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union import aiohttp import requests from aiohttp import ServerTimeoutError from pydantic import BaseModel, Field, root_validator, validator from requests.exceptions import Timeout _LOGGER = logging.getLogger(__name__) BASE_URL = os.getenv("POWERBI_BASE_URL", "https://api.powerbi.com/v1.0/myorg") if TYPE_CHECKING: from azure.core.credentials import TokenCredential [docs]class PowerBIDataset(BaseModel): """Create PowerBI engine from dataset ID and credential or token. Use either the credential or a supplied token to authenticate. If both are supplied the credential is used to generate a token. The impersonated_user_name is the UPN of a user to be impersonated. If the model is not RLS enabled, this will be ignored. """ dataset_id: str table_names: List[str] group_id: Optional[str] = None credential: Optional[TokenCredential] = None token: Optional[str] = None impersonated_user_name: Optional[str] = None sample_rows_in_table_info: int = Field(default=1, gt=0, le=10) schemas: Dict[str, str] = Field(default_factory=dict) aiosession: Optional[aiohttp.ClientSession] = None class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True @validator("table_names", allow_reuse=True) def fix_table_names(cls, table_names: List[str]) -> List[str]: """Fix the table names."""
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
56f2766f87ff-1
"""Fix the table names.""" return [fix_table_name(table) for table in table_names] @root_validator(pre=True, allow_reuse=True) def token_or_credential_present(cls, values: Dict[str, Any]) -> Dict[str, Any]: """Validate that at least one of token and credentials is present.""" if "token" in values or "credential" in values: return values raise ValueError("Please provide either a credential or a token.") @property def request_url(self) -> str: """Get the request url.""" if self.group_id: return f"{BASE_URL}/groups/{self.group_id}/datasets/{self.dataset_id}/executeQueries" # noqa: E501 # pylint: disable=C0301 return f"{BASE_URL}/datasets/{self.dataset_id}/executeQueries" # noqa: E501 # pylint: disable=C0301 @property def headers(self) -> Dict[str, str]: """Get the token.""" if self.token: return { "Content-Type": "application/json", "Authorization": "Bearer " + self.token, } from azure.core.exceptions import ( ClientAuthenticationError, # pylint: disable=import-outside-toplevel ) if self.credential: try: token = self.credential.get_token( "https://analysis.windows.net/powerbi/api/.default" ).token return { "Content-Type": "application/json", "Authorization": "Bearer " + token, } except Exception as exc: # pylint: disable=broad-exception-caught raise ClientAuthenticationError( "Could not get a token from the supplied credentials." ) from exc
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
56f2766f87ff-2
"Could not get a token from the supplied credentials." ) from exc raise ClientAuthenticationError("No credential or token supplied.") [docs] def get_table_names(self) -> Iterable[str]: """Get names of tables available.""" return self.table_names [docs] def get_schemas(self) -> str: """Get the available schema's.""" if self.schemas: return ", ".join([f"{key}: {value}" for key, value in self.schemas.items()]) return "No known schema's yet. Use the schema_powerbi tool first." @property def table_info(self) -> str: """Information about all tables in the database.""" return self.get_table_info() def _get_tables_to_query( self, table_names: Optional[Union[List[str], str]] = None ) -> Optional[List[str]]: """Get the tables names that need to be queried, after checking they exist.""" if table_names is not None: if ( isinstance(table_names, list) and len(table_names) > 0 and table_names[0] != "" ): fixed_tables = [fix_table_name(table) for table in table_names] non_existing_tables = [ table for table in fixed_tables if table not in self.table_names ] if non_existing_tables: _LOGGER.warning( "Table(s) %s not found in dataset.", ", ".join(non_existing_tables), ) tables = [ table for table in fixed_tables if table not in non_existing_tables ] return tables if tables else None if isinstance(table_names, str) and table_names != "":
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
56f2766f87ff-3
if isinstance(table_names, str) and table_names != "": if table_names not in self.table_names: _LOGGER.warning("Table %s not found in dataset.", table_names) return None return [fix_table_name(table_names)] return self.table_names def _get_tables_todo(self, tables_todo: List[str]) -> List[str]: """Get the tables that still need to be queried.""" return [table for table in tables_todo if table not in self.schemas] def _get_schema_for_tables(self, table_names: List[str]) -> str: """Create a string of the table schemas for the supplied tables.""" schemas = [ schema for table, schema in self.schemas.items() if table in table_names ] return ", ".join(schemas) [docs] def get_table_info( self, table_names: Optional[Union[List[str], str]] = None ) -> str: """Get information about specified tables.""" tables_requested = self._get_tables_to_query(table_names) if tables_requested is None: return "No (valid) tables requested." tables_todo = self._get_tables_todo(tables_requested) for table in tables_todo: self._get_schema(table) return self._get_schema_for_tables(tables_requested) [docs] async def aget_table_info( self, table_names: Optional[Union[List[str], str]] = None ) -> str: """Get information about specified tables.""" tables_requested = self._get_tables_to_query(table_names) if tables_requested is None: return "No (valid) tables requested." tables_todo = self._get_tables_todo(tables_requested)
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
56f2766f87ff-4
tables_todo = self._get_tables_todo(tables_requested) await asyncio.gather(*[self._aget_schema(table) for table in tables_todo]) return self._get_schema_for_tables(tables_requested) def _get_schema(self, table: str) -> None: """Get the schema for a table.""" try: result = self.run( f"EVALUATE TOPN({self.sample_rows_in_table_info}, {table})" ) self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"]) except Timeout: _LOGGER.warning("Timeout while getting table info for %s", table) self.schemas[table] = "unknown" except Exception as exc: # pylint: disable=broad-exception-caught _LOGGER.warning("Error while getting table info for %s: %s", table, exc) self.schemas[table] = "unknown" async def _aget_schema(self, table: str) -> None: """Get the schema for a table.""" try: result = await self.arun( f"EVALUATE TOPN({self.sample_rows_in_table_info}, {table})" ) self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"]) except ServerTimeoutError: _LOGGER.warning("Timeout while getting table info for %s", table) self.schemas[table] = "unknown" except Exception as exc: # pylint: disable=broad-exception-caught _LOGGER.warning("Error while getting table info for %s: %s", table, exc) self.schemas[table] = "unknown"
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
56f2766f87ff-5
self.schemas[table] = "unknown" def _create_json_content(self, command: str) -> dict[str, Any]: """Create the json content for the request.""" return { "queries": [{"query": rf"{command}"}], "impersonatedUserName": self.impersonated_user_name, "serializerSettings": {"includeNulls": True}, } [docs] def run(self, command: str) -> Any: """Execute a DAX command and return a json representing the results.""" _LOGGER.debug("Running command: %s", command) result = requests.post( self.request_url, json=self._create_json_content(command), headers=self.headers, timeout=10, ) return result.json() [docs] async def arun(self, command: str) -> Any: """Execute a DAX command and return the result asynchronously.""" _LOGGER.debug("Running command: %s", command) if self.aiosession: async with self.aiosession.post( self.request_url, headers=self.headers, json=self._create_json_content(command), timeout=10, ) as response: response_json = await response.json() return response_json async with aiohttp.ClientSession() as session: async with session.post( self.request_url, headers=self.headers, json=self._create_json_content(command), timeout=10, ) as response: response_json = await response.json() return response_json def json_to_md( json_contents: List[Dict[str, Union[str, int, float]]], table_name: Optional[str] = None, ) -> str:
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
56f2766f87ff-6
table_name: Optional[str] = None, ) -> str: """Converts a JSON object to a markdown table.""" output_md = "" headers = json_contents[0].keys() for header in headers: header.replace("[", ".").replace("]", "") if table_name: header.replace(f"{table_name}.", "") output_md += f"| {header} " output_md += "|\n" for row in json_contents: for value in row.values(): output_md += f"| {value} " output_md += "|\n" return output_md def fix_table_name(table: str) -> str: """Add single quotes around table names that contain spaces.""" if " " in table and not table.startswith("'") and not table.endswith("'"): return f"'{table}'" return table By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
bedde0423e99-0
Source code for langchain.utilities.pupmed import json import logging import time import urllib.error import urllib.request from typing import List from pydantic import BaseModel, Extra from langchain.schema import Document logger = logging.getLogger(__name__) [docs]class PubMedAPIWrapper(BaseModel): """ 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 load_max_docs: a limit to the number of loaded documents load_all_available_meta: if True: the `metadata` of the loaded Documents gets all available meta info (see https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch) if False: the `metadata` gets only the most informative fields. """ 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 load_max_docs: int = 25 ARXIV_MAX_QUERY_LENGTH = 300 doc_content_chars_max: int = 2000 load_all_available_meta: bool = False email: str = "[email protected]" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] def run(self, query: str) -> str:
https://python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
bedde0423e99-1
[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['pub_date']}\nTitle: {result['title']}\n" f"Summary: {result['summary']}" for result in self.load(query[: self.ARXIV_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 load(self, query: str) -> List[dict]: """ Search PubMed for documents matching the query. Return a list of dictionaries containing the document metadata. """ url = ( self.base_url_esearch + "db=pubmed&term=" + str({urllib.parse.quote(query)}) + f"&retmode=json&retmax={self.top_k_results}&usehistory=y" ) result = urllib.request.urlopen(url) text = result.read().decode("utf-8") json_text = json.loads(text) articles = [] webenv = json_text["esearchresult"]["webenv"] for uid in json_text["esearchresult"]["idlist"]: article = self.retrieve_article(uid, webenv) articles.append(article)
https://python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
bedde0423e99-2
article = self.retrieve_article(uid, webenv) articles.append(article) # Convert the list of articles to a JSON string return articles def _transform_doc(self, doc: dict) -> Document: summary = doc.pop("summary") return Document(page_content=summary, metadata=doc) [docs] def load_docs(self, query: str) -> List[Document]: document_dicts = self.load(query=query) return [self._transform_doc(d) for d in document_dicts] [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 except urllib.error.HTTPError as e: if e.code == 429 and retry < self.max_retry: # Too Many Requests error # 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") # Get title title = "" if "<ArticleTitle>" in xml_text and "</ArticleTitle>" in xml_text: start_tag = "<ArticleTitle>" end_tag = "</ArticleTitle>" title = xml_text[
https://python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
bedde0423e99-3
end_tag = "</ArticleTitle>" title = xml_text[ xml_text.index(start_tag) + len(start_tag) : xml_text.index(end_tag) ] # Get abstract abstract = "" if "<AbstractText>" in xml_text and "</AbstractText>" in xml_text: start_tag = "<AbstractText>" end_tag = "</AbstractText>" abstract = xml_text[ xml_text.index(start_tag) + len(start_tag) : xml_text.index(end_tag) ] # Get publication date pub_date = "" if "<PubDate>" in xml_text and "</PubDate>" in xml_text: start_tag = "<PubDate>" end_tag = "</PubDate>" pub_date = xml_text[ xml_text.index(start_tag) + len(start_tag) : xml_text.index(end_tag) ] # Return article as dictionary article = { "uid": uid, "title": title, "summary": abstract, "pub_date": pub_date, } return article By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
a2b37c2ea00a-0
Source code for langchain.utilities.apify from typing import Any, Callable, Dict, Optional from pydantic import BaseModel, root_validator from langchain.document_loaders import ApifyDatasetLoader from langchain.document_loaders.base import Document from langchain.utils import get_from_dict_or_env [docs]class ApifyWrapper(BaseModel): """Wrapper around Apify. To use, you should have the ``apify-client`` python package installed, and the environment variable ``APIFY_API_TOKEN`` set with your API key, or pass `apify_api_token` as a named parameter to the constructor. """ apify_client: Any apify_client_async: Any @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate environment. Validate that an Apify API token is set and the apify-client Python package exists in the current environment. """ apify_api_token = get_from_dict_or_env( values, "apify_api_token", "APIFY_API_TOKEN" ) try: from apify_client import ApifyClient, ApifyClientAsync values["apify_client"] = ApifyClient(apify_api_token) values["apify_client_async"] = ApifyClientAsync(apify_api_token) except ImportError: raise ValueError( "Could not import apify-client Python package. " "Please install it with `pip install apify-client`." ) return values [docs] def call_actor( self, actor_id: str, run_input: Dict, dataset_mapping_function: Callable[[Dict], Document], *, build: Optional[str] = None,
https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
a2b37c2ea00a-1
*, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None, ) -> ApifyDatasetLoader: """Run an Actor on the Apify platform and wait for results to be ready. Args: actor_id (str): The ID or name of the Actor on the Apify platform. run_input (Dict): The input object of the Actor that you're trying to run. dataset_mapping_function (Callable): A function that takes a single dictionary (an Apify dataset item) and converts it to an instance of the Document class. build (str, optional): Optionally specifies the actor build to run. It can be either a build tag or build number. memory_mbytes (int, optional): Optional memory limit for the run, in megabytes. timeout_secs (int, optional): Optional timeout for the run, in seconds. Returns: ApifyDatasetLoader: A loader that will fetch the records from the Actor run's default dataset. """ actor_call = self.apify_client.actor(actor_id).call( run_input=run_input, build=build, memory_mbytes=memory_mbytes, timeout_secs=timeout_secs, ) return ApifyDatasetLoader( dataset_id=actor_call["defaultDatasetId"], dataset_mapping_function=dataset_mapping_function, ) [docs] async def acall_actor( self, actor_id: str, run_input: Dict, dataset_mapping_function: Callable[[Dict], Document], *, build: Optional[str] = None, memory_mbytes: Optional[int] = None,
https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
a2b37c2ea00a-2
memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None, ) -> ApifyDatasetLoader: """Run an Actor on the Apify platform and wait for results to be ready. Args: actor_id (str): The ID or name of the Actor on the Apify platform. run_input (Dict): The input object of the Actor that you're trying to run. dataset_mapping_function (Callable): A function that takes a single dictionary (an Apify dataset item) and converts it to an instance of the Document class. build (str, optional): Optionally specifies the actor build to run. It can be either a build tag or build number. memory_mbytes (int, optional): Optional memory limit for the run, in megabytes. timeout_secs (int, optional): Optional timeout for the run, in seconds. Returns: ApifyDatasetLoader: A loader that will fetch the records from the Actor run's default dataset. """ actor_call = await self.apify_client_async.actor(actor_id).call( run_input=run_input, build=build, memory_mbytes=memory_mbytes, timeout_secs=timeout_secs, ) return ApifyDatasetLoader( dataset_id=actor_call["defaultDatasetId"], dataset_mapping_function=dataset_mapping_function, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
afbe5348ea6e-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: 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://python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
afbe5348ea6e-1
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 = ( self._spark.sql(f"SHOW CREATE TABLE {table}").collect()[0].createtab_stmt
https://python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
afbe5348ea6e-2
) # 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 = "" return ( f"{self._sample_rows_in_table_info} rows from {table} table:\n"
https://python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
afbe5348ea6e-3
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. 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
https://python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
afbe5348ea6e-4
""" 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}" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
e3cfe05aab50-0
Source code for langchain.utilities.graphql import json from typing import Any, Callable, Dict, Optional from pydantic import BaseModel, Extra, root_validator [docs]class GraphQLAPIWrapper(BaseModel): """Wrapper around GraphQL API. To use, you should have the ``gql`` python package installed. This wrapper will use the GraphQL API to conduct queries. """ custom_headers: Optional[Dict[str, str]] = None graphql_endpoint: str gql_client: Any #: :meta private: gql_function: Callable[[str], Any] #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in the environment.""" try: from gql import Client, gql from gql.transport.requests import RequestsHTTPTransport except ImportError as e: raise ImportError( "Could not import gql python package. " f"Try installing it with `pip install gql`. Received error: {e}" ) headers = values.get("custom_headers") transport = RequestsHTTPTransport( url=values["graphql_endpoint"], headers=headers, ) client = Client(transport=transport, fetch_schema_from_transport=True) values["gql_client"] = client values["gql_function"] = gql return values [docs] def run(self, query: str) -> str: """Run a GraphQL query and get the results.""" result = self._execute_query(query) return json.dumps(result, indent=2)
https://python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html
e3cfe05aab50-1
return json.dumps(result, indent=2) def _execute_query(self, query: str) -> Dict[str, Any]: """Execute a GraphQL query and return the results.""" document_node = self.gql_function(query) result = self.gql_client.execute(document_node) return result By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html
405d4587a104-0
Source code for langchain.utilities.metaphor_search """Util that calls Metaphor Search API. In order to set this up, follow instructions at: """ import json from typing import Dict, List import aiohttp import requests from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env 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) -> List[dict]: headers = {"X-Api-Key": self.metaphor_api_key} params = {"numResults": num_results, "query": query} response = requests.post( # type: ignore f"{METAPHOR_API_URL}/search", headers=headers, json=params, ) response.raise_for_status() search_results = response.json() print(search_results) 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) -> List[Dict]:
https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
405d4587a104-1
"""Run query through Metaphor Search and return metadata. Args: query: The query to search for. num_results: The number of results to return. Returns: A list of dictionaries with the following keys: title - The title of the url - The url author - Author of the content, if applicable. Otherwise, None. date_created - Estimated date created, in YYYY-MM-DD format. Otherwise, None. """ raw_search_results = self._metaphor_search_results( query, num_results=num_results ) return self._clean_results(raw_search_results) [docs] async def results_async(self, query: str, num_results: int) -> 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} 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( {
https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
405d4587a104-2
for result in raw_search_results: cleaned_results.append( { "title": result["title"], "url": result["url"], "author": result["author"], "date_created": result["dateCreated"], } ) return cleaned_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
0e36e0b9712b-0
Source code for langchain.utilities.wikipedia """Util that calls Wikipedia.""" import logging from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.schema import Document logger = logging.getLogger(__name__) WIKIPEDIA_MAX_QUERY_LENGTH = 300 [docs]class 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 class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environment.""" try: import 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]:
https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
0e36e0b9712b-1
summaries = [] for page_title in page_titles[: self.top_k_results]: if wiki_page := self._fetch_page(page_title): if summary := self._formatted_page_summary(page_title, wiki_page): summaries.append(summary) if not summaries: return "No good 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,
https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
0e36e0b9712b-2
except ( self.wiki_client.exceptions.PageError, self.wiki_client.exceptions.DisambiguationError, ): return None [docs] def load(self, query: str) -> List[Document]: """ Run Wikipedia search and get the article text plus the meta information. See 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 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
0e634b1fce0c-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://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
0e634b1fce0c-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://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
0e634b1fce0c-2
"snippet": result["snippet"], "title": result["name"], "link": result["url"], } metadata_results.append(metadata_result) return metadata_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
51c46d846653-0
Source code for langchain.utilities.openweathermap """Util that calls OpenWeatherMap using PyOWM.""" from typing import Any, Dict, Optional from pydantic import Extra, root_validator from langchain.tools.base import BaseModel from langchain.utils import get_from_dict_or_env [docs]class OpenWeatherMapAPIWrapper(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
https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
51c46d846653-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) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
d09db68961b4-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 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 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://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
d09db68961b4-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://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
d09db68961b4-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 "answer" in res["answer_box"].keys(): toret = res["answer_box"]["answer"] elif "answer_box" in res.keys() and "snippet" in res["answer_box"].keys(): toret = res["answer_box"]["snippet"]
https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
d09db68961b4-3
toret = res["answer_box"]["snippet"] elif ( "answer_box" in res.keys() and "snippet_highlighted_words" in res["answer_box"].keys() ): toret = res["answer_box"]["snippet_highlighted_words"][0] elif ( "sports_results" in res.keys() and "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"] else: toret = "No good search result found" return toret By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
a5497978e5fe-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 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 [docs]class BashProcess: """Executes bash commands and returns the output.""" def __init__( self, strip_newlines: bool = False, return_err_output: bool = False, persistent: bool = False, ): """Initialize with stripping newlines.""" self.strip_newlines = strip_newlines self.return_err_output = return_err_output self.prompt = "" self.process = None if persistent: self.prompt = str(uuid4()) self.process = self._initialize_persistent_process(self.prompt) @staticmethod def _initialize_persistent_process(prompt: str) -> pexpect.spawn: # Start bash in a clean environment # Doesn't work on windows pexpect = _lazy_import_pexpect() process = pexpect.spawn( "env", ["-i", "bash", "--norc", "--noprofile"], encoding="utf-8" ) # Set the custom prompt process.sendline("PS1=" + prompt)
https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html
a5497978e5fe-1
# 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 and return final output.""" 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: """Run commands and return final output.""" 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: # Remove the command from the output using a regular expression pattern = re.escape(command) + r"\s*\n" output = re.sub(pattern, "", output, count=1) return output.strip() def _run_persistent(self, command: str) -> str: """Run commands and return final output.""" pexpect = _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)
https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html
a5497978e5fe-2
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 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html
f06e69224257-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://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
f06e69224257-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://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
f06e69224257-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) -> List[Dict]: """Run query through GoogleSearch 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._google_search_results(query, num=num_results) if len(results) == 0: return [{"Result": "No good Google Search Result was found"}] 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)
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
f06e69224257-3
metadata_result["snippet"] = result["snippet"] metadata_results.append(metadata_result) return metadata_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
9431822cf745-0
Source code for langchain.utilities.twilio """Util that calls Twilio.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class TwilioAPIWrapper(BaseModel): """Sms Client using Twilio. To use, you should have the ``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://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
9431822cf745-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://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
9431822cf745-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 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
f0f4d1276b5d-0
Source code for langchain.utilities.awslambda """Util that calls Lambda.""" import json from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator [docs]class LambdaWrapper(BaseModel): """Wrapper for AWS Lambda SDK. Docs for using: 1. pip install boto3 2. Create a lambda function using the AWS Console or CLI 3. Run `aws configure` and enter your AWS credentials """ lambda_client: Any #: :meta private: function_name: Optional[str] = None awslambda_tool_name: Optional[str] = None awslambda_tool_description: Optional[str] = None 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: """Invoke Lambda function and parse result.""" 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:
https://python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html
f0f4d1276b5d-1
answer = json.loads(payload_string)["body"] except StopIteration: return "Failed to parse response from Lambda" if answer is None or answer == "": # We don't want to return the assumption alone if answer is empty return "Request failed." else: return f"Result: {answer}" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html
ea93c34850dc-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 enviroment 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://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
ea93c34850dc-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) 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", "Unkown") address = place_details.get("result", {}).get( "formatted_address", "Unknown" )
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
ea93c34850dc-2
"formatted_address", "Unknown" ) phone_number = place_details.get("result", {}).get( "formatted_phone_number", "Unknown" ) website = place_details.get("result", {}).get("website", "Unknown") formatted_details = ( f"{name}\nAddress: {address}\n" f"Phone: {phone_number}\nWebsite: {website}\n\n" ) return formatted_details except Exception as e: logging.error(f"An error occurred while formatting place details: {e}") return None By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
46a0f871d43f-0
Source code for langchain.utilities.python import sys from io import StringIO from typing import Dict, Optional from pydantic import BaseModel, Field [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] def run(self, command: str) -> str: """Run command with own globals/locals and returns anything printed.""" old_stdout = sys.stdout sys.stdout = mystdout = StringIO() try: exec(command, self.globals, self.locals) sys.stdout = old_stdout output = mystdout.getvalue() except Exception as e: sys.stdout = old_stdout output = repr(e) return output By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/python.html
c9b645d8954f-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://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
c9b645d8954f-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://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
c9b645d8954f-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://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
c9b645d8954f-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://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
c9b645d8954f-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 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
c3855981a20a-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 """ k: int = 10 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 ddg # 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 ddg results = ddg( query, region=self.region, safesearch=self.safesearch, time=self.time, max_results=self.max_results, ) if results is None or len(results) == 0:
https://python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
c3855981a20a-1
) if results is None or len(results) == 0: return ["No good DuckDuckGo Search Result was found"] snippets = [result["body"] for result in results] return snippets [docs] def run(self, query: str) -> str: snippets = self.get_snippets(query) return " ".join(snippets) [docs] def results(self, query: str, num_results: int) -> 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 ddg results = ddg( query, region=self.region, safesearch=self.safesearch, time=self.time, max_results=num_results, ) if results is None or len(results) == 0: return [{"Result": "No good DuckDuckGo Search Result was found"}] def to_metadata(result: Dict) -> Dict[str, str]: return { "snippet": result["body"], "title": result["title"], "link": result["href"], } return [to_metadata(result) for result in results] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
749e78be2c5e-0
Source code for langchain.utilities.arxiv """Util that calls Arxiv.""" import logging import os from typing import Any, Dict, List from pydantic import BaseModel, Extra, root_validator from langchain.schema import Document logger = logging.getLogger(__name__) [docs]class ArxivAPIWrapper(BaseModel): """Wrapper around ArxivAPI. To use, you should have the ``arxiv`` python package installed. https://lukasschwab.me/arxiv.py/index.html This wrapper will use the Arxiv API to conduct searches and fetch document summaries. By default, it will return the document summaries of the top-k results. It limits the Document content by doc_content_chars_max. Set doc_content_chars_max=None if you don't want to limit the content size. Parameters: top_k_results: number of the top-scored document used for the arxiv tool ARXIV_MAX_QUERY_LENGTH: the cut limit on the query used for the arxiv tool. load_max_docs: a limit to the number of loaded documents load_all_available_meta: if True: the `metadata` of the loaded Documents gets all available meta info (see https://lukasschwab.me/arxiv.py/index.html#Result), if False: the `metadata` gets only the most informative fields. """ arxiv_search: Any #: :meta private: arxiv_exceptions: Any # :meta private: top_k_results: int = 3 ARXIV_MAX_QUERY_LENGTH = 300 load_max_docs: int = 100 load_all_available_meta: bool = False doc_content_chars_max: int = 4000 class Config: """Configuration for this pydantic object."""
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
749e78be2c5e-1
class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environment.""" try: import arxiv values["arxiv_search"] = arxiv.Search values["arxiv_exceptions"] = ( arxiv.ArxivError, arxiv.UnexpectedEmptyPageError, arxiv.HTTPError, ) values["arxiv_result"] = arxiv.Result except ImportError: raise ImportError( "Could not import arxiv python package. " "Please install it with `pip install arxiv`." ) return values [docs] def run(self, query: str) -> str: """ Run Arxiv search and get the article meta information. See https://lukasschwab.me/arxiv.py/index.html#Search See https://lukasschwab.me/arxiv.py/index.html#Result It uses only the most informative fields of article meta information. """ try: results = self.arxiv_search( # type: ignore query[: self.ARXIV_MAX_QUERY_LENGTH], max_results=self.top_k_results ).results() except self.arxiv_exceptions as ex: return f"Arxiv exception: {ex}" docs = [ f"Published: {result.updated.date()}\nTitle: {result.title}\n" f"Authors: {', '.join(a.name for a in result.authors)}\n" f"Summary: {result.summary}" for result in results ] if docs:
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
749e78be2c5e-2
for result in results ] if docs: return "\n\n".join(docs)[: self.doc_content_chars_max] else: return "No good Arxiv Result was found" [docs] def load(self, query: str) -> List[Document]: """ Run Arxiv search and get the article texts plus the article meta information. See https://lukasschwab.me/arxiv.py/index.html#Search Returns: a list of documents with the document.page_content in text format """ try: import fitz except ImportError: raise ImportError( "PyMuPDF package not found, please install it with " "`pip install pymupdf`" ) try: results = self.arxiv_search( # type: ignore query[: self.ARXIV_MAX_QUERY_LENGTH], max_results=self.load_max_docs ).results() except self.arxiv_exceptions as ex: logger.debug("Error on arxiv: %s", ex) return [] docs: List[Document] = [] for result in results: try: doc_file_name: str = result.download_pdf() with fitz.open(doc_file_name) as doc_file: text: str = "".join(page.get_text() for page in doc_file) except FileNotFoundError as f_ex: logger.debug(f_ex) continue if self.load_all_available_meta: extra_metadata = { "entry_id": result.entry_id, "published_first_time": str(result.published.date()), "comment": result.comment, "journal_ref": result.journal_ref, "doi": result.doi, "primary_category": result.primary_category,
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
749e78be2c5e-3
"doi": result.doi, "primary_category": result.primary_category, "categories": result.categories, "links": [link.href for link in result.links], } else: extra_metadata = {} metadata = { "Published": str(result.updated.date()), "Title": result.title, "Authors": ", ".join(a.name for a in result.authors), "Summary": result.summary, **extra_metadata, } doc = Document( page_content=text[: self.doc_content_chars_max], metadata=metadata ) docs.append(doc) os.remove(doc_file_name) return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
16f172f85368-0
Source code for langchain.docstore.in_memory """Simple in memory docstore in the form of a dict.""" from typing import Dict, Union from langchain.docstore.base import AddableMixin, Docstore from langchain.docstore.document import Document [docs]class InMemoryDocstore(Docstore, AddableMixin): """Simple in memory docstore in the form of a dict.""" def __init__(self, _dict: Dict[str, Document]): """Initialize with dict.""" self._dict = _dict [docs] def add(self, texts: Dict[str, Document]) -> None: """Add texts to in memory dictionary.""" overlapping = set(texts).intersection(self._dict) if overlapping: raise ValueError(f"Tried to add ids that already exist: {overlapping}") self._dict = dict(self._dict, **texts) [docs] def search(self, search: str) -> Union[str, Document]: """Search via direct lookup.""" if search not in self._dict: return f"ID {search} not found." else: return self._dict[search] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html
b2bedbc91717-0
Source code for langchain.docstore.wikipedia """Wrapper around wikipedia API.""" from typing import Union from langchain.docstore.base import Docstore from langchain.docstore.document import Document [docs]class Wikipedia(Docstore): """Wrapper around wikipedia API.""" def __init__(self) -> None: """Check that wikipedia package is installed.""" try: import wikipedia # noqa: F401 except ImportError: raise ImportError( "Could not import wikipedia python package. " "Please install it with `pip install wikipedia`." ) [docs] def search(self, search: str) -> Union[str, Document]: """Try to search for wiki page. If page exists, return the page summary, and a PageWithLookups object. If page does not exist, return similar entries. """ import wikipedia try: page_content = wikipedia.page(search).content url = wikipedia.page(search).url result: Union[str, Document] = Document( page_content=page_content, metadata={"page": url} ) except wikipedia.PageError: result = f"Could not find [{search}]. Similar: {wikipedia.search(search)}" except wikipedia.DisambiguationError: result = f"Could not find [{search}]. Similar: {wikipedia.search(search)}" return result By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/docstore/wikipedia.html
2d255703a6a3-0
Source code for langchain.chains.sequential """Chain pipeline where the outputs of one step feed directly into next.""" from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain.chains.base import Chain from langchain.input import get_color_mapping [docs]class SequentialChain(Chain): """Chain where the outputs of one chain feed directly into next.""" chains: List[Chain] input_variables: List[str] output_variables: List[str] #: :meta private: return_all: bool = False class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Return expected input keys to the chain. :meta private: """ return self.input_variables @property def output_keys(self) -> List[str]: """Return output key. :meta private: """ return self.output_variables @root_validator(pre=True) def validate_chains(cls, values: Dict) -> Dict: """Validate that the correct inputs exist for all chains.""" chains = values["chains"] input_variables = values["input_variables"] memory_keys = list() if "memory" in values and values["memory"] is not None: """Validate that prompt input variables are consistent.""" memory_keys = values["memory"].memory_variables if set(input_variables).intersection(set(memory_keys)): overlapping_keys = set(input_variables) & set(memory_keys) raise ValueError(
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
2d255703a6a3-1
overlapping_keys = set(input_variables) & set(memory_keys) raise ValueError( f"The the input key(s) {''.join(overlapping_keys)} are found " f"in the Memory keys ({memory_keys}) - please use input and " f"memory keys that don't overlap." ) known_variables = set(input_variables + memory_keys) for chain in chains: missing_vars = set(chain.input_keys).difference(known_variables) if missing_vars: raise ValueError( f"Missing required input keys: {missing_vars}, " f"only had {known_variables}" ) overlapping_keys = known_variables.intersection(chain.output_keys) if overlapping_keys: raise ValueError( f"Chain returned keys that already exist: {overlapping_keys}" ) known_variables |= set(chain.output_keys) if "output_variables" not in values: if values.get("return_all", False): output_keys = known_variables.difference(input_variables) else: output_keys = chains[-1].output_keys values["output_variables"] = output_keys else: missing_vars = set(values["output_variables"]).difference(known_variables) if missing_vars: raise ValueError( f"Expected output variables that were not found: {missing_vars}." ) return values def _call( self, inputs: Dict[str, str], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: known_values = inputs.copy() _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() for i, chain in enumerate(self.chains):
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
2d255703a6a3-2
for i, chain in enumerate(self.chains): callbacks = _run_manager.get_child() outputs = chain(known_values, return_only_outputs=True, callbacks=callbacks) known_values.update(outputs) return {k: known_values[k] for k in self.output_variables} async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, Any]: known_values = inputs.copy() _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager() callbacks = _run_manager.get_child() for i, chain in enumerate(self.chains): outputs = await chain.acall( known_values, return_only_outputs=True, callbacks=callbacks ) known_values.update(outputs) return {k: known_values[k] for k in self.output_variables} [docs]class SimpleSequentialChain(Chain): """Simple chain where the outputs of one step feed directly into next.""" chains: List[Chain] strip_outputs: bool = False input_key: str = "input" #: :meta private: output_key: str = "output" #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Expect input key. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Return output key. :meta private: """ return [self.output_key] @root_validator()
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
2d255703a6a3-3
""" return [self.output_key] @root_validator() def validate_chains(cls, values: Dict) -> Dict: """Validate that chains are all single input/output.""" for chain in values["chains"]: if len(chain.input_keys) != 1: raise ValueError( "Chains used in SimplePipeline should all have one input, got " f"{chain} with {len(chain.input_keys)} inputs." ) if len(chain.output_keys) != 1: raise ValueError( "Chains used in SimplePipeline should all have one output, got " f"{chain} with {len(chain.output_keys)} outputs." ) return values def _call( self, inputs: Dict[str, str], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() _input = inputs[self.input_key] color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))]) for i, chain in enumerate(self.chains): _input = chain.run(_input, callbacks=_run_manager.get_child()) if self.strip_outputs: _input = _input.strip() _run_manager.on_text( _input, color=color_mapping[str(i)], end="\n", verbose=self.verbose ) return {self.output_key: _input} async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, Any]:
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
2d255703a6a3-4
) -> Dict[str, Any]: _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager() callbacks = _run_manager.get_child() _input = inputs[self.input_key] color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))]) for i, chain in enumerate(self.chains): _input = await chain.arun(_input, callbacks=callbacks) if self.strip_outputs: _input = _input.strip() await _run_manager.on_text( _input, color=color_mapping[str(i)], end="\n", verbose=self.verbose ) return {self.output_key: _input} By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
d5ea25e4cbd7-0
Source code for langchain.chains.mapreduce """Map-reduce chain. Splits up a document, sends the smaller parts to the LLM with one prompt, then combines the results with another one. """ from __future__ import annotations from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import CallbackManagerForChainRun, Callbacks from langchain.chains.base import Chain from langchain.chains.combine_documents.base import BaseCombineDocumentsChain from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain from langchain.chains.combine_documents.stuff import StuffDocumentsChain from langchain.chains.llm import LLMChain from langchain.docstore.document import Document from langchain.prompts.base import BasePromptTemplate from langchain.text_splitter import TextSplitter [docs]class MapReduceChain(Chain): """Map-reduce chain.""" combine_documents_chain: BaseCombineDocumentsChain """Chain to use to combine documents.""" text_splitter: TextSplitter """Text splitter to use.""" input_key: str = "input_text" #: :meta private: output_key: str = "output_text" #: :meta private: [docs] @classmethod def from_params( cls, llm: BaseLanguageModel, prompt: BasePromptTemplate, text_splitter: TextSplitter, callbacks: Callbacks = None, combine_chain_kwargs: Optional[Mapping[str, Any]] = None, reduce_chain_kwargs: Optional[Mapping[str, Any]] = None, **kwargs: Any, ) -> MapReduceChain:
https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
d5ea25e4cbd7-1
**kwargs: Any, ) -> MapReduceChain: """Construct a map-reduce chain that uses the chain for map and reduce.""" llm_chain = LLMChain(llm=llm, prompt=prompt, callbacks=callbacks) reduce_chain = StuffDocumentsChain( llm_chain=llm_chain, callbacks=callbacks, **(reduce_chain_kwargs if reduce_chain_kwargs else {}), ) combine_documents_chain = MapReduceDocumentsChain( llm_chain=llm_chain, combine_document_chain=reduce_chain, callbacks=callbacks, **(combine_chain_kwargs if combine_chain_kwargs else {}), ) return cls( combine_documents_chain=combine_documents_chain, text_splitter=text_splitter, callbacks=callbacks, **kwargs, ) class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Expect input key. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Return output key. :meta private: """ return [self.output_key] def _call( self, inputs: Dict[str, str], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() # Split the larger text into smaller chunks. doc_text = inputs.pop(self.input_key) texts = self.text_splitter.split_text(doc_text)
https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
d5ea25e4cbd7-2
texts = self.text_splitter.split_text(doc_text) docs = [Document(page_content=text) for text in texts] _inputs: Dict[str, Any] = { **inputs, self.combine_documents_chain.input_key: docs, } outputs = self.combine_documents_chain.run( _inputs, callbacks=_run_manager.get_child() ) return {self.output_key: outputs} By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
95f7f77482b1-0
Source code for langchain.chains.moderation """Pass input through a moderation endpoint.""" from typing import Any, Dict, List, Optional from pydantic import root_validator from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.utils import get_from_dict_or_env [docs]class OpenAIModerationChain(Chain): """Pass input through a moderation endpoint. To use, you should have the ``openai`` python package installed, and the environment variable ``OPENAI_API_KEY`` set with your API key. Any parameters that are valid to be passed to the openai.create call can be passed in, even if not explicitly saved on this class. Example: .. code-block:: python from langchain.chains import OpenAIModerationChain moderation = OpenAIModerationChain() """ client: Any #: :meta private: model_name: Optional[str] = None """Moderation model name to use.""" error: bool = False """Whether or not to error if bad content was found.""" input_key: str = "input" #: :meta private: output_key: str = "output" #: :meta private: openai_api_key: Optional[str] = None openai_organization: Optional[str] = None @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" openai_api_key = get_from_dict_or_env( values, "openai_api_key", "OPENAI_API_KEY" ) openai_organization = get_from_dict_or_env( values, "openai_organization",
https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html
95f7f77482b1-1
values, "openai_organization", "OPENAI_ORGANIZATION", default="", ) try: import openai openai.api_key = openai_api_key if openai_organization: openai.organization = openai_organization values["client"] = openai.Moderation except ImportError: raise ImportError( "Could not import openai python package. " "Please install it with `pip install openai`." ) return values @property def input_keys(self) -> List[str]: """Expect input key. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Return output key. :meta private: """ return [self.output_key] def _moderate(self, text: str, results: dict) -> str: if results["flagged"]: error_str = "Text was found that violates OpenAI's content policy." if self.error: raise ValueError(error_str) else: return error_str return text def _call( self, inputs: Dict[str, str], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: text = inputs[self.input_key] results = self.client.create(text) output = self._moderate(text, results["results"][0]) return {self.output_key: output} By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html
aa9e9e684820-0
Source code for langchain.chains.llm_requests """Chain that hits a URL and then uses an LLM to parse results.""" from __future__ import annotations from typing import Any, Dict, List, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains import LLMChain from langchain.chains.base import Chain from langchain.requests import TextRequestsWrapper DEFAULT_HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" # noqa: E501 } [docs]class LLMRequestsChain(Chain): """Chain that hits a URL and then uses an LLM to parse results.""" llm_chain: LLMChain requests_wrapper: TextRequestsWrapper = Field( default_factory=TextRequestsWrapper, exclude=True ) text_length: int = 8000 requests_key: str = "requests_result" #: :meta private: input_key: str = "url" #: :meta private: output_key: str = "output" #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Will be whatever keys the prompt expects. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Will always return text key. :meta private: """ return [self.output_key]
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html
aa9e9e684820-1
:meta private: """ return [self.output_key] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" try: from bs4 import BeautifulSoup # noqa: F401 except ImportError: raise ValueError( "Could not import bs4 python package. " "Please install it with `pip install bs4`." ) return values def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: from bs4 import BeautifulSoup _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() # Other keys are assumed to be needed for LLM prediction other_keys = {k: v for k, v in inputs.items() if k != self.input_key} url = inputs[self.input_key] res = self.requests_wrapper.get(url) # extract the text from the html soup = BeautifulSoup(res, "html.parser") other_keys[self.requests_key] = soup.get_text()[: self.text_length] result = self.llm_chain.predict( callbacks=_run_manager.get_child(), **other_keys ) return {self.output_key: result} @property def _chain_type(self) -> str: return "llm_requests_chain" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html
a2edca350549-0
Source code for langchain.chains.loading """Functionality for loading chains.""" import json from pathlib import Path from typing import Any, Union import yaml from langchain.chains.api.base import APIChain from langchain.chains.base import Chain from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain from langchain.chains.combine_documents.map_rerank import MapRerankDocumentsChain from langchain.chains.combine_documents.refine import RefineDocumentsChain from langchain.chains.combine_documents.stuff import StuffDocumentsChain from langchain.chains.hyde.base import HypotheticalDocumentEmbedder from langchain.chains.llm import LLMChain from langchain.chains.llm_bash.base import LLMBashChain from langchain.chains.llm_checker.base import LLMCheckerChain from langchain.chains.llm_math.base import LLMMathChain from langchain.chains.llm_requests import LLMRequestsChain from langchain.chains.pal.base import PALChain from langchain.chains.qa_with_sources.base import QAWithSourcesChain from langchain.chains.qa_with_sources.vector_db import VectorDBQAWithSourcesChain from langchain.chains.retrieval_qa.base import RetrievalQA, VectorDBQA from langchain.chains.sql_database.base import SQLDatabaseChain from langchain.llms.loading import load_llm, load_llm_from_config from langchain.prompts.loading import load_prompt, load_prompt_from_config from langchain.utilities.loading import try_load_from_hub URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/chains/" def _load_llm_chain(config: dict, **kwargs: Any) -> LLMChain: """Load LLM chain from config dict.""" if "llm" in config:
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-1
if "llm" in config: llm_config = config.pop("llm") llm = load_llm_from_config(llm_config) elif "llm_path" in config: llm = load_llm(config.pop("llm_path")) else: raise ValueError("One of `llm` or `llm_path` must be present.") if "prompt" in config: prompt_config = config.pop("prompt") prompt = load_prompt_from_config(prompt_config) elif "prompt_path" in config: prompt = load_prompt(config.pop("prompt_path")) else: raise ValueError("One of `prompt` or `prompt_path` must be present.") return LLMChain(llm=llm, prompt=prompt, **config) def _load_hyde_chain(config: dict, **kwargs: Any) -> HypotheticalDocumentEmbedder: """Load hypothetical document embedder chain from config dict.""" if "llm_chain" in config: llm_chain_config = config.pop("llm_chain") llm_chain = load_chain_from_config(llm_chain_config) elif "llm_chain_path" in config: llm_chain = load_chain(config.pop("llm_chain_path")) else: raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.") if "embeddings" in kwargs: embeddings = kwargs.pop("embeddings") else: raise ValueError("`embeddings` must be present.") return HypotheticalDocumentEmbedder( llm_chain=llm_chain, base_embeddings=embeddings, **config )
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-2
) def _load_stuff_documents_chain(config: dict, **kwargs: Any) -> StuffDocumentsChain: if "llm_chain" in config: llm_chain_config = config.pop("llm_chain") llm_chain = load_chain_from_config(llm_chain_config) elif "llm_chain_path" in config: llm_chain = load_chain(config.pop("llm_chain_path")) else: raise ValueError("One of `llm_chain` or `llm_chain_config` must be present.") if not isinstance(llm_chain, LLMChain): raise ValueError(f"Expected LLMChain, got {llm_chain}") if "document_prompt" in config: prompt_config = config.pop("document_prompt") document_prompt = load_prompt_from_config(prompt_config) elif "document_prompt_path" in config: document_prompt = load_prompt(config.pop("document_prompt_path")) else: raise ValueError( "One of `document_prompt` or `document_prompt_path` must be present." ) return StuffDocumentsChain( llm_chain=llm_chain, document_prompt=document_prompt, **config ) def _load_map_reduce_documents_chain( config: dict, **kwargs: Any ) -> MapReduceDocumentsChain: if "llm_chain" in config: llm_chain_config = config.pop("llm_chain") llm_chain = load_chain_from_config(llm_chain_config) elif "llm_chain_path" in config: llm_chain = load_chain(config.pop("llm_chain_path")) else: raise ValueError("One of `llm_chain` or `llm_chain_config` must be present.") if not isinstance(llm_chain, LLMChain):
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-3
if not isinstance(llm_chain, LLMChain): raise ValueError(f"Expected LLMChain, got {llm_chain}") if "combine_document_chain" in config: combine_document_chain_config = config.pop("combine_document_chain") combine_document_chain = load_chain_from_config(combine_document_chain_config) elif "combine_document_chain_path" in config: combine_document_chain = load_chain(config.pop("combine_document_chain_path")) else: raise ValueError( "One of `combine_document_chain` or " "`combine_document_chain_path` must be present." ) if "collapse_document_chain" in config: collapse_document_chain_config = config.pop("collapse_document_chain") if collapse_document_chain_config is None: collapse_document_chain = None else: collapse_document_chain = load_chain_from_config( collapse_document_chain_config ) elif "collapse_document_chain_path" in config: collapse_document_chain = load_chain(config.pop("collapse_document_chain_path")) return MapReduceDocumentsChain( llm_chain=llm_chain, combine_document_chain=combine_document_chain, collapse_document_chain=collapse_document_chain, **config, ) def _load_llm_bash_chain(config: dict, **kwargs: Any) -> LLMBashChain: llm_chain = None if "llm_chain" in config: llm_chain_config = config.pop("llm_chain") llm_chain = load_chain_from_config(llm_chain_config) elif "llm_chain_path" in config: llm_chain = load_chain(config.pop("llm_chain_path")) # llm attribute is deprecated in favor of llm_chain, here to support old configs
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-4
# llm attribute is deprecated in favor of llm_chain, here to support old configs elif "llm" in config: llm_config = config.pop("llm") llm = load_llm_from_config(llm_config) # llm_path attribute is deprecated in favor of llm_chain_path, # its to support old configs elif "llm_path" in config: llm = load_llm(config.pop("llm_path")) else: raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.") if "prompt" in config: prompt_config = config.pop("prompt") prompt = load_prompt_from_config(prompt_config) elif "prompt_path" in config: prompt = load_prompt(config.pop("prompt_path")) if llm_chain: return LLMBashChain(llm_chain=llm_chain, prompt=prompt, **config) else: return LLMBashChain(llm=llm, prompt=prompt, **config) def _load_llm_checker_chain(config: dict, **kwargs: Any) -> LLMCheckerChain: if "llm" in config: llm_config = config.pop("llm") llm = load_llm_from_config(llm_config) elif "llm_path" in config: llm = load_llm(config.pop("llm_path")) else: raise ValueError("One of `llm` or `llm_path` must be present.") if "create_draft_answer_prompt" in config: create_draft_answer_prompt_config = config.pop("create_draft_answer_prompt") create_draft_answer_prompt = load_prompt_from_config( create_draft_answer_prompt_config )
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-5
create_draft_answer_prompt_config ) elif "create_draft_answer_prompt_path" in config: create_draft_answer_prompt = load_prompt( config.pop("create_draft_answer_prompt_path") ) if "list_assertions_prompt" in config: list_assertions_prompt_config = config.pop("list_assertions_prompt") list_assertions_prompt = load_prompt_from_config(list_assertions_prompt_config) elif "list_assertions_prompt_path" in config: list_assertions_prompt = load_prompt(config.pop("list_assertions_prompt_path")) if "check_assertions_prompt" in config: check_assertions_prompt_config = config.pop("check_assertions_prompt") check_assertions_prompt = load_prompt_from_config( check_assertions_prompt_config ) elif "check_assertions_prompt_path" in config: check_assertions_prompt = load_prompt( config.pop("check_assertions_prompt_path") ) if "revised_answer_prompt" in config: revised_answer_prompt_config = config.pop("revised_answer_prompt") revised_answer_prompt = load_prompt_from_config(revised_answer_prompt_config) elif "revised_answer_prompt_path" in config: revised_answer_prompt = load_prompt(config.pop("revised_answer_prompt_path")) return LLMCheckerChain( llm=llm, create_draft_answer_prompt=create_draft_answer_prompt, list_assertions_prompt=list_assertions_prompt, check_assertions_prompt=check_assertions_prompt, revised_answer_prompt=revised_answer_prompt, **config, ) def _load_llm_math_chain(config: dict, **kwargs: Any) -> LLMMathChain: llm_chain = None if "llm_chain" in config:
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-6
llm_chain = None if "llm_chain" in config: llm_chain_config = config.pop("llm_chain") llm_chain = load_chain_from_config(llm_chain_config) elif "llm_chain_path" in config: llm_chain = load_chain(config.pop("llm_chain_path")) # llm attribute is deprecated in favor of llm_chain, here to support old configs elif "llm" in config: llm_config = config.pop("llm") llm = load_llm_from_config(llm_config) # llm_path attribute is deprecated in favor of llm_chain_path, # its to support old configs elif "llm_path" in config: llm = load_llm(config.pop("llm_path")) else: raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.") if "prompt" in config: prompt_config = config.pop("prompt") prompt = load_prompt_from_config(prompt_config) elif "prompt_path" in config: prompt = load_prompt(config.pop("prompt_path")) if llm_chain: return LLMMathChain(llm_chain=llm_chain, prompt=prompt, **config) else: return LLMMathChain(llm=llm, prompt=prompt, **config) def _load_map_rerank_documents_chain( config: dict, **kwargs: Any ) -> MapRerankDocumentsChain: if "llm_chain" in config: llm_chain_config = config.pop("llm_chain") llm_chain = load_chain_from_config(llm_chain_config) elif "llm_chain_path" in config:
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-7
elif "llm_chain_path" in config: llm_chain = load_chain(config.pop("llm_chain_path")) else: raise ValueError("One of `llm_chain` or `llm_chain_config` must be present.") return MapRerankDocumentsChain(llm_chain=llm_chain, **config) def _load_pal_chain(config: dict, **kwargs: Any) -> PALChain: llm_chain = None if "llm_chain" in config: llm_chain_config = config.pop("llm_chain") llm_chain = load_chain_from_config(llm_chain_config) elif "llm_chain_path" in config: llm_chain = load_chain(config.pop("llm_chain_path")) # llm attribute is deprecated in favor of llm_chain, here to support old configs elif "llm" in config: llm_config = config.pop("llm") llm = load_llm_from_config(llm_config) # llm_path attribute is deprecated in favor of llm_chain_path, # its to support old configs elif "llm_path" in config: llm = load_llm(config.pop("llm_path")) else: raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.") if "prompt" in config: prompt_config = config.pop("prompt") prompt = load_prompt_from_config(prompt_config) elif "prompt_path" in config: prompt = load_prompt(config.pop("prompt_path")) else: raise ValueError("One of `prompt` or `prompt_path` must be present.") if llm_chain:
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-8
if llm_chain: return PALChain(llm_chain=llm_chain, prompt=prompt, **config) else: return PALChain(llm=llm, prompt=prompt, **config) def _load_refine_documents_chain(config: dict, **kwargs: Any) -> RefineDocumentsChain: if "initial_llm_chain" in config: initial_llm_chain_config = config.pop("initial_llm_chain") initial_llm_chain = load_chain_from_config(initial_llm_chain_config) elif "initial_llm_chain_path" in config: initial_llm_chain = load_chain(config.pop("initial_llm_chain_path")) else: raise ValueError( "One of `initial_llm_chain` or `initial_llm_chain_config` must be present." ) if "refine_llm_chain" in config: refine_llm_chain_config = config.pop("refine_llm_chain") refine_llm_chain = load_chain_from_config(refine_llm_chain_config) elif "refine_llm_chain_path" in config: refine_llm_chain = load_chain(config.pop("refine_llm_chain_path")) else: raise ValueError( "One of `refine_llm_chain` or `refine_llm_chain_config` must be present." ) if "document_prompt" in config: prompt_config = config.pop("document_prompt") document_prompt = load_prompt_from_config(prompt_config) elif "document_prompt_path" in config: document_prompt = load_prompt(config.pop("document_prompt_path")) return RefineDocumentsChain( initial_llm_chain=initial_llm_chain, refine_llm_chain=refine_llm_chain, document_prompt=document_prompt,
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-9
refine_llm_chain=refine_llm_chain, document_prompt=document_prompt, **config, ) def _load_qa_with_sources_chain(config: dict, **kwargs: Any) -> QAWithSourcesChain: if "combine_documents_chain" in config: combine_documents_chain_config = config.pop("combine_documents_chain") combine_documents_chain = load_chain_from_config(combine_documents_chain_config) elif "combine_documents_chain_path" in config: combine_documents_chain = load_chain(config.pop("combine_documents_chain_path")) else: raise ValueError( "One of `combine_documents_chain` or " "`combine_documents_chain_path` must be present." ) return QAWithSourcesChain(combine_documents_chain=combine_documents_chain, **config) def _load_sql_database_chain(config: dict, **kwargs: Any) -> SQLDatabaseChain: if "database" in kwargs: database = kwargs.pop("database") else: raise ValueError("`database` must be present.") if "llm" in config: llm_config = config.pop("llm") llm = load_llm_from_config(llm_config) elif "llm_path" in config: llm = load_llm(config.pop("llm_path")) else: raise ValueError("One of `llm` or `llm_path` must be present.") if "prompt" in config: prompt_config = config.pop("prompt") prompt = load_prompt_from_config(prompt_config) else: prompt = None return SQLDatabaseChain.from_llm(llm, database, prompt=prompt, **config) def _load_vector_db_qa_with_sources_chain( config: dict, **kwargs: Any
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-10
config: dict, **kwargs: Any ) -> VectorDBQAWithSourcesChain: if "vectorstore" in kwargs: vectorstore = kwargs.pop("vectorstore") else: raise ValueError("`vectorstore` must be present.") if "combine_documents_chain" in config: combine_documents_chain_config = config.pop("combine_documents_chain") combine_documents_chain = load_chain_from_config(combine_documents_chain_config) elif "combine_documents_chain_path" in config: combine_documents_chain = load_chain(config.pop("combine_documents_chain_path")) else: raise ValueError( "One of `combine_documents_chain` or " "`combine_documents_chain_path` must be present." ) return VectorDBQAWithSourcesChain( combine_documents_chain=combine_documents_chain, vectorstore=vectorstore, **config, ) def _load_retrieval_qa(config: dict, **kwargs: Any) -> RetrievalQA: if "retriever" in kwargs: retriever = kwargs.pop("retriever") else: raise ValueError("`retriever` must be present.") if "combine_documents_chain" in config: combine_documents_chain_config = config.pop("combine_documents_chain") combine_documents_chain = load_chain_from_config(combine_documents_chain_config) elif "combine_documents_chain_path" in config: combine_documents_chain = load_chain(config.pop("combine_documents_chain_path")) else: raise ValueError( "One of `combine_documents_chain` or " "`combine_documents_chain_path` must be present." ) return RetrievalQA( combine_documents_chain=combine_documents_chain, retriever=retriever, **config, )
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-11
retriever=retriever, **config, ) def _load_vector_db_qa(config: dict, **kwargs: Any) -> VectorDBQA: if "vectorstore" in kwargs: vectorstore = kwargs.pop("vectorstore") else: raise ValueError("`vectorstore` must be present.") if "combine_documents_chain" in config: combine_documents_chain_config = config.pop("combine_documents_chain") combine_documents_chain = load_chain_from_config(combine_documents_chain_config) elif "combine_documents_chain_path" in config: combine_documents_chain = load_chain(config.pop("combine_documents_chain_path")) else: raise ValueError( "One of `combine_documents_chain` or " "`combine_documents_chain_path` must be present." ) return VectorDBQA( combine_documents_chain=combine_documents_chain, vectorstore=vectorstore, **config, ) def _load_api_chain(config: dict, **kwargs: Any) -> APIChain: if "api_request_chain" in config: api_request_chain_config = config.pop("api_request_chain") api_request_chain = load_chain_from_config(api_request_chain_config) elif "api_request_chain_path" in config: api_request_chain = load_chain(config.pop("api_request_chain_path")) else: raise ValueError( "One of `api_request_chain` or `api_request_chain_path` must be present." ) if "api_answer_chain" in config: api_answer_chain_config = config.pop("api_answer_chain") api_answer_chain = load_chain_from_config(api_answer_chain_config) elif "api_answer_chain_path" in config:
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-12
elif "api_answer_chain_path" in config: api_answer_chain = load_chain(config.pop("api_answer_chain_path")) else: raise ValueError( "One of `api_answer_chain` or `api_answer_chain_path` must be present." ) if "requests_wrapper" in kwargs: requests_wrapper = kwargs.pop("requests_wrapper") else: raise ValueError("`requests_wrapper` must be present.") return APIChain( api_request_chain=api_request_chain, api_answer_chain=api_answer_chain, requests_wrapper=requests_wrapper, **config, ) def _load_llm_requests_chain(config: dict, **kwargs: Any) -> LLMRequestsChain: if "llm_chain" in config: llm_chain_config = config.pop("llm_chain") llm_chain = load_chain_from_config(llm_chain_config) elif "llm_chain_path" in config: llm_chain = load_chain(config.pop("llm_chain_path")) else: raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.") if "requests_wrapper" in kwargs: requests_wrapper = kwargs.pop("requests_wrapper") return LLMRequestsChain( llm_chain=llm_chain, requests_wrapper=requests_wrapper, **config ) else: return LLMRequestsChain(llm_chain=llm_chain, **config) type_to_loader_dict = { "api_chain": _load_api_chain, "hyde_chain": _load_hyde_chain, "llm_chain": _load_llm_chain, "llm_bash_chain": _load_llm_bash_chain,
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-13
"llm_bash_chain": _load_llm_bash_chain, "llm_checker_chain": _load_llm_checker_chain, "llm_math_chain": _load_llm_math_chain, "llm_requests_chain": _load_llm_requests_chain, "pal_chain": _load_pal_chain, "qa_with_sources_chain": _load_qa_with_sources_chain, "stuff_documents_chain": _load_stuff_documents_chain, "map_reduce_documents_chain": _load_map_reduce_documents_chain, "map_rerank_documents_chain": _load_map_rerank_documents_chain, "refine_documents_chain": _load_refine_documents_chain, "sql_database_chain": _load_sql_database_chain, "vector_db_qa_with_sources_chain": _load_vector_db_qa_with_sources_chain, "vector_db_qa": _load_vector_db_qa, "retrieval_qa": _load_retrieval_qa, } def load_chain_from_config(config: dict, **kwargs: Any) -> Chain: """Load chain from Config Dict.""" if "_type" not in config: raise ValueError("Must specify a chain Type in config") config_type = config.pop("_type") if config_type not in type_to_loader_dict: raise ValueError(f"Loading {config_type} chain not supported") chain_loader = type_to_loader_dict[config_type] return chain_loader(config, **kwargs) [docs]def load_chain(path: Union[str, Path], **kwargs: Any) -> Chain: """Unified method for loading a chain from LangChainHub or local fs.""" if hub_result := try_load_from_hub( path, _load_chain_from_file, "chains", {"json", "yaml"}, **kwargs
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
a2edca350549-14
): return hub_result else: return _load_chain_from_file(path, **kwargs) def _load_chain_from_file(file: Union[str, Path], **kwargs: Any) -> Chain: """Load chain from file.""" # Convert file to Path object. if isinstance(file, str): file_path = Path(file) else: file_path = file # Load from either json or yaml. if file_path.suffix == ".json": with open(file_path) as f: config = json.load(f) elif file_path.suffix == ".yaml": with open(file_path, "r") as f: config = yaml.safe_load(f) else: raise ValueError("File type must be json or yaml") # Override default 'verbose' and 'memory' for the chain if "verbose" in kwargs: config["verbose"] = kwargs.pop("verbose") if "memory" in kwargs: config["memory"] = kwargs.pop("memory") # Load the chain from the config now. return load_chain_from_config(config, **kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
48dd8cb3e272-0
Source code for langchain.chains.transform """Chain that runs an arbitrary python function.""" from typing import Callable, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain [docs]class TransformChain(Chain): """Chain transform chain output. Example: .. code-block:: python from langchain import TransformChain transform_chain = TransformChain(input_variables=["text"], output_variables["entities"], transform=func()) """ input_variables: List[str] output_variables: List[str] transform: Callable[[Dict[str, str]], Dict[str, str]] @property def input_keys(self) -> List[str]: """Expect input keys. :meta private: """ return self.input_variables @property def output_keys(self) -> List[str]: """Return output keys. :meta private: """ return self.output_variables def _call( self, inputs: Dict[str, str], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: return self.transform(inputs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/transform.html
db1056e59def-0
Source code for langchain.chains.llm """Chain that just formats a prompt and calls an LLM.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Sequence, Tuple, Union from pydantic import Extra from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManager, AsyncCallbackManagerForChainRun, CallbackManager, CallbackManagerForChainRun, Callbacks, ) from langchain.chains.base import Chain from langchain.input import get_colored_text from langchain.prompts.base import BasePromptTemplate from langchain.prompts.prompt import PromptTemplate from langchain.schema import LLMResult, PromptValue [docs]class LLMChain(Chain): """Chain to run queries against LLMs. Example: .. code-block:: python from langchain import LLMChain, OpenAI, PromptTemplate prompt_template = "Tell me a {adjective} joke" prompt = PromptTemplate( input_variables=["adjective"], template=prompt_template ) llm = LLMChain(llm=OpenAI(), prompt=prompt) """ prompt: BasePromptTemplate """Prompt object to use.""" llm: BaseLanguageModel output_key: str = "text" #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Will be whatever keys the prompt expects. :meta private: """ return self.prompt.input_variables @property def output_keys(self) -> List[str]: """Will always return text key.
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
db1056e59def-1
def output_keys(self) -> List[str]: """Will always return text key. :meta private: """ return [self.output_key] def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: response = self.generate([inputs], run_manager=run_manager) return self.create_outputs(response)[0] [docs] def generate( self, input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> LLMResult: """Generate LLM result from inputs.""" prompts, stop = self.prep_prompts(input_list, run_manager=run_manager) return self.llm.generate_prompt( prompts, stop, callbacks=run_manager.get_child() if run_manager else None ) [docs] async def agenerate( self, input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> LLMResult: """Generate LLM result from inputs.""" prompts, stop = await self.aprep_prompts(input_list, run_manager=run_manager) return await self.llm.agenerate_prompt( prompts, stop, callbacks=run_manager.get_child() if run_manager else None ) [docs] def prep_prompts( self, input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Tuple[List[PromptValue], Optional[List[str]]]: """Prepare prompts from inputs.""" stop = None
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html