id
stringlengths
14
16
text
stringlengths
44
2.73k
source
stringlengths
49
114
59c1f05558a3-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) -> str: """Use aiohttp to run query through SerpAPI and parse result.""" 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:
https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
59c1f05558a3-2
else: async with self.aiosession.get(url, params=params) as response: res = await response.json() return self._process_response(res) [docs] def run(self, query: str) -> 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] 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"] elif ( "answer_box" in res.keys() and "snippet_highlighted_words" in res["answer_box"].keys() ): toret = res["answer_box"]["snippet_highlighted_words"][0]
https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
59c1f05558a3-3
): 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 ( "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"] else: toret = "No good search result found" return toret By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
99cbc9b7a787-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
99cbc9b7a787-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 Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
51f7c28eeaed-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
51f7c28eeaed-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
51f7c28eeaed-2
from googleapiclient.discovery import build 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"]
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
51f7c28eeaed-3
if "snippet" in result: metadata_result["snippet"] = result["snippet"] metadata_results.append(metadata_result) return metadata_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
476d98ad312b-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" ) 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
https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
476d98ad312b-1
temperature = w.temperature("celsius") rain = w.rain 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 Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
3166e1c08acf-0
Source code for langchain.utilities.bash """Wrapper around subprocess to run commands.""" import subprocess from typing import List, Union [docs]class BashProcess: """Executes bash commands and returns the output.""" def __init__(self, strip_newlines: bool = False, return_err_output: bool = False): """Initialize with stripping newlines.""" self.strip_newlines = strip_newlines self.return_err_output = return_err_output [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) try: output = subprocess.run( commands, 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 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html
e7b8f54630a4-0
Source code for langchain.utilities.arxiv """Util that calls Arxiv.""" from typing import Any, Dict from pydantic import BaseModel, Extra, root_validator [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 of an input search. """ arxiv_client: Any #: :meta private: arxiv_exceptions: Any # :meta private: top_k_results: int = 3 ARXIV_MAX_QUERY_LENGTH = 300 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, ) except ImportError: raise ValueError( "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 document meta information. See https://lukasschwab.me/arxiv.py/index.html#Search
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
e7b8f54630a4-1
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 document meta information. """ try: 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 self.arxiv_search( # type: ignore query[: self.ARXIV_MAX_QUERY_LENGTH], max_results=self.top_k_results ).results() ] return "\n\n".join(docs) if docs else "No good Arxiv Result was found" except self.arxiv_exceptions as ex: return f"Arxiv exception: {ex}" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
b8e80ea7ad51-0
Source code for langchain.utilities.wikipedia """Util that calls Wikipedia.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator 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 of an input search. """ wiki_client: Any #: :meta private: top_k_results: int = 3 lang: str = "en" 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 ValueError( "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.""" search_results = self.wiki_client.search(query[:WIKIPEDIA_MAX_QUERY_LENGTH]) summaries = [] len_search_results = len(search_results) if len_search_results == 0: return "No good Wikipedia Search Result was found" for i in range(min(self.top_k_results, len_search_results)): summary = self.fetch_formatted_page_summary(search_results[i]) if summary is not None:
https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
b8e80ea7ad51-1
summary = self.fetch_formatted_page_summary(search_results[i]) if summary is not None: summaries.append(summary) return "\n\n".join(summaries) [docs] def fetch_formatted_page_summary(self, page: str) -> Optional[str]: try: wiki_page = self.wiki_client.page(title=page, auto_suggest=False) return f"Page: {page}\nSummary: {wiki_page.summary}" except ( self.wiki_client.exceptions.PageError, self.wiki_client.exceptions.DisambiguationError, ): return None By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
90fbe6992c42-0
Source code for langchain.utilities.powerbi """Wrapper around a Power BI endpoint.""" from __future__ import annotations 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 from requests.exceptions import Timeout from langchain.tools.powerbi.prompt import BAD_REQUEST_RESPONSE, UNAUTHORIZED_RESPONSE _LOGGER = logging.getLogger(__name__) if TYPE_CHECKING: from azure.core.exceptions import ClientAuthenticationError from azure.identity import ChainedTokenCredential from azure.identity._internal import InteractiveCredential BASE_URL = os.getenv("POWERBI_BASE_URL", "https://api.powerbi.com/v1.0/myorg/datasets/") [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[Union[ChainedTokenCredential, InteractiveCredential]] = None token: Optional[str] = None impersonated_user_name: Optional[str] = None sample_rows_in_table_info: int = Field(default=1, gt=0, le=10) aiosession: Optional[aiohttp.ClientSession] = None schemas: Dict[str, str] = Field(default_factory=dict, init=False) class Config: """Configuration for this pydantic object."""
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
90fbe6992c42-1
class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True @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}/{self.group_id}/datasets/{self.dataset_id}/executeQueries" # noqa: E501 # pylint: disable=C0301 return f"{BASE_URL}/{self.dataset_id}/executeQueries" # noqa: E501 # pylint: disable=C0301 @property def headers(self) -> Dict[str, str]: """Get the token.""" token = None if self.token: token = self.token if self.credential: try: token = self.credential.get_token( "https://analysis.windows.net/powerbi/api/.default" ).token except Exception as exc: # pylint: disable=broad-exception-caught raise ClientAuthenticationError( "Could not get a token from the supplied credentials." ) from exc if not token: raise ClientAuthenticationError("No credential or token supplied.") return { "Content-Type": "application/json", "Authorization": "Bearer " + token, } [docs] def get_table_names(self) -> Iterable[str]: """Get names of tables available.""" return self.table_names
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
90fbe6992c42-2
"""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 ) -> List[str]: """Get the tables names that need to be queried.""" if table_names is not None: if ( isinstance(table_names, list) and len(table_names) > 0 and table_names[0] != "" ): return table_names if isinstance(table_names, str) and table_names != "": return [table_names] return self.table_names def _get_tables_todo(self, tables_todo: List[str]) -> List[str]: for table in tables_todo: if table in self.schemas: tables_todo.remove(table) return tables_todo 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:
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
90fbe6992c42-3
) -> str: """Get information about specified tables.""" tables_requested = self._get_tables_to_query(table_names) tables_todo = self._get_tables_todo(tables_requested) for table in tables_todo: try: result = self.run( f"EVALUATE TOPN({self.sample_rows_in_table_info}, {table})" ) except Timeout: _LOGGER.warning("Timeout while getting table info for %s", table) continue except Exception as exc: # pylint: disable=broad-exception-caught if "bad request" in str(exc).lower(): return BAD_REQUEST_RESPONSE if "unauthorized" in str(exc).lower(): return UNAUTHORIZED_RESPONSE return str(exc) self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"]) 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) tables_todo = self._get_tables_todo(tables_requested) for table in tables_todo: try: result = await self.arun( f"EVALUATE TOPN({self.sample_rows_in_table_info}, {table})" ) except ServerTimeoutError: _LOGGER.warning("Timeout while getting table info for %s", table) continue except Exception as exc: # pylint: disable=broad-exception-caught if "bad request" in str(exc).lower(): return BAD_REQUEST_RESPONSE
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
90fbe6992c42-4
if "bad request" in str(exc).lower(): return BAD_REQUEST_RESPONSE if "unauthorized" in str(exc).lower(): return UNAUTHORIZED_RESPONSE return str(exc) self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"]) return self._get_schema_for_tables(tables_requested) [docs] def run(self, command: str) -> Any: """Execute a DAX command and return a json representing the results.""" result = requests.post( self.request_url, json={ "queries": [{"query": command}], "impersonatedUserName": self.impersonated_user_name, "serializerSettings": {"includeNulls": True}, }, headers=self.headers, timeout=10, ) result.raise_for_status() return result.json() [docs] async def arun(self, command: str) -> Any: """Execute a DAX command and return the result asynchronously.""" json_content = ( { "queries": [{"query": command}], "impersonatedUserName": self.impersonated_user_name, "serializerSettings": {"includeNulls": True}, }, ) if self.aiosession: async with self.aiosession.post( self.request_url, headers=self.headers, json=json_content, timeout=10 ) as response: response.raise_for_status() 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=json_content, timeout=10 ) as response: response.raise_for_status()
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
90fbe6992c42-5
) as response: response.raise_for_status() 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: """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 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
7aae1d7a91ff-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.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 BaseLanguageModel, 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. :meta private: """ return [self.output_key] def _call(self, inputs: Dict[str, Any]) -> Dict[str, str]: return self.apply([inputs])[0]
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
7aae1d7a91ff-1
return self.apply([inputs])[0] [docs] def generate(self, input_list: List[Dict[str, Any]]) -> LLMResult: """Generate LLM result from inputs.""" prompts, stop = self.prep_prompts(input_list) return self.llm.generate_prompt(prompts, stop) [docs] async def agenerate(self, input_list: List[Dict[str, Any]]) -> LLMResult: """Generate LLM result from inputs.""" prompts, stop = await self.aprep_prompts(input_list) return await self.llm.agenerate_prompt(prompts, stop) [docs] def prep_prompts( self, input_list: List[Dict[str, Any]] ) -> Tuple[List[PromptValue], Optional[List[str]]]: """Prepare prompts from inputs.""" stop = None if "stop" in input_list[0]: stop = input_list[0]["stop"] prompts = [] for inputs in input_list: selected_inputs = {k: inputs[k] for k in self.prompt.input_variables} prompt = self.prompt.format_prompt(**selected_inputs) _colored_text = get_colored_text(prompt.to_string(), "green") _text = "Prompt after formatting:\n" + _colored_text self.callback_manager.on_text(_text, end="\n", verbose=self.verbose) if "stop" in inputs and inputs["stop"] != stop: raise ValueError( "If `stop` is present in any inputs, should be present in all." ) prompts.append(prompt) return prompts, stop [docs] async def aprep_prompts( self, input_list: List[Dict[str, Any]]
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
7aae1d7a91ff-2
self, input_list: List[Dict[str, Any]] ) -> Tuple[List[PromptValue], Optional[List[str]]]: """Prepare prompts from inputs.""" stop = None if "stop" in input_list[0]: stop = input_list[0]["stop"] prompts = [] for inputs in input_list: selected_inputs = {k: inputs[k] for k in self.prompt.input_variables} prompt = self.prompt.format_prompt(**selected_inputs) _colored_text = get_colored_text(prompt.to_string(), "green") _text = "Prompt after formatting:\n" + _colored_text if self.callback_manager.is_async: await self.callback_manager.on_text( _text, end="\n", verbose=self.verbose ) else: self.callback_manager.on_text(_text, end="\n", verbose=self.verbose) if "stop" in inputs and inputs["stop"] != stop: raise ValueError( "If `stop` is present in any inputs, should be present in all." ) prompts.append(prompt) return prompts, stop [docs] def apply(self, input_list: List[Dict[str, Any]]) -> List[Dict[str, str]]: """Utilize the LLM generate method for speed gains.""" response = self.generate(input_list) return self.create_outputs(response) [docs] async def aapply(self, input_list: List[Dict[str, Any]]) -> List[Dict[str, str]]: """Utilize the LLM generate method for speed gains.""" response = await self.agenerate(input_list) return self.create_outputs(response) [docs] def create_outputs(self, response: LLMResult) -> List[Dict[str, str]]:
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
7aae1d7a91ff-3
"""Create outputs from response.""" return [ # Get the text of the top generated string. {self.output_key: generation[0].text} for generation in response.generations ] async def _acall(self, inputs: Dict[str, Any]) -> Dict[str, str]: return (await self.aapply([inputs]))[0] [docs] def predict(self, **kwargs: Any) -> str: """Format prompt with kwargs and pass to LLM. Args: **kwargs: Keys to pass to prompt template. Returns: Completion from LLM. Example: .. code-block:: python completion = llm.predict(adjective="funny") """ return self(kwargs)[self.output_key] [docs] async def apredict(self, **kwargs: Any) -> str: """Format prompt with kwargs and pass to LLM. Args: **kwargs: Keys to pass to prompt template. Returns: Completion from LLM. Example: .. code-block:: python completion = llm.predict(adjective="funny") """ return (await self.acall(kwargs))[self.output_key] [docs] def predict_and_parse(self, **kwargs: Any) -> Union[str, List[str], Dict[str, str]]: """Call predict and then parse the results.""" result = self.predict(**kwargs) if self.prompt.output_parser is not None: return self.prompt.output_parser.parse(result) else: return result [docs] async def apredict_and_parse( self, **kwargs: Any ) -> Union[str, List[str], Dict[str, str]]:
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
7aae1d7a91ff-4
) -> Union[str, List[str], Dict[str, str]]: """Call apredict and then parse the results.""" result = await self.apredict(**kwargs) if self.prompt.output_parser is not None: return self.prompt.output_parser.parse(result) else: return result [docs] def apply_and_parse( self, input_list: List[Dict[str, Any]] ) -> Sequence[Union[str, List[str], Dict[str, str]]]: """Call apply and then parse the results.""" result = self.apply(input_list) return self._parse_result(result) def _parse_result( self, result: List[Dict[str, str]] ) -> Sequence[Union[str, List[str], Dict[str, str]]]: if self.prompt.output_parser is not None: return [ self.prompt.output_parser.parse(res[self.output_key]) for res in result ] else: return result [docs] async def aapply_and_parse( self, input_list: List[Dict[str, Any]] ) -> Sequence[Union[str, List[str], Dict[str, str]]]: """Call apply and then parse the results.""" result = await self.aapply(input_list) return self._parse_result(result) @property def _chain_type(self) -> str: return "llm_chain" [docs] @classmethod def from_string(cls, llm: BaseLanguageModel, template: str) -> Chain: """Create LLMChain from LLM and template.""" prompt_template = PromptTemplate.from_template(template) return cls(llm=llm, prompt=prompt_template) By Harrison Chase © Copyright 2023, Harrison Chase.
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
7aae1d7a91ff-5
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
c4deb884d8b0-0
Source code for langchain.chains.sequential """Chain pipeline where the outputs of one step feed directly into next.""" from typing import Dict, List from pydantic import Extra, root_validator 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( f"The the input key(s) {''.join(overlapping_keys)} are found " f"in the Memory keys ({memory_keys}) - please use input and "
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
c4deb884d8b0-1
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]) -> Dict[str, str]: known_values = inputs.copy() for i, chain in enumerate(self.chains): outputs = chain(known_values, return_only_outputs=True) 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
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
c4deb884d8b0-2
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() 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]) -> Dict[str, str]: _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) if self.strip_outputs: _input = _input.strip()
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
c4deb884d8b0-3
if self.strip_outputs: _input = _input.strip() self.callback_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 Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
902c7621310b-0
Source code for langchain.chains.transform """Chain that runs an arbitrary python function.""" from typing import Callable, Dict, List 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]) -> Dict[str, str]: return self.transform(inputs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/transform.html
8b84f920fd65-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 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
8b84f920fd65-1
"""Load LLM chain from config dict.""" 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
8b84f920fd65-2
llm_chain=llm_chain, base_embeddings=embeddings, **config ) 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:
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
8b84f920fd65-3
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 "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: if "llm" in config: llm_config = config.pop("llm") llm = load_llm_from_config(llm_config) elif "llm_path" in config:
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
8b84f920fd65-4
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")) 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 ) 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"))
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
8b84f920fd65-5
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: 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:
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
8b84f920fd65-6
prompt = load_prompt_from_config(prompt_config) elif "prompt_path" in config: prompt = load_prompt(config.pop("prompt_path")) 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: 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: 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 PALChain(llm=llm, prompt=prompt, **config)
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
8b84f920fd65-7
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, **config, ) def _load_qa_with_sources_chain(config: dict, **kwargs: Any) -> QAWithSourcesChain:
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
8b84f920fd65-8
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) return SQLDatabaseChain(database=database, llm=llm, prompt=prompt, **config) def _load_vector_db_qa_with_sources_chain( 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:
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
8b84f920fd65-9
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_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)
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
8b84f920fd65-10
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: 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")
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
8b84f920fd65-11
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, "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, } 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:
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
8b84f920fd65-12
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 ): 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.
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
8b84f920fd65-13
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
3d76e78cb830-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 Dict, List from pydantic import Extra, Field, root_validator 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] @root_validator()
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html
3d76e78cb830-1
""" 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, str]) -> Dict[str, str]: from bs4 import BeautifulSoup # 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(**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 Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html
1634108e904f-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.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", "OPENAI_ORGANIZATION", default="", )
https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html
1634108e904f-1
"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 ValueError( "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]) -> 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 Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html
3443a13eca32-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 Dict, List from pydantic import Extra 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.llms.base import BaseLLM 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: BaseLLM, prompt: BasePromptTemplate, text_splitter: TextSplitter ) -> MapReduceChain: """Construct a map-reduce chain that uses the chain for map and reduce.""" llm_chain = LLMChain(llm=llm, prompt=prompt) reduce_chain = StuffDocumentsChain(llm_chain=llm_chain) combine_documents_chain = MapReduceDocumentsChain( llm_chain=llm_chain, combine_document_chain=reduce_chain ) return cls(
https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
3443a13eca32-1
) return cls( combine_documents_chain=combine_documents_chain, text_splitter=text_splitter ) 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]) -> Dict[str, str]: # Split the larger text into smaller chunks. texts = self.text_splitter.split_text(inputs[self.input_key]) docs = [Document(page_content=text) for text in texts] outputs = self.combine_documents_chain.run(input_documents=docs) return {self.output_key: outputs} By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
9467364d8485-0
Source code for langchain.chains.llm_summarization_checker.base """Chain for summarization with self-verification.""" from pathlib import Path from typing import Dict, List from pydantic import Extra from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.chains.sequential import SequentialChain from langchain.llms.base import BaseLLM from langchain.prompts.prompt import PromptTemplate PROMPTS_DIR = Path(__file__).parent / "prompts" CREATE_ASSERTIONS_PROMPT = PromptTemplate.from_file( PROMPTS_DIR / "create_facts.txt", ["summary"] ) CHECK_ASSERTIONS_PROMPT = PromptTemplate.from_file( PROMPTS_DIR / "check_facts.txt", ["assertions"] ) REVISED_SUMMARY_PROMPT = PromptTemplate.from_file( PROMPTS_DIR / "revise_summary.txt", ["checked_assertions", "summary"] ) ARE_ALL_TRUE_PROMPT = PromptTemplate.from_file( PROMPTS_DIR / "are_all_true_prompt.txt", ["checked_assertions"] ) [docs]class LLMSummarizationCheckerChain(Chain): """Chain for question-answering with self-verification. Example: .. code-block:: python from langchain import OpenAI, LLMSummarizationCheckerChain llm = OpenAI(temperature=0.0) checker_chain = LLMSummarizationCheckerChain(llm=llm) """ llm: BaseLLM """LLM wrapper to use.""" create_assertions_prompt: PromptTemplate = CREATE_ASSERTIONS_PROMPT check_assertions_prompt: PromptTemplate = CHECK_ASSERTIONS_PROMPT revised_summary_prompt: PromptTemplate = REVISED_SUMMARY_PROMPT
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html
9467364d8485-1
revised_summary_prompt: PromptTemplate = REVISED_SUMMARY_PROMPT are_all_true_prompt: PromptTemplate = ARE_ALL_TRUE_PROMPT input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: max_checks: int = 2 """Maximum number of times to check the assertions. Default to double-checking.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Return the singular input key. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Return the singular output key. :meta private: """ return [self.output_key] def _call(self, inputs: Dict[str, str]) -> Dict[str, str]: all_true = False count = 0 output = None original_input = inputs[self.input_key] chain_input = original_input while not all_true and count < self.max_checks: chain = SequentialChain( chains=[ LLMChain( llm=self.llm, prompt=self.create_assertions_prompt, output_key="assertions", verbose=self.verbose, ), LLMChain( llm=self.llm, prompt=self.check_assertions_prompt, output_key="checked_assertions", verbose=self.verbose, ), LLMChain( llm=self.llm, prompt=self.revised_summary_prompt, output_key="revised_summary", verbose=self.verbose, ),
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html
9467364d8485-2
output_key="revised_summary", verbose=self.verbose, ), LLMChain( llm=self.llm, output_key="all_true", prompt=self.are_all_true_prompt, verbose=self.verbose, ), ], input_variables=["summary"], output_variables=["all_true", "revised_summary"], verbose=self.verbose, ) output = chain({"summary": chain_input}) count += 1 if output["all_true"].strip() == "True": break if self.verbose: print(output["revised_summary"]) chain_input = output["revised_summary"] if not output: raise ValueError("No output from chain") return {self.output_key: output["revised_summary"].strip()} @property def _chain_type(self) -> str: return "llm_summarization_checker_chain" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html
0f7775e3f4b7-0
Source code for langchain.chains.hyde.base """Hypothetical Document Embeddings. https://arxiv.org/abs/2212.10496 """ from __future__ import annotations from typing import Dict, List import numpy as np from pydantic import Extra from langchain.chains.base import Chain from langchain.chains.hyde.prompts import PROMPT_MAP from langchain.chains.llm import LLMChain from langchain.embeddings.base import Embeddings from langchain.llms.base import BaseLLM [docs]class HypotheticalDocumentEmbedder(Chain, Embeddings): """Generate hypothetical document for query, and then embed that. Based on https://arxiv.org/abs/2212.10496 """ base_embeddings: Embeddings llm_chain: LLMChain class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Input keys for Hyde's LLM chain.""" return self.llm_chain.input_keys @property def output_keys(self) -> List[str]: """Output keys for Hyde's LLM chain.""" return self.llm_chain.output_keys [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Call the base embeddings.""" return self.base_embeddings.embed_documents(texts) [docs] def combine_embeddings(self, embeddings: List[List[float]]) -> List[float]: """Combine embeddings into final embeddings.""" return list(np.array(embeddings).mean(axis=0)) [docs] def embed_query(self, text: str) -> List[float]: """Generate a hypothetical document and embedded it."""
https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html
0f7775e3f4b7-1
"""Generate a hypothetical document and embedded it.""" var_name = self.llm_chain.input_keys[0] result = self.llm_chain.generate([{var_name: text}]) documents = [generation.text for generation in result.generations[0]] embeddings = self.embed_documents(documents) return self.combine_embeddings(embeddings) def _call(self, inputs: Dict[str, str]) -> Dict[str, str]: """Call the internal llm chain.""" return self.llm_chain._call(inputs) [docs] @classmethod def from_llm( cls, llm: BaseLLM, base_embeddings: Embeddings, prompt_key: str ) -> HypotheticalDocumentEmbedder: """Load and use LLMChain for a specific prompt key.""" prompt = PROMPT_MAP[prompt_key] llm_chain = LLMChain(llm=llm, prompt=prompt) return cls(base_embeddings=base_embeddings, llm_chain=llm_chain) @property def _chain_type(self) -> str: return "hyde_chain" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html
d50ffdbfd046-0
Source code for langchain.chains.graph_qa.base """Question answering over a graph.""" from __future__ import annotations from typing import Any, Dict, List from pydantic import Field from langchain.chains.base import Chain from langchain.chains.graph_qa.prompts import ENTITY_EXTRACTION_PROMPT, PROMPT from langchain.chains.llm import LLMChain from langchain.graphs.networkx_graph import NetworkxEntityGraph, get_entities from langchain.llms.base import BaseLLM from langchain.prompts.base import BasePromptTemplate [docs]class GraphQAChain(Chain): """Chain for question-answering against a graph.""" graph: NetworkxEntityGraph = Field(exclude=True) entity_extraction_chain: LLMChain qa_chain: LLMChain input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: @property def input_keys(self) -> List[str]: """Return the input keys. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Return the output keys. :meta private: """ _output_keys = [self.output_key] return _output_keys [docs] @classmethod def from_llm( cls, llm: BaseLLM, qa_prompt: BasePromptTemplate = PROMPT, entity_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT, **kwargs: Any, ) -> GraphQAChain: """Initialize from LLM.""" qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html
d50ffdbfd046-1
qa_chain = LLMChain(llm=llm, prompt=qa_prompt) entity_chain = LLMChain(llm=llm, prompt=entity_prompt) return cls(qa_chain=qa_chain, entity_extraction_chain=entity_chain, **kwargs) def _call(self, inputs: Dict[str, str]) -> Dict[str, Any]: """Extract entities, look up info and answer question.""" question = inputs[self.input_key] entity_string = self.entity_extraction_chain.run(question) self.callback_manager.on_text( "Entities Extracted:", end="\n", verbose=self.verbose ) self.callback_manager.on_text( entity_string, color="green", end="\n", verbose=self.verbose ) entities = get_entities(entity_string) context = "" for entity in entities: triplets = self.graph.get_entity_knowledge(entity) context += "\n".join(triplets) self.callback_manager.on_text("Full Context:", end="\n", verbose=self.verbose) self.callback_manager.on_text( context, color="green", end="\n", verbose=self.verbose ) result = self.qa_chain({"question": question, "context": context}) return {self.output_key: result[self.qa_chain.output_key]} By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html
4f649a0dd29b-0
Source code for langchain.chains.qa_generation.base from __future__ import annotations import json from typing import Any, Dict, List, Optional from pydantic import Field from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.chains.qa_generation.prompt import PROMPT_SELECTOR from langchain.prompts.base import BasePromptTemplate from langchain.schema import BaseLanguageModel from langchain.text_splitter import RecursiveCharacterTextSplitter, TextSplitter [docs]class QAGenerationChain(Chain): llm_chain: LLMChain text_splitter: TextSplitter = Field( default=RecursiveCharacterTextSplitter(chunk_overlap=500) ) input_key: str = "text" output_key: str = "questions" k: Optional[int] = None [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, prompt: Optional[BasePromptTemplate] = None, **kwargs: Any, ) -> QAGenerationChain: _prompt = prompt or PROMPT_SELECTOR.get_prompt(llm) chain = LLMChain(llm=llm, prompt=_prompt) return cls(llm_chain=chain, **kwargs) @property def _chain_type(self) -> str: raise NotImplementedError @property def input_keys(self) -> List[str]: return [self.input_key] @property def output_keys(self) -> List[str]: return [self.output_key] def _call(self, inputs: Dict[str, str]) -> Dict[str, Any]: docs = self.text_splitter.create_documents([inputs[self.input_key]])
https://python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html
4f649a0dd29b-1
docs = self.text_splitter.create_documents([inputs[self.input_key]]) results = self.llm_chain.generate([{"text": d.page_content} for d in docs]) qa = [json.loads(res[0].text) for res in results.generations] return {self.output_key: qa} async def _acall(self, inputs: Dict[str, str]) -> Dict[str, str]: raise NotImplementedError By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html
ce4b71509362-0
Source code for langchain.chains.retrieval_qa.base """Chain for question-answering against a vector database.""" from __future__ import annotations import warnings from abc import abstractmethod from typing import Any, Dict, List, Optional from pydantic import Extra, Field, root_validator from langchain.chains.base import Chain from langchain.chains.combine_documents.base import BaseCombineDocumentsChain from langchain.chains.combine_documents.stuff import StuffDocumentsChain from langchain.chains.llm import LLMChain from langchain.chains.question_answering import load_qa_chain from langchain.chains.question_answering.stuff_prompt import PROMPT_SELECTOR from langchain.prompts import PromptTemplate from langchain.schema import BaseLanguageModel, BaseRetriever, Document from langchain.vectorstores.base import VectorStore class BaseRetrievalQA(Chain): combine_documents_chain: BaseCombineDocumentsChain """Chain to use to combine the documents.""" input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: return_source_documents: bool = False """Return the source documents.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True allow_population_by_field_name = True @property def input_keys(self) -> List[str]: """Return the input keys. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Return the output keys. :meta private: """ _output_keys = [self.output_key] if self.return_source_documents:
https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
ce4b71509362-1
_output_keys = [self.output_key] if self.return_source_documents: _output_keys = _output_keys + ["source_documents"] return _output_keys @classmethod def from_llm( cls, llm: BaseLanguageModel, prompt: Optional[PromptTemplate] = None, **kwargs: Any, ) -> BaseRetrievalQA: """Initialize from LLM.""" _prompt = prompt or PROMPT_SELECTOR.get_prompt(llm) llm_chain = LLMChain(llm=llm, prompt=_prompt) document_prompt = PromptTemplate( input_variables=["page_content"], template="Context:\n{page_content}" ) combine_documents_chain = StuffDocumentsChain( llm_chain=llm_chain, document_variable_name="context", document_prompt=document_prompt, ) return cls(combine_documents_chain=combine_documents_chain, **kwargs) @classmethod def from_chain_type( cls, llm: BaseLanguageModel, chain_type: str = "stuff", chain_type_kwargs: Optional[dict] = None, **kwargs: Any, ) -> BaseRetrievalQA: """Load chain from chain type.""" _chain_type_kwargs = chain_type_kwargs or {} combine_documents_chain = load_qa_chain( llm, chain_type=chain_type, **_chain_type_kwargs ) return cls(combine_documents_chain=combine_documents_chain, **kwargs) @abstractmethod def _get_docs(self, question: str) -> List[Document]: """Get documents to do question answering over.""" def _call(self, inputs: Dict[str, str]) -> Dict[str, Any]:
https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
ce4b71509362-2
def _call(self, inputs: Dict[str, str]) -> Dict[str, Any]: """Run get_relevant_text and llm on input query. If chain has 'return_source_documents' as 'True', returns the retrieved documents as well under the key 'source_documents'. Example: .. code-block:: python res = indexqa({'query': 'This is my query'}) answer, docs = res['result'], res['source_documents'] """ question = inputs[self.input_key] docs = self._get_docs(question) answer = self.combine_documents_chain.run( input_documents=docs, question=question ) if self.return_source_documents: return {self.output_key: answer, "source_documents": docs} else: return {self.output_key: answer} @abstractmethod async def _aget_docs(self, question: str) -> List[Document]: """Get documents to do question answering over.""" async def _acall(self, inputs: Dict[str, str]) -> Dict[str, Any]: """Run get_relevant_text and llm on input query. If chain has 'return_source_documents' as 'True', returns the retrieved documents as well under the key 'source_documents'. Example: .. code-block:: python res = indexqa({'query': 'This is my query'}) answer, docs = res['result'], res['source_documents'] """ question = inputs[self.input_key] docs = await self._aget_docs(question) answer = await self.combine_documents_chain.arun( input_documents=docs, question=question ) if self.return_source_documents: return {self.output_key: answer, "source_documents": docs}
https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
ce4b71509362-3
return {self.output_key: answer, "source_documents": docs} else: return {self.output_key: answer} [docs]class RetrievalQA(BaseRetrievalQA): """Chain for question-answering against an index. Example: .. code-block:: python from langchain.llms import OpenAI from langchain.chains import RetrievalQA from langchain.faiss import FAISS from langchain.vectorstores.base import VectorStoreRetriever retriever = VectorStoreRetriever(vectorstore=FAISS(...)) retrievalQA = RetrievalQA.from_llm(llm=OpenAI(), retriever=retriever) """ retriever: BaseRetriever = Field(exclude=True) def _get_docs(self, question: str) -> List[Document]: return self.retriever.get_relevant_documents(question) async def _aget_docs(self, question: str) -> List[Document]: return await self.retriever.aget_relevant_documents(question) [docs]class VectorDBQA(BaseRetrievalQA): """Chain for question-answering against a vector database.""" vectorstore: VectorStore = Field(exclude=True, alias="vectorstore") """Vector Database to connect to.""" k: int = 4 """Number of documents to query for.""" search_type: str = "similarity" """Search type to use over vectorstore. `similarity` or `mmr`.""" search_kwargs: Dict[str, Any] = Field(default_factory=dict) """Extra search args.""" @root_validator() def raise_deprecation(cls, values: Dict) -> Dict: warnings.warn( "`VectorDBQA` is deprecated - "
https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
ce4b71509362-4
warnings.warn( "`VectorDBQA` is deprecated - " "please use `from langchain.chains import RetrievalQA`" ) return values @root_validator() def validate_search_type(cls, values: Dict) -> Dict: """Validate search type.""" if "search_type" in values: search_type = values["search_type"] if search_type not in ("similarity", "mmr"): raise ValueError(f"search_type of {search_type} not allowed.") return values def _get_docs(self, question: str) -> List[Document]: if self.search_type == "similarity": docs = self.vectorstore.similarity_search( question, k=self.k, **self.search_kwargs ) elif self.search_type == "mmr": docs = self.vectorstore.max_marginal_relevance_search( question, k=self.k, **self.search_kwargs ) else: raise ValueError(f"search_type of {self.search_type} not allowed.") return docs async def _aget_docs(self, question: str) -> List[Document]: raise NotImplementedError("VectorDBQA does not support async") @property def _chain_type(self) -> str: """Return the chain type.""" return "vector_db_qa" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
75e6aa978a0b-0
Source code for langchain.chains.api.base """Chain that makes API calls and summarizes the responses to answer a question.""" from __future__ import annotations from typing import Any, Dict, List, Optional from pydantic import Field, root_validator from langchain.chains.api.prompt import API_RESPONSE_PROMPT, API_URL_PROMPT from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.prompts import BasePromptTemplate from langchain.requests import TextRequestsWrapper from langchain.schema import BaseLanguageModel [docs]class APIChain(Chain): """Chain that makes API calls and summarizes the responses to answer a question.""" api_request_chain: LLMChain api_answer_chain: LLMChain requests_wrapper: TextRequestsWrapper = Field(exclude=True) api_docs: str question_key: str = "question" #: :meta private: output_key: str = "output" #: :meta private: @property def input_keys(self) -> List[str]: """Expect input key. :meta private: """ return [self.question_key] @property def output_keys(self) -> List[str]: """Expect output key. :meta private: """ return [self.output_key] @root_validator(pre=True) def validate_api_request_prompt(cls, values: Dict) -> Dict: """Check that api request prompt expects the right variables.""" input_vars = values["api_request_chain"].prompt.input_variables expected_vars = {"question", "api_docs"} if set(input_vars) != expected_vars: raise ValueError( f"Input variables should be {expected_vars}, got {input_vars}" ) return values
https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
75e6aa978a0b-1
) return values @root_validator(pre=True) def validate_api_answer_prompt(cls, values: Dict) -> Dict: """Check that api answer prompt expects the right variables.""" input_vars = values["api_answer_chain"].prompt.input_variables expected_vars = {"question", "api_docs", "api_url", "api_response"} if set(input_vars) != expected_vars: raise ValueError( f"Input variables should be {expected_vars}, got {input_vars}" ) return values def _call(self, inputs: Dict[str, str]) -> Dict[str, str]: question = inputs[self.question_key] api_url = self.api_request_chain.predict( question=question, api_docs=self.api_docs ) self.callback_manager.on_text( api_url, color="green", end="\n", verbose=self.verbose ) api_response = self.requests_wrapper.get(api_url) self.callback_manager.on_text( api_response, color="yellow", end="\n", verbose=self.verbose ) answer = self.api_answer_chain.predict( question=question, api_docs=self.api_docs, api_url=api_url, api_response=api_response, ) return {self.output_key: answer} async def _acall(self, inputs: Dict[str, str]) -> Dict[str, str]: question = inputs[self.question_key] api_url = await self.api_request_chain.apredict( question=question, api_docs=self.api_docs ) self.callback_manager.on_text( api_url, color="green", end="\n", verbose=self.verbose ) api_response = await self.requests_wrapper.aget(api_url) self.callback_manager.on_text(
https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
75e6aa978a0b-2
self.callback_manager.on_text( api_response, color="yellow", end="\n", verbose=self.verbose ) answer = await self.api_answer_chain.apredict( question=question, api_docs=self.api_docs, api_url=api_url, api_response=api_response, ) return {self.output_key: answer} [docs] @classmethod def from_llm_and_api_docs( cls, llm: BaseLanguageModel, api_docs: str, headers: Optional[dict] = None, api_url_prompt: BasePromptTemplate = API_URL_PROMPT, api_response_prompt: BasePromptTemplate = API_RESPONSE_PROMPT, **kwargs: Any, ) -> APIChain: """Load chain from just an LLM and the api docs.""" get_request_chain = LLMChain(llm=llm, prompt=api_url_prompt) requests_wrapper = TextRequestsWrapper(headers=headers) get_answer_chain = LLMChain(llm=llm, prompt=api_response_prompt) return cls( api_request_chain=get_request_chain, api_answer_chain=get_answer_chain, requests_wrapper=requests_wrapper, api_docs=api_docs, **kwargs, ) @property def _chain_type(self) -> str: return "api_chain" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
dfb66c88271a-0
Source code for langchain.chains.api.openapi.chain """Chain that makes API calls and summarizes the responses to answer a question.""" from __future__ import annotations import json from typing import Any, Dict, List, NamedTuple, Optional, cast from pydantic import BaseModel, Field from requests import Response from langchain.chains.api.openapi.requests_chain import APIRequesterChain from langchain.chains.api.openapi.response_chain import APIResponderChain from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.llms.base import BaseLLM from langchain.requests import Requests from langchain.tools.openapi.utils.api_models import APIOperation class _ParamMapping(NamedTuple): """Mapping from parameter name to parameter value.""" query_params: List[str] body_params: List[str] path_params: List[str] [docs]class OpenAPIEndpointChain(Chain, BaseModel): """Chain interacts with an OpenAPI endpoint using natural language.""" api_request_chain: LLMChain api_response_chain: Optional[LLMChain] api_operation: APIOperation requests: Requests = Field(exclude=True, default_factory=Requests) param_mapping: _ParamMapping = Field(alias="param_mapping") return_intermediate_steps: bool = False instructions_key: str = "instructions" #: :meta private: output_key: str = "output" #: :meta private: max_text_length: Optional[int] = Field(ge=0) #: :meta private: @property def input_keys(self) -> List[str]: """Expect input key. :meta private: """ return [self.instructions_key] @property def output_keys(self) -> List[str]:
https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
dfb66c88271a-1
@property def output_keys(self) -> List[str]: """Expect output key. :meta private: """ if not self.return_intermediate_steps: return [self.output_key] else: return [self.output_key, "intermediate_steps"] def _construct_path(self, args: Dict[str, str]) -> str: """Construct the path from the deserialized input.""" path = self.api_operation.base_url + self.api_operation.path for param in self.param_mapping.path_params: path = path.replace(f"{{{param}}}", args.pop(param, "")) return path def _extract_query_params(self, args: Dict[str, str]) -> Dict[str, str]: """Extract the query params from the deserialized input.""" query_params = {} for param in self.param_mapping.query_params: if param in args: query_params[param] = args.pop(param) return query_params def _extract_body_params(self, args: Dict[str, str]) -> Optional[Dict[str, str]]: """Extract the request body params from the deserialized input.""" body_params = None if self.param_mapping.body_params: body_params = {} for param in self.param_mapping.body_params: if param in args: body_params[param] = args.pop(param) return body_params [docs] def deserialize_json_input(self, serialized_args: str) -> dict: """Use the serialized typescript dictionary. Resolve the path, query params dict, and optional requestBody dict. """ args: dict = json.loads(serialized_args) path = self._construct_path(args) body_params = self._extract_body_params(args)
https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
dfb66c88271a-2
body_params = self._extract_body_params(args) query_params = self._extract_query_params(args) return { "url": path, "data": body_params, "params": query_params, } def _get_output(self, output: str, intermediate_steps: dict) -> dict: """Return the output from the API call.""" if self.return_intermediate_steps: return { self.output_key: output, "intermediate_steps": intermediate_steps, } else: return {self.output_key: output} def _call(self, inputs: Dict[str, str]) -> Dict[str, str]: intermediate_steps = {} instructions = inputs[self.instructions_key] instructions = instructions[: self.max_text_length] _api_arguments = self.api_request_chain.predict_and_parse( instructions=instructions ) api_arguments = cast(str, _api_arguments) intermediate_steps["request_args"] = api_arguments self.callback_manager.on_text( api_arguments, color="green", end="\n", verbose=self.verbose ) if api_arguments.startswith("ERROR"): return self._get_output(api_arguments, intermediate_steps) elif api_arguments.startswith("MESSAGE:"): return self._get_output( api_arguments[len("MESSAGE:") :], intermediate_steps ) try: request_args = self.deserialize_json_input(api_arguments) method = getattr(self.requests, self.api_operation.method.value) api_response: Response = method(**request_args) if api_response.status_code != 200: method_str = str(self.api_operation.method.value) response_text = ( f"{api_response.status_code}: {api_response.reason}"
https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
dfb66c88271a-3
response_text = ( f"{api_response.status_code}: {api_response.reason}" + f"\nFor {method_str.upper()} {request_args['url']}\n" + f"Called with args: {request_args['params']}" ) else: response_text = api_response.text except Exception as e: response_text = f"Error with message {str(e)}" response_text = response_text[: self.max_text_length] intermediate_steps["response_text"] = response_text self.callback_manager.on_text( response_text, color="blue", end="\n", verbose=self.verbose ) if self.api_response_chain is not None: _answer = self.api_response_chain.predict_and_parse( response=response_text, instructions=instructions, ) answer = cast(str, _answer) self.callback_manager.on_text( answer, color="yellow", end="\n", verbose=self.verbose ) return self._get_output(answer, intermediate_steps) else: return self._get_output(response_text, intermediate_steps) [docs] @classmethod def from_url_and_method( cls, spec_url: str, path: str, method: str, llm: BaseLLM, requests: Optional[Requests] = None, return_intermediate_steps: bool = False, **kwargs: Any # TODO: Handle async ) -> "OpenAPIEndpointChain": """Create an OpenAPIEndpoint from a spec at the specified url.""" operation = APIOperation.from_openapi_url(spec_url, path, method) return cls.from_api_operation( operation, requests=requests, llm=llm,
https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
dfb66c88271a-4
operation, requests=requests, llm=llm, return_intermediate_steps=return_intermediate_steps, **kwargs, ) [docs] @classmethod def from_api_operation( cls, operation: APIOperation, llm: BaseLLM, requests: Optional[Requests] = None, verbose: bool = False, return_intermediate_steps: bool = False, raw_response: bool = False, **kwargs: Any # TODO: Handle async ) -> "OpenAPIEndpointChain": """Create an OpenAPIEndpointChain from an operation and a spec.""" param_mapping = _ParamMapping( query_params=operation.query_params, body_params=operation.body_params, path_params=operation.path_params, ) requests_chain = APIRequesterChain.from_llm_and_typescript( llm, typescript_definition=operation.to_typescript(), verbose=verbose ) if raw_response: response_chain = None else: response_chain = APIResponderChain.from_llm(llm, verbose=verbose) _requests = requests or Requests() return cls( api_request_chain=requests_chain, api_response_chain=response_chain, api_operation=operation, requests=_requests, param_mapping=param_mapping, verbose=verbose, return_intermediate_steps=return_intermediate_steps, **kwargs, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
440fc7a1e7cd-0
Source code for langchain.chains.llm_checker.base """Chain for question-answering with self-verification.""" from typing import Dict, List from pydantic import Extra from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.chains.llm_checker.prompt import ( CHECK_ASSERTIONS_PROMPT, CREATE_DRAFT_ANSWER_PROMPT, LIST_ASSERTIONS_PROMPT, REVISED_ANSWER_PROMPT, ) from langchain.chains.sequential import SequentialChain from langchain.llms.base import BaseLLM from langchain.prompts import PromptTemplate [docs]class LLMCheckerChain(Chain): """Chain for question-answering with self-verification. Example: .. code-block:: python from langchain import OpenAI, LLMCheckerChain llm = OpenAI(temperature=0.7) checker_chain = LLMCheckerChain(llm=llm) """ llm: BaseLLM """LLM wrapper to use.""" create_draft_answer_prompt: PromptTemplate = CREATE_DRAFT_ANSWER_PROMPT list_assertions_prompt: PromptTemplate = LIST_ASSERTIONS_PROMPT check_assertions_prompt: PromptTemplate = CHECK_ASSERTIONS_PROMPT revised_answer_prompt: PromptTemplate = REVISED_ANSWER_PROMPT """Prompt to use when questioning the documents.""" input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Return the singular input key.
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html
440fc7a1e7cd-1
def input_keys(self) -> List[str]: """Return the singular input key. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Return the singular output key. :meta private: """ return [self.output_key] def _call(self, inputs: Dict[str, str]) -> Dict[str, str]: question = inputs[self.input_key] create_draft_answer_chain = LLMChain( llm=self.llm, prompt=self.create_draft_answer_prompt, output_key="statement" ) list_assertions_chain = LLMChain( llm=self.llm, prompt=self.list_assertions_prompt, output_key="assertions" ) check_assertions_chain = LLMChain( llm=self.llm, prompt=self.check_assertions_prompt, output_key="checked_assertions", ) revised_answer_chain = LLMChain( llm=self.llm, prompt=self.revised_answer_prompt, output_key="revised_statement", ) chains = [ create_draft_answer_chain, list_assertions_chain, check_assertions_chain, revised_answer_chain, ] question_to_checked_assertions_chain = SequentialChain( chains=chains, input_variables=["question"], output_variables=["revised_statement"], verbose=True, ) output = question_to_checked_assertions_chain({"question": question}) return {self.output_key: output["revised_statement"]} @property def _chain_type(self) -> str: return "llm_checker_chain" By Harrison Chase
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html
440fc7a1e7cd-2
return "llm_checker_chain" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html
92a2e7a9d43a-0
Source code for langchain.chains.conversational_retrieval.base """Chain for chatting with a vector database.""" from __future__ import annotations import warnings from abc import abstractmethod from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pydantic import Extra, Field, root_validator from langchain.chains.base import Chain from langchain.chains.combine_documents.base import BaseCombineDocumentsChain from langchain.chains.combine_documents.stuff import StuffDocumentsChain from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT from langchain.chains.llm import LLMChain from langchain.chains.question_answering import load_qa_chain from langchain.prompts.base import BasePromptTemplate from langchain.schema import BaseLanguageModel, BaseMessage, BaseRetriever, Document from langchain.vectorstores.base import VectorStore # Depending on the memory type and configuration, the chat history format may differ. # This needs to be consolidated. CHAT_TURN_TYPE = Union[Tuple[str, str], BaseMessage] _ROLE_MAP = {"human": "Human: ", "ai": "Assistant: "} def _get_chat_history(chat_history: List[CHAT_TURN_TYPE]) -> str: buffer = "" for dialogue_turn in chat_history: if isinstance(dialogue_turn, BaseMessage): role_prefix = _ROLE_MAP.get(dialogue_turn.type, f"{dialogue_turn.type}: ") buffer += f"\n{role_prefix}{dialogue_turn.content}" elif isinstance(dialogue_turn, tuple): human = "Human: " + dialogue_turn[0] ai = "Assistant: " + dialogue_turn[1] buffer += "\n" + "\n".join([human, ai]) else:
https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
92a2e7a9d43a-1
buffer += "\n" + "\n".join([human, ai]) else: raise ValueError( f"Unsupported chat history format: {type(dialogue_turn)}." f" Full chat history: {chat_history} " ) return buffer class BaseConversationalRetrievalChain(Chain): """Chain for chatting with an index.""" combine_docs_chain: BaseCombineDocumentsChain question_generator: LLMChain output_key: str = "answer" return_source_documents: bool = False get_chat_history: Optional[Callable[[CHAT_TURN_TYPE], str]] = None """Return the source documents.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True allow_population_by_field_name = True @property def input_keys(self) -> List[str]: """Input keys.""" return ["question", "chat_history"] @property def output_keys(self) -> List[str]: """Return the output keys. :meta private: """ _output_keys = [self.output_key] if self.return_source_documents: _output_keys = _output_keys + ["source_documents"] return _output_keys @abstractmethod def _get_docs(self, question: str, inputs: Dict[str, Any]) -> List[Document]: """Get docs.""" def _call(self, inputs: Dict[str, Any]) -> Dict[str, Any]: question = inputs["question"] get_chat_history = self.get_chat_history or _get_chat_history chat_history_str = get_chat_history(inputs["chat_history"]) if chat_history_str: new_question = self.question_generator.run(
https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
92a2e7a9d43a-2
if chat_history_str: new_question = self.question_generator.run( question=question, chat_history=chat_history_str ) else: new_question = question docs = self._get_docs(new_question, inputs) new_inputs = inputs.copy() new_inputs["question"] = new_question new_inputs["chat_history"] = chat_history_str answer = self.combine_docs_chain.run(input_documents=docs, **new_inputs) if self.return_source_documents: return {self.output_key: answer, "source_documents": docs} else: return {self.output_key: answer} @abstractmethod async def _aget_docs(self, question: str, inputs: Dict[str, Any]) -> List[Document]: """Get docs.""" async def _acall(self, inputs: Dict[str, Any]) -> Dict[str, Any]: question = inputs["question"] get_chat_history = self.get_chat_history or _get_chat_history chat_history_str = get_chat_history(inputs["chat_history"]) if chat_history_str: new_question = await self.question_generator.arun( question=question, chat_history=chat_history_str ) else: new_question = question docs = await self._aget_docs(new_question, inputs) new_inputs = inputs.copy() new_inputs["question"] = new_question new_inputs["chat_history"] = chat_history_str answer = await self.combine_docs_chain.arun(input_documents=docs, **new_inputs) if self.return_source_documents: return {self.output_key: answer, "source_documents": docs} else: return {self.output_key: answer} def save(self, file_path: Union[Path, str]) -> None:
https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
92a2e7a9d43a-3
def save(self, file_path: Union[Path, str]) -> None: if self.get_chat_history: raise ValueError("Chain not savable when `get_chat_history` is not None.") super().save(file_path) [docs]class ConversationalRetrievalChain(BaseConversationalRetrievalChain): """Chain for chatting with an index.""" retriever: BaseRetriever """Index to connect to.""" max_tokens_limit: Optional[int] = None """If set, restricts the docs to return from store based on tokens, enforced only for StuffDocumentChain""" def _reduce_tokens_below_limit(self, docs: List[Document]) -> List[Document]: num_docs = len(docs) if self.max_tokens_limit and isinstance( self.combine_docs_chain, StuffDocumentsChain ): tokens = [ self.combine_docs_chain.llm_chain.llm.get_num_tokens(doc.page_content) for doc in docs ] token_count = sum(tokens[:num_docs]) while token_count > self.max_tokens_limit: num_docs -= 1 token_count -= tokens[num_docs] return docs[:num_docs] def _get_docs(self, question: str, inputs: Dict[str, Any]) -> List[Document]: docs = self.retriever.get_relevant_documents(question) return self._reduce_tokens_below_limit(docs) async def _aget_docs(self, question: str, inputs: Dict[str, Any]) -> List[Document]: docs = await self.retriever.aget_relevant_documents(question) return self._reduce_tokens_below_limit(docs) [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel,
https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
92a2e7a9d43a-4
def from_llm( cls, llm: BaseLanguageModel, retriever: BaseRetriever, condense_question_prompt: BasePromptTemplate = CONDENSE_QUESTION_PROMPT, chain_type: str = "stuff", verbose: bool = False, combine_docs_chain_kwargs: Optional[Dict] = None, **kwargs: Any, ) -> BaseConversationalRetrievalChain: """Load chain from LLM.""" combine_docs_chain_kwargs = combine_docs_chain_kwargs or {} doc_chain = load_qa_chain( llm, chain_type=chain_type, verbose=verbose, **combine_docs_chain_kwargs, ) condense_question_chain = LLMChain( llm=llm, prompt=condense_question_prompt, verbose=verbose ) return cls( retriever=retriever, combine_docs_chain=doc_chain, question_generator=condense_question_chain, **kwargs, ) [docs]class ChatVectorDBChain(BaseConversationalRetrievalChain): """Chain for chatting with a vector database.""" vectorstore: VectorStore = Field(alias="vectorstore") top_k_docs_for_context: int = 4 search_kwargs: dict = Field(default_factory=dict) @property def _chain_type(self) -> str: return "chat-vector-db" @root_validator() def raise_deprecation(cls, values: Dict) -> Dict: warnings.warn( "`ChatVectorDBChain` is deprecated - " "please use `from langchain.chains import ConversationalRetrievalChain`" ) return values
https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
92a2e7a9d43a-5
) return values def _get_docs(self, question: str, inputs: Dict[str, Any]) -> List[Document]: vectordbkwargs = inputs.get("vectordbkwargs", {}) full_kwargs = {**self.search_kwargs, **vectordbkwargs} return self.vectorstore.similarity_search( question, k=self.top_k_docs_for_context, **full_kwargs ) async def _aget_docs(self, question: str, inputs: Dict[str, Any]) -> List[Document]: raise NotImplementedError("ChatVectorDBChain does not support async") [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, vectorstore: VectorStore, condense_question_prompt: BasePromptTemplate = CONDENSE_QUESTION_PROMPT, chain_type: str = "stuff", combine_docs_chain_kwargs: Optional[Dict] = None, **kwargs: Any, ) -> BaseConversationalRetrievalChain: """Load chain from LLM.""" combine_docs_chain_kwargs = combine_docs_chain_kwargs or {} doc_chain = load_qa_chain( llm, chain_type=chain_type, **combine_docs_chain_kwargs, ) condense_question_chain = LLMChain(llm=llm, prompt=condense_question_prompt) return cls( vectorstore=vectorstore, combine_docs_chain=doc_chain, question_generator=condense_question_chain, **kwargs, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
58f580e05f30-0
Source code for langchain.chains.combine_documents.base """Base interface for chains combining documents.""" from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional, Tuple from pydantic import Field from langchain.chains.base import Chain from langchain.docstore.document import Document from langchain.prompts.base import BasePromptTemplate from langchain.text_splitter import RecursiveCharacterTextSplitter, TextSplitter def format_document(doc: Document, prompt: BasePromptTemplate) -> str: """Format a document into a string based on a prompt template.""" base_info = {"page_content": doc.page_content} base_info.update(doc.metadata) missing_metadata = set(prompt.input_variables).difference(base_info) if len(missing_metadata) > 0: required_metadata = [ iv for iv in prompt.input_variables if iv != "page_content" ] raise ValueError( f"Document prompt requires documents to have metadata variables: " f"{required_metadata}. Received document with missing metadata: " f"{list(missing_metadata)}." ) document_info = {k: base_info[k] for k in prompt.input_variables} return prompt.format(**document_info) class BaseCombineDocumentsChain(Chain, ABC): """Base interface for chains combining documents.""" input_key: str = "input_documents" #: :meta private: output_key: str = "output_text" #: :meta private: @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: """
https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html
58f580e05f30-1
"""Return output key. :meta private: """ return [self.output_key] def prompt_length(self, docs: List[Document], **kwargs: Any) -> Optional[int]: """Return the prompt length given the documents passed in. Returns None if the method does not depend on the prompt length. """ return None @abstractmethod def combine_docs(self, docs: List[Document], **kwargs: Any) -> Tuple[str, dict]: """Combine documents into a single string.""" @abstractmethod async def acombine_docs( self, docs: List[Document], **kwargs: Any ) -> Tuple[str, dict]: """Combine documents into a single string asynchronously.""" def _call(self, inputs: Dict[str, Any]) -> Dict[str, str]: docs = inputs[self.input_key] # 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} output, extra_return_dict = self.combine_docs(docs, **other_keys) extra_return_dict[self.output_key] = output return extra_return_dict async def _acall(self, inputs: Dict[str, Any]) -> Dict[str, str]: docs = inputs[self.input_key] # 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} output, extra_return_dict = await self.acombine_docs(docs, **other_keys) extra_return_dict[self.output_key] = output return extra_return_dict [docs]class AnalyzeDocumentChain(Chain): """Chain that splits documents, then analyzes it in pieces."""
https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html
58f580e05f30-2
"""Chain that splits documents, then analyzes it in pieces.""" input_key: str = "input_document" #: :meta private: text_splitter: TextSplitter = Field(default_factory=RecursiveCharacterTextSplitter) combine_docs_chain: BaseCombineDocumentsChain @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.combine_docs_chain.output_keys def _call(self, inputs: Dict[str, Any]) -> Dict[str, str]: document = inputs[self.input_key] docs = self.text_splitter.create_documents([document]) # 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} other_keys[self.combine_docs_chain.input_key] = docs return self.combine_docs_chain(other_keys, return_only_outputs=True) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html
de80aeed33f8-0
Source code for langchain.chains.constitutional_ai.base """Chain for applying constitutional principles to the outputs of another chain.""" from typing import Any, Dict, List, Optional from langchain.chains.base import Chain from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple from langchain.chains.constitutional_ai.principles import PRINCIPLES from langchain.chains.constitutional_ai.prompts import CRITIQUE_PROMPT, REVISION_PROMPT from langchain.chains.llm import LLMChain from langchain.prompts.base import BasePromptTemplate from langchain.schema import BaseLanguageModel [docs]class ConstitutionalChain(Chain): """Chain for applying constitutional principles. Example: .. code-block:: python from langchain.llms import OpenAI from langchain.chains import LLMChain, ConstitutionalChain qa_prompt = PromptTemplate( template="Q: {question} A:", input_variables=["question"], ) qa_chain = LLMChain(llm=OpenAI(), prompt=qa_prompt) constitutional_chain = ConstitutionalChain.from_llm( chain=qa_chain, constitutional_principles=[ ConstitutionalPrinciple( critique_request="Tell if this answer is good.", revision_request="Give a better answer.", ) ], ) constitutional_chain.run(question="What is the meaning of life?") """ chain: LLMChain constitutional_principles: List[ConstitutionalPrinciple] critique_chain: LLMChain revision_chain: LLMChain [docs] @classmethod def get_principles( cls, names: Optional[List[str]] = None ) -> List[ConstitutionalPrinciple]: if names is None:
https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html
de80aeed33f8-1
) -> List[ConstitutionalPrinciple]: if names is None: return list(PRINCIPLES.values()) else: return [PRINCIPLES[name] for name in names] [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, chain: LLMChain, critique_prompt: BasePromptTemplate = CRITIQUE_PROMPT, revision_prompt: BasePromptTemplate = REVISION_PROMPT, **kwargs: Any, ) -> "ConstitutionalChain": """Create a chain from an LLM.""" critique_chain = LLMChain(llm=llm, prompt=critique_prompt) revision_chain = LLMChain(llm=llm, prompt=revision_prompt) return cls( chain=chain, critique_chain=critique_chain, revision_chain=revision_chain, **kwargs, ) @property def input_keys(self) -> List[str]: """Defines the input keys.""" return self.chain.input_keys @property def output_keys(self) -> List[str]: """Defines the output keys.""" return ["output"] def _call(self, inputs: Dict[str, str]) -> Dict[str, str]: response = self.chain.run(**inputs) input_prompt = self.chain.prompt.format(**inputs) self.callback_manager.on_text( text="Initial response: " + response + "\n\n", verbose=self.verbose, color="yellow", ) for constitutional_principle in self.constitutional_principles: # Do critique raw_critique = self.critique_chain.run( input_prompt=input_prompt, output_from_model=response,
https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html
de80aeed33f8-2
input_prompt=input_prompt, output_from_model=response, critique_request=constitutional_principle.critique_request, ) critique = self._parse_critique( output_string=raw_critique, ).strip() # Do revision revision = self.revision_chain.run( input_prompt=input_prompt, output_from_model=response, critique_request=constitutional_principle.critique_request, critique=critique, revision_request=constitutional_principle.revision_request, ).strip() response = revision self.callback_manager.on_text( text=f"Applying {constitutional_principle.name}..." + "\n\n", verbose=self.verbose, color="green", ) self.callback_manager.on_text( text="Critique: " + critique + "\n\n", verbose=self.verbose, color="blue", ) self.callback_manager.on_text( text="Updated response: " + revision + "\n\n", verbose=self.verbose, color="yellow", ) return {"output": response} @staticmethod def _parse_critique(output_string: str) -> str: if "Revision request:" not in output_string: return output_string output_string = output_string.split("Revision request:")[0] if "\n\n" in output_string: output_string = output_string.split("\n\n")[0] return output_string By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html
0aee63e7f654-0
Source code for langchain.chains.llm_math.base """Chain that interprets a prompt and executes python code to do math.""" import math import re from typing import Dict, List import numexpr from pydantic import Extra from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.chains.llm_math.prompt import PROMPT from langchain.prompts.base import BasePromptTemplate from langchain.schema import BaseLanguageModel [docs]class LLMMathChain(Chain): """Chain that interprets a prompt and executes python code to do math. Example: .. code-block:: python from langchain import LLMMathChain, OpenAI llm_math = LLMMathChain(llm=OpenAI()) """ llm: BaseLanguageModel """LLM wrapper to use.""" prompt: BasePromptTemplate = PROMPT """Prompt to use to translate to python if neccessary.""" input_key: str = "question" #: :meta private: output_key: str = "answer" #: :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]: """Expect output key. :meta private: """ return [self.output_key] def _evaluate_expression(self, expression: str) -> str: try: local_dict = {"pi": math.pi, "e": math.e}
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html
0aee63e7f654-1
try: local_dict = {"pi": math.pi, "e": math.e} output = str( numexpr.evaluate( expression.strip(), global_dict={}, # restrict access to globals local_dict=local_dict, # add common mathematical functions ) ) except Exception as e: raise ValueError(f"{e}. Please try again with a valid numerical expression") # Remove any leading and trailing brackets from the output return re.sub(r"^\[|\]$", "", output) def _process_llm_result(self, llm_output: str) -> Dict[str, str]: self.callback_manager.on_text(llm_output, color="green", verbose=self.verbose) llm_output = llm_output.strip() text_match = re.search(r"^```text(.*?)```", llm_output, re.DOTALL) if text_match: expression = text_match.group(1) output = self._evaluate_expression(expression) self.callback_manager.on_text("\nAnswer: ", verbose=self.verbose) self.callback_manager.on_text(output, color="yellow", verbose=self.verbose) answer = "Answer: " + output elif llm_output.startswith("Answer:"): answer = llm_output elif "Answer:" in llm_output: answer = "Answer: " + llm_output.split("Answer:")[-1] else: raise ValueError(f"unknown format from LLM: {llm_output}") return {self.output_key: answer} async def _aprocess_llm_result(self, llm_output: str) -> Dict[str, str]: if self.callback_manager.is_async: await self.callback_manager.on_text( llm_output, color="green", verbose=self.verbose
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html
0aee63e7f654-2
llm_output, color="green", verbose=self.verbose ) else: self.callback_manager.on_text( llm_output, color="green", verbose=self.verbose ) llm_output = llm_output.strip() text_match = re.search(r"^```text(.*?)```", llm_output, re.DOTALL) if text_match: expression = text_match.group(1) output = self._evaluate_expression(expression) if self.callback_manager.is_async: await self.callback_manager.on_text("\nAnswer: ", verbose=self.verbose) await self.callback_manager.on_text( output, color="yellow", verbose=self.verbose ) else: self.callback_manager.on_text("\nAnswer: ", verbose=self.verbose) self.callback_manager.on_text( output, color="yellow", verbose=self.verbose ) answer = "Answer: " + output elif llm_output.startswith("Answer:"): answer = llm_output elif "Answer:" in llm_output: answer = "Answer: " + llm_output.split("Answer:")[-1] else: raise ValueError(f"unknown format from LLM: {llm_output}") return {self.output_key: answer} def _call(self, inputs: Dict[str, str]) -> Dict[str, str]: llm_executor = LLMChain( prompt=self.prompt, llm=self.llm, callback_manager=self.callback_manager ) self.callback_manager.on_text(inputs[self.input_key], verbose=self.verbose) llm_output = llm_executor.predict( question=inputs[self.input_key], stop=["```output"] ) return self._process_llm_result(llm_output)
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html
0aee63e7f654-3
) return self._process_llm_result(llm_output) async def _acall(self, inputs: Dict[str, str]) -> Dict[str, str]: llm_executor = LLMChain( prompt=self.prompt, llm=self.llm, callback_manager=self.callback_manager ) if self.callback_manager.is_async: await self.callback_manager.on_text( inputs[self.input_key], verbose=self.verbose ) else: self.callback_manager.on_text(inputs[self.input_key], verbose=self.verbose) llm_output = await llm_executor.apredict( question=inputs[self.input_key], stop=["```output"] ) return await self._aprocess_llm_result(llm_output) @property def _chain_type(self) -> str: return "llm_math_chain" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html
2f76397f83c5-0
Source code for langchain.chains.llm_bash.base """Chain that interprets a prompt and executes bash code to perform bash operations.""" from typing import Dict, List from pydantic import Extra from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.chains.llm_bash.prompt import PROMPT from langchain.prompts.base import BasePromptTemplate from langchain.schema import BaseLanguageModel from langchain.utilities.bash import BashProcess [docs]class LLMBashChain(Chain): """Chain that interprets a prompt and executes bash code to perform bash operations. Example: .. code-block:: python from langchain import LLMBashChain, OpenAI llm_bash = LLMBashChain(llm=OpenAI()) """ llm: BaseLanguageModel """LLM wrapper to use.""" input_key: str = "question" #: :meta private: output_key: str = "answer" #: :meta private: prompt: BasePromptTemplate = PROMPT 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]: """Expect output key. :meta private: """ return [self.output_key] def _call(self, inputs: Dict[str, str]) -> Dict[str, str]: llm_executor = LLMChain(prompt=self.prompt, llm=self.llm) bash_executor = BashProcess()
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html
2f76397f83c5-1
bash_executor = BashProcess() self.callback_manager.on_text(inputs[self.input_key], verbose=self.verbose) t = llm_executor.predict(question=inputs[self.input_key]) self.callback_manager.on_text(t, color="green", verbose=self.verbose) t = t.strip() if t.startswith("```bash"): # Split the string into a list of substrings command_list = t.split("\n") print(command_list) # Remove the first and last substrings command_list = [s for s in command_list[1:-1]] output = bash_executor.run(command_list) self.callback_manager.on_text("\nAnswer: ", verbose=self.verbose) self.callback_manager.on_text(output, color="yellow", verbose=self.verbose) else: raise ValueError(f"unknown format from LLM: {t}") return {self.output_key: output} @property def _chain_type(self) -> str: return "llm_bash_chain" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html
43a4bce2b6b7-0
Source code for langchain.chains.sql_database.base """Chain for interacting with SQL Database.""" from __future__ import annotations from typing import Any, Dict, List, Optional from pydantic import Extra, Field from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.chains.sql_database.prompt import DECIDER_PROMPT, PROMPT, SQL_PROMPTS from langchain.prompts.base import BasePromptTemplate from langchain.schema import BaseLanguageModel from langchain.sql_database import SQLDatabase [docs]class SQLDatabaseChain(Chain): """Chain for interacting with SQL Database. Example: .. code-block:: python from langchain import SQLDatabaseChain, OpenAI, SQLDatabase db = SQLDatabase(...) db_chain = SQLDatabaseChain(llm=OpenAI(), database=db) """ llm: BaseLanguageModel """LLM wrapper to use.""" database: SQLDatabase = Field(exclude=True) """SQL Database to connect to.""" prompt: Optional[BasePromptTemplate] = None """Prompt to use to translate natural language to SQL.""" top_k: int = 5 """Number of results to return from the query""" input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: return_intermediate_steps: bool = False """Whether or not to return the intermediate steps along with the final answer.""" return_direct: bool = False """Whether or not to return the result of querying the SQL table directly.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property
https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html
43a4bce2b6b7-1
extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Return the singular input key. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Return the singular output key. :meta private: """ if not self.return_intermediate_steps: return [self.output_key] else: return [self.output_key, "intermediate_steps"] def _call(self, inputs: Dict[str, Any]) -> Dict[str, Any]: prompt = self.prompt or SQL_PROMPTS.get(self.database.dialect, PROMPT) llm_chain = LLMChain(llm=self.llm, prompt=prompt) input_text = f"{inputs[self.input_key]}\nSQLQuery:" self.callback_manager.on_text(input_text, verbose=self.verbose) # If not present, then defaults to None which is all tables. table_names_to_use = inputs.get("table_names_to_use") table_info = self.database.get_table_info(table_names=table_names_to_use) llm_inputs = { "input": input_text, "top_k": self.top_k, "dialect": self.database.dialect, "table_info": table_info, "stop": ["\nSQLResult:"], } intermediate_steps = [] sql_cmd = llm_chain.predict(**llm_inputs) intermediate_steps.append(sql_cmd) self.callback_manager.on_text(sql_cmd, color="green", verbose=self.verbose) result = self.database.run(sql_cmd) intermediate_steps.append(result) self.callback_manager.on_text("\nSQLResult: ", verbose=self.verbose)
https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html
43a4bce2b6b7-2
self.callback_manager.on_text("\nSQLResult: ", verbose=self.verbose) self.callback_manager.on_text(result, color="yellow", verbose=self.verbose) # If return direct, we just set the final result equal to the sql query if self.return_direct: final_result = result else: self.callback_manager.on_text("\nAnswer:", verbose=self.verbose) input_text += f"{sql_cmd}\nSQLResult: {result}\nAnswer:" llm_inputs["input"] = input_text final_result = llm_chain.predict(**llm_inputs) self.callback_manager.on_text( final_result, color="green", verbose=self.verbose ) chain_result: Dict[str, Any] = {self.output_key: final_result} if self.return_intermediate_steps: chain_result["intermediate_steps"] = intermediate_steps return chain_result @property def _chain_type(self) -> str: return "sql_database_chain" [docs]class SQLDatabaseSequentialChain(Chain): """Chain for querying SQL database that is a sequential chain. The chain is as follows: 1. Based on the query, determine which tables to use. 2. Based on those tables, call the normal SQL database chain. This is useful in cases where the number of tables in the database is large. """ return_intermediate_steps: bool = False [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, database: SQLDatabase, query_prompt: BasePromptTemplate = PROMPT, decider_prompt: BasePromptTemplate = DECIDER_PROMPT, **kwargs: Any, ) -> SQLDatabaseSequentialChain:
https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html
43a4bce2b6b7-3
**kwargs: Any, ) -> SQLDatabaseSequentialChain: """Load the necessary chains.""" sql_chain = SQLDatabaseChain( llm=llm, database=database, prompt=query_prompt, **kwargs ) decider_chain = LLMChain( llm=llm, prompt=decider_prompt, output_key="table_names" ) return cls(sql_chain=sql_chain, decider_chain=decider_chain, **kwargs) decider_chain: LLMChain sql_chain: SQLDatabaseChain input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: @property def input_keys(self) -> List[str]: """Return the singular input key. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Return the singular output key. :meta private: """ if not self.return_intermediate_steps: return [self.output_key] else: return [self.output_key, "intermediate_steps"] def _call(self, inputs: Dict[str, str]) -> Dict[str, str]: _table_names = self.sql_chain.database.get_usable_table_names() table_names = ", ".join(_table_names) llm_inputs = { "query": inputs[self.input_key], "table_names": table_names, } table_names_to_use = self.decider_chain.predict_and_parse(**llm_inputs) self.callback_manager.on_text( "Table names to use:", end="\n", verbose=self.verbose ) self.callback_manager.on_text(
https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html