id
stringlengths
14
15
text
stringlengths
35
2.51k
source
stringlengths
61
154
1e456a6bbf90-3
] return tables if tables else None if isinstance(table_names, str) and table_names != "": if table_names not in self.table_names: _LOGGER.warning("Table %s not found in dataset.", table_names) return None return [fix_table_name(table_names)] return self.table_names def _get_tables_todo(self, tables_todo: List[str]) -> List[str]: """Get the tables that still need to be queried.""" return [table for table in tables_todo if table not in self.schemas] def _get_schema_for_tables(self, table_names: List[str]) -> str: """Create a string of the table schemas for the supplied tables.""" schemas = [ schema for table, schema in self.schemas.items() if table in table_names ] return ", ".join(schemas) [docs] def get_table_info( self, table_names: Optional[Union[List[str], str]] = None ) -> str: """Get information about specified tables.""" tables_requested = self._get_tables_to_query(table_names) if tables_requested is None: return "No (valid) tables requested." tables_todo = self._get_tables_todo(tables_requested) for table in tables_todo: self._get_schema(table) return self._get_schema_for_tables(tables_requested) [docs] async def aget_table_info( self, table_names: Optional[Union[List[str], str]] = None ) -> str: """Get information about specified tables.""" tables_requested = self._get_tables_to_query(table_names) if tables_requested is None: return "No (valid) tables requested."
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
1e456a6bbf90-4
if tables_requested is None: return "No (valid) tables requested." tables_todo = self._get_tables_todo(tables_requested) await asyncio.gather(*[self._aget_schema(table) for table in tables_todo]) return self._get_schema_for_tables(tables_requested) def _get_schema(self, table: str) -> None: """Get the schema for a table.""" try: result = self.run( f"EVALUATE TOPN({self.sample_rows_in_table_info}, {table})" ) self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"]) except Timeout: _LOGGER.warning("Timeout while getting table info for %s", table) self.schemas[table] = "unknown" except Exception as exc: # pylint: disable=broad-exception-caught _LOGGER.warning("Error while getting table info for %s: %s", table, exc) self.schemas[table] = "unknown" async def _aget_schema(self, table: str) -> None: """Get the schema for a table.""" try: result = await self.arun( f"EVALUATE TOPN({self.sample_rows_in_table_info}, {table})" ) self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"]) except ServerTimeoutError: _LOGGER.warning("Timeout while getting table info for %s", table) self.schemas[table] = "unknown" except Exception as exc: # pylint: disable=broad-exception-caught _LOGGER.warning("Error while getting table info for %s: %s", table, exc)
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
1e456a6bbf90-5
self.schemas[table] = "unknown" def _create_json_content(self, command: str) -> dict[str, Any]: """Create the json content for the request.""" return { "queries": [{"query": rf"{command}"}], "impersonatedUserName": self.impersonated_user_name, "serializerSettings": {"includeNulls": True}, } [docs] def run(self, command: str) -> Any: """Execute a DAX command and return a json representing the results.""" _LOGGER.debug("Running command: %s", command) result = requests.post( self.request_url, json=self._create_json_content(command), headers=self.headers, timeout=10, ) return result.json() [docs] async def arun(self, command: str) -> Any: """Execute a DAX command and return the result asynchronously.""" _LOGGER.debug("Running command: %s", command) if self.aiosession: async with self.aiosession.post( self.request_url, headers=self.headers, json=self._create_json_content(command), timeout=10, ) as response: response_json = await response.json(content_type=response.content_type) return response_json async with aiohttp.ClientSession() as session: async with session.post( self.request_url, headers=self.headers, json=self._create_json_content(command), timeout=10, ) as response: response_json = await response.json(content_type=response.content_type) return response_json [docs]def json_to_md( json_contents: List[Dict[str, Union[str, int, float]]],
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
1e456a6bbf90-6
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 [docs]def fix_table_name(table: str) -> str: """Add single quotes around table names that contain spaces.""" if " " in table and not table.startswith("'") and not table.endswith("'"): return f"'{table}'" return table
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
ed73fd7a92c4-0
Source code for langchain.utilities.awslambda """Util that calls Lambda.""" import json from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator [docs]class LambdaWrapper(BaseModel): """Wrapper for AWS Lambda SDK. Docs for using: 1. pip install boto3 2. Create a lambda function using the AWS Console or CLI 3. Run `aws configure` and enter your AWS credentials """ lambda_client: Any #: :meta private: function_name: Optional[str] = None awslambda_tool_name: Optional[str] = None awslambda_tool_description: Optional[str] = None [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that python package exists in environment.""" try: import boto3 except ImportError: raise ImportError( "boto3 is not installed. Please install it with `pip install boto3`" ) values["lambda_client"] = boto3.client("lambda") values["function_name"] = values["function_name"] return values [docs] def run(self, query: str) -> str: """Invoke Lambda function and parse result.""" res = self.lambda_client.invoke( FunctionName=self.function_name, InvocationType="RequestResponse", Payload=json.dumps({"body": query}), ) try: payload_stream = res["Payload"] payload_string = payload_stream.read().decode("utf-8") answer = json.loads(payload_string)["body"] except StopIteration:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html
ed73fd7a92c4-1
answer = json.loads(payload_string)["body"] except StopIteration: return "Failed to parse response from Lambda" if answer is None or answer == "": # We don't want to return the assumption alone if answer is empty return "Request failed." else: return f"Result: {answer}"
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html
cab2a3762851-0
Source code for langchain.utilities.pupmed import json import logging import time import urllib.error import urllib.request from typing import List from pydantic import BaseModel, Extra from langchain.schema import Document logger = logging.getLogger(__name__) [docs]class PubMedAPIWrapper(BaseModel): """ Wrapper around PubMed API. This wrapper will use the PubMed API to conduct searches and fetch document summaries. By default, it will return the document summaries of the top-k results of an input search. Parameters: top_k_results: number of the top-scored document used for the PubMed tool load_max_docs: a limit to the number of loaded documents load_all_available_meta: if True: the `metadata` of the loaded Documents gets all available meta info (see https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch) if False: the `metadata` gets only the most informative fields. """ base_url_esearch = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" base_url_efetch = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?" max_retry = 5 sleep_time = 0.2 # Default values for the parameters top_k_results: int = 3 load_max_docs: int = 25 ARXIV_MAX_QUERY_LENGTH = 300 doc_content_chars_max: int = 2000 load_all_available_meta: bool = False email: str = "your_email@example.com" [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
cab2a3762851-1
"""Configuration for this pydantic object.""" extra = Extra.forbid [docs] def run(self, query: str) -> str: """ Run PubMed search and get the article meta information. See https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch It uses only the most informative fields of article meta information. """ try: # Retrieve the top-k results for the query docs = [ f"Published: {result['pub_date']}\nTitle: {result['title']}\n" f"Summary: {result['summary']}" for result in self.load(query[: self.ARXIV_MAX_QUERY_LENGTH]) ] # Join the results and limit the character count return ( "\n\n".join(docs)[: self.doc_content_chars_max] if docs else "No good PubMed Result was found" ) except Exception as ex: return f"PubMed exception: {ex}" [docs] def load(self, query: str) -> List[dict]: """ Search PubMed for documents matching the query. Return a list of dictionaries containing the document metadata. """ url = ( self.base_url_esearch + "db=pubmed&term=" + str({urllib.parse.quote(query)}) + f"&retmode=json&retmax={self.top_k_results}&usehistory=y" ) result = urllib.request.urlopen(url) text = result.read().decode("utf-8") json_text = json.loads(text) articles = [] webenv = json_text["esearchresult"]["webenv"] for uid in json_text["esearchresult"]["idlist"]:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
cab2a3762851-2
for uid in json_text["esearchresult"]["idlist"]: article = self.retrieve_article(uid, webenv) articles.append(article) # Convert the list of articles to a JSON string return articles def _transform_doc(self, doc: dict) -> Document: summary = doc.pop("summary") return Document(page_content=summary, metadata=doc) [docs] def load_docs(self, query: str) -> List[Document]: document_dicts = self.load(query=query) return [self._transform_doc(d) for d in document_dicts] [docs] def retrieve_article(self, uid: str, webenv: str) -> dict: url = ( self.base_url_efetch + "db=pubmed&retmode=xml&id=" + uid + "&webenv=" + webenv ) retry = 0 while True: try: result = urllib.request.urlopen(url) break except urllib.error.HTTPError as e: if e.code == 429 and retry < self.max_retry: # Too Many Requests error # wait for an exponentially increasing amount of time print( f"Too Many Requests, " f"waiting for {self.sleep_time:.2f} seconds..." ) time.sleep(self.sleep_time) self.sleep_time *= 2 retry += 1 else: raise e xml_text = result.read().decode("utf-8") # Get title title = "" if "<ArticleTitle>" in xml_text and "</ArticleTitle>" in xml_text: start_tag = "<ArticleTitle>" end_tag = "</ArticleTitle>" title = xml_text[
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
cab2a3762851-3
end_tag = "</ArticleTitle>" title = xml_text[ xml_text.index(start_tag) + len(start_tag) : xml_text.index(end_tag) ] # Get abstract abstract = "" if "<AbstractText>" in xml_text and "</AbstractText>" in xml_text: start_tag = "<AbstractText>" end_tag = "</AbstractText>" abstract = xml_text[ xml_text.index(start_tag) + len(start_tag) : xml_text.index(end_tag) ] # Get publication date pub_date = "" if "<PubDate>" in xml_text and "</PubDate>" in xml_text: start_tag = "<PubDate>" end_tag = "</PubDate>" pub_date = xml_text[ xml_text.index(start_tag) + len(start_tag) : xml_text.index(end_tag) ] # Return article as dictionary article = { "uid": uid, "title": title, "summary": abstract, "pub_date": pub_date, } return article
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
07f20d9bfa4d-0
Source code for langchain.utilities.google_search """Util that calls Google Search.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class GoogleSearchAPIWrapper(BaseModel): """Wrapper for Google Search API. Adapted from: Instructions adapted from https://stackoverflow.com/questions/ 37083058/ programmatically-searching-google-in-python-using-custom-search TODO: DOCS for using it 1. Install google-api-python-client - If you don't already have a Google account, sign up. - If you have never created a Google APIs Console project, read the Managing Projects page and create a project in the Google API Console. - Install the library using pip install google-api-python-client The current version of the library is 2.70.0 at this time 2. To create an API key: - Navigate to the APIs & Services→Credentials panel in Cloud Console. - Select Create credentials, then select API key from the drop-down menu. - The API key created dialog box displays your newly created key. - You now have an API_KEY 3. Setup Custom Search Engine so you can search the entire web - Create a custom search engine in this link. - In Sites to search, add any valid URL (i.e. www.stackoverflow.com). - That’s all you have to fill up, the rest doesn’t matter. In the left-side menu, click Edit search engine → {your search engine name} → Setup Set Search the entire web to ON. Remove the URL you added from the list of Sites to search. - Under Search engine ID you’ll find the search-engine-ID.
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
07f20d9bfa4d-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 [docs] 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", []) [docs] @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:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
07f20d9bfa4d-2
try: 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:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
07f20d9bfa4d-3
} if "snippet" in result: metadata_result["snippet"] = result["snippet"] metadata_results.append(metadata_result) return metadata_results
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html
a36d3a3caca9-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 [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key exists in environment.""" openweathermap_api_key = get_from_dict_or_env( values, "openweathermap_api_key", "OPENWEATHERMAP_API_KEY" ) try: import pyowm except ImportError: raise ImportError( "pyowm is not installed. Please install it with `pip install pyowm`" ) owm = pyowm.OWM(openweathermap_api_key) values["owm"] = owm return values def _format_weather_info(self, location: str, w: Any) -> str: detailed_status = w.detailed_status wind = w.wind() humidity = w.humidity temperature = w.temperature("celsius") rain = w.rain heat_index = w.heat_index
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
a36d3a3caca9-1
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)
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
657b96f8793c-0
Source code for langchain.utilities.scenexplain """Util that calls SceneXplain. In order to set this up, you need API key for the SceneXplain API. You can obtain a key by following the steps below. - Sign up for a free account at https://scenex.jina.ai/. - Navigate to the API Access page (https://scenex.jina.ai/api) and create a new API key. """ from typing import Dict import requests from pydantic import BaseModel, BaseSettings, Field, root_validator from langchain.utils import get_from_dict_or_env [docs]class SceneXplainAPIWrapper(BaseSettings, BaseModel): """Wrapper for SceneXplain API. In order to set this up, you need API key for the SceneXplain API. You can obtain a key by following the steps below. - Sign up for a free account at https://scenex.jina.ai/. - Navigate to the API Access page (https://scenex.jina.ai/api) and create a new API key. """ scenex_api_key: str = Field(..., env="SCENEX_API_KEY") scenex_api_url: str = ( "https://us-central1-causal-diffusion.cloudfunctions.net/describe" ) def _describe_image(self, image: str) -> str: headers = { "x-api-key": f"token {self.scenex_api_key}", "content-type": "application/json", } payload = { "data": [ { "image": image, "algorithm": "Ember", "languages": ["en"], } ] }
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html
657b96f8793c-1
"languages": ["en"], } ] } response = requests.post(self.scenex_api_url, headers=headers, json=payload) response.raise_for_status() result = response.json().get("result", []) img = result[0] if result else {} return img.get("text", "") [docs] @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key exists in environment.""" scenex_api_key = get_from_dict_or_env( values, "scenex_api_key", "SCENEX_API_KEY" ) values["scenex_api_key"] = scenex_api_key return values [docs] def run(self, image: str) -> str: """Run SceneXplain image explainer.""" description = self._describe_image(image) if not description: return "No description found." return description
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html
2a1d333abbbd-0
Source code for langchain.utilities.serpapi """Chain that calls SerpAPI. Heavily borrowed from https://github.com/ofirpress/self-ask """ import os import sys from typing import Any, Dict, Optional, Tuple import aiohttp from pydantic import BaseModel, Extra, Field, root_validator from langchain.utils import get_from_dict_or_env class HiddenPrints: """Context manager to hide prints.""" def __enter__(self) -> None: """Open file to pipe stdout to.""" self._original_stdout = sys.stdout sys.stdout = open(os.devnull, "w") def __exit__(self, *_: Any) -> None: """Close file that stdout was piped to.""" sys.stdout.close() sys.stdout = self._original_stdout [docs]class SerpAPIWrapper(BaseModel): """Wrapper around SerpAPI. To use, you should have the ``google-search-results`` python package installed, and the environment variable ``SERPAPI_API_KEY`` set with your API key, or pass `serpapi_api_key` as a named parameter to the constructor. Example: .. code-block:: python from langchain.utilities import SerpAPIWrapper serpapi = SerpAPIWrapper() """ search_engine: Any #: :meta private: params: dict = Field( default={ "engine": "google", "google_domain": "google.com", "gl": "us", "hl": "en", } ) serpapi_api_key: Optional[str] = None aiosession: Optional[aiohttp.ClientSession] = None [docs] class Config:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
2a1d333abbbd-1
[docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" serpapi_api_key = get_from_dict_or_env( values, "serpapi_api_key", "SERPAPI_API_KEY" ) values["serpapi_api_key"] = serpapi_api_key try: from serpapi import GoogleSearch values["search_engine"] = GoogleSearch except ImportError: raise ValueError( "Could not import serpapi python package. " "Please install it with `pip install google-search-results`." ) return values [docs] async def arun(self, query: str, **kwargs: Any) -> str: """Run query through SerpAPI and parse result async.""" return self._process_response(await self.aresults(query)) [docs] def run(self, query: str, **kwargs: Any) -> str: """Run query through SerpAPI and parse result.""" return self._process_response(self.results(query)) [docs] def results(self, query: str) -> dict: """Run query through SerpAPI and return the raw result.""" params = self.get_params(query) with HiddenPrints(): search = self.search_engine(params) res = search.get_dict() return res [docs] async def aresults(self, query: str) -> dict: """Use aiohttp to run query through SerpAPI and return the results async."""
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
2a1d333abbbd-2
"""Use aiohttp to run query through SerpAPI and return the results async.""" def construct_url_and_params() -> Tuple[str, Dict[str, str]]: params = self.get_params(query) params["source"] = "python" if self.serpapi_api_key: params["serp_api_key"] = self.serpapi_api_key params["output"] = "json" url = "https://serpapi.com/search" return url, params url, params = construct_url_and_params() if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.get(url, params=params) as response: res = await response.json() else: async with self.aiosession.get(url, params=params) as response: res = await response.json() return res [docs] def get_params(self, query: str) -> Dict[str, str]: """Get parameters for SerpAPI.""" _params = { "api_key": self.serpapi_api_key, "q": query, } params = {**self.params, **_params} return params @staticmethod def _process_response(res: dict) -> str: """Process response from SerpAPI.""" if "error" in res.keys(): raise ValueError(f"Got error from SerpAPI: {res['error']}") if "answer_box" in res.keys() and type(res["answer_box"]) == list: res["answer_box"] = res["answer_box"][0] if "answer_box" in res.keys() and "answer" in res["answer_box"].keys():
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
2a1d333abbbd-3
toret = res["answer_box"]["answer"] elif "answer_box" in res.keys() and "snippet" in res["answer_box"].keys(): toret = res["answer_box"]["snippet"] elif ( "answer_box" in res.keys() and "snippet_highlighted_words" in res["answer_box"].keys() ): toret = res["answer_box"]["snippet_highlighted_words"][0] elif ( "sports_results" in res.keys() and "game_spotlight" in res["sports_results"].keys() ): toret = res["sports_results"]["game_spotlight"] elif ( "shopping_results" in res.keys() and "title" in res["shopping_results"][0].keys() ): toret = res["shopping_results"][:3] elif ( "knowledge_graph" in res.keys() and "description" in res["knowledge_graph"].keys() ): toret = res["knowledge_graph"]["description"] elif "snippet" in res["organic_results"][0].keys(): toret = res["organic_results"][0]["snippet"] elif "link" in res["organic_results"][0].keys(): toret = res["organic_results"][0]["link"] else: toret = "No good search result found" return toret
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
18d668a93dfc-0
Source code for langchain.utilities.graphql import json from typing import Any, Callable, Dict, Optional from pydantic import BaseModel, Extra, root_validator [docs]class GraphQLAPIWrapper(BaseModel): """Wrapper around GraphQL API. To use, you should have the ``gql`` python package installed. This wrapper will use the GraphQL API to conduct queries. """ custom_headers: Optional[Dict[str, str]] = None graphql_endpoint: str gql_client: Any #: :meta private: gql_function: Callable[[str], Any] #: :meta private: [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in the environment.""" try: from gql import Client, gql from gql.transport.requests import RequestsHTTPTransport except ImportError as e: raise ImportError( "Could not import gql python package. " f"Try installing it with `pip install gql`. Received error: {e}" ) headers = values.get("custom_headers") transport = RequestsHTTPTransport( url=values["graphql_endpoint"], headers=headers, ) client = Client(transport=transport, fetch_schema_from_transport=True) values["gql_client"] = client values["gql_function"] = gql return values [docs] def run(self, query: str) -> str: """Run a GraphQL query and get the results.""" result = self._execute_query(query) return json.dumps(result, indent=2)
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html
18d668a93dfc-1
return json.dumps(result, indent=2) def _execute_query(self, query: str) -> Dict[str, Any]: """Execute a GraphQL query and return the results.""" document_node = self.gql_function(query) result = self.gql_client.execute(document_node) return result
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html
4eec71934f2d-0
Source code for langchain.utilities.google_places_api """Chain that calls Google Places API. """ import logging from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class GooglePlacesAPIWrapper(BaseModel): """Wrapper around Google Places API. To use, you should have the ``googlemaps`` python package installed, **an API key for the google maps platform**, and the enviroment variable ''GPLACES_API_KEY'' set with your API key , or pass 'gplaces_api_key' as a named parameter to the constructor. By default, this will return the all the results on the input query. You can use the top_k_results argument to limit the number of results. Example: .. code-block:: python from langchain import GooglePlacesAPIWrapper gplaceapi = GooglePlacesAPIWrapper() """ gplaces_api_key: Optional[str] = None google_map_client: Any #: :meta private: top_k_results: Optional[int] = None [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key is in your environment variable.""" gplaces_api_key = get_from_dict_or_env( values, "gplaces_api_key", "GPLACES_API_KEY" ) values["gplaces_api_key"] = gplaces_api_key try: import googlemaps values["google_map_client"] = googlemaps.Client(gplaces_api_key) except ImportError:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
4eec71934f2d-1
except ImportError: raise ImportError( "Could not import googlemaps python package. " "Please install it with `pip install googlemaps`." ) return values [docs] def run(self, query: str) -> str: """Run Places search and get k number of places that exists that match.""" search_results = self.google_map_client.places(query)["results"] num_to_return = len(search_results) places = [] if num_to_return == 0: return "Google Places did not find any places that match the description" num_to_return = ( num_to_return if self.top_k_results is None else min(num_to_return, self.top_k_results) ) for i in range(num_to_return): result = search_results[i] details = self.fetch_place_details(result["place_id"]) if details is not None: places.append(details) return "\n".join([f"{i+1}. {item}" for i, item in enumerate(places)]) [docs] def fetch_place_details(self, place_id: str) -> Optional[str]: try: place_details = self.google_map_client.place(place_id) formatted_details = self.format_place_details(place_details) return formatted_details except Exception as e: logging.error(f"An Error occurred while fetching place details: {e}") return None [docs] def format_place_details(self, place_details: Dict[str, Any]) -> Optional[str]: try: name = place_details.get("result", {}).get("name", "Unkown") address = place_details.get("result", {}).get( "formatted_address", "Unknown" )
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
4eec71934f2d-2
"formatted_address", "Unknown" ) phone_number = place_details.get("result", {}).get( "formatted_phone_number", "Unknown" ) website = place_details.get("result", {}).get("website", "Unknown") formatted_details = ( f"{name}\nAddress: {address}\n" f"Phone: {phone_number}\nWebsite: {website}\n\n" ) return formatted_details except Exception as e: logging.error(f"An error occurred while formatting place details: {e}") return None
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
1ef448ad7000-0
Source code for langchain.utilities.google_serper """Util that calls Google Search using the Serper.dev API.""" from typing import Any, Dict, List, Optional import aiohttp import requests from pydantic.class_validators import root_validator from pydantic.main import BaseModel from typing_extensions import Literal from langchain.utils import get_from_dict_or_env [docs]class GoogleSerperAPIWrapper(BaseModel): """Wrapper around the Serper.dev Google Search API. You can create a free API key at https://serper.dev. To use, you should have the environment variable ``SERPER_API_KEY`` set with your API key, or pass `serper_api_key` as a named parameter to the constructor. Example: .. code-block:: python from langchain import GoogleSerperAPIWrapper google_serper = GoogleSerperAPIWrapper() """ k: int = 10 gl: str = "us" hl: str = "en" # "places" and "images" is available from Serper but not implemented in the # parser of run(). They can be used in results() type: Literal["news", "search", "places", "images"] = "search" result_key_for_type = { "news": "news", "places": "places", "images": "images", "search": "organic", } tbs: Optional[str] = None serper_api_key: Optional[str] = None aiosession: Optional[aiohttp.ClientSession] = None [docs] class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True [docs] @root_validator()
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
1ef448ad7000-1
arbitrary_types_allowed = True [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key exists in environment.""" serper_api_key = get_from_dict_or_env( values, "serper_api_key", "SERPER_API_KEY" ) values["serper_api_key"] = serper_api_key return values [docs] def results(self, query: str, **kwargs: Any) -> Dict: """Run query through GoogleSearch.""" return self._google_serper_api_results( query, gl=self.gl, hl=self.hl, num=self.k, tbs=self.tbs, search_type=self.type, **kwargs, ) [docs] def run(self, query: str, **kwargs: Any) -> str: """Run query through GoogleSearch and parse result.""" results = self._google_serper_api_results( query, gl=self.gl, hl=self.hl, num=self.k, tbs=self.tbs, search_type=self.type, **kwargs, ) return self._parse_results(results) [docs] async def aresults(self, query: str, **kwargs: Any) -> Dict: """Run query through GoogleSearch.""" results = await self._async_google_serper_search_results( query, gl=self.gl, hl=self.hl, num=self.k, search_type=self.type, tbs=self.tbs, **kwargs, ) return results [docs] async def arun(self, query: str, **kwargs: Any) -> str:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
1ef448ad7000-2
"""Run query through GoogleSearch and parse result async.""" results = await self._async_google_serper_search_results( query, gl=self.gl, hl=self.hl, num=self.k, search_type=self.type, tbs=self.tbs, **kwargs, ) return self._parse_results(results) def _parse_snippets(self, results: dict) -> List[str]: snippets = [] if results.get("answerBox"): answer_box = results.get("answerBox", {}) if answer_box.get("answer"): return [answer_box.get("answer")] elif answer_box.get("snippet"): return [answer_box.get("snippet").replace("\n", " ")] elif answer_box.get("snippetHighlighted"): return answer_box.get("snippetHighlighted") if results.get("knowledgeGraph"): kg = results.get("knowledgeGraph", {}) title = kg.get("title") entity_type = kg.get("type") if entity_type: snippets.append(f"{title}: {entity_type}.") description = kg.get("description") if description: snippets.append(description) for attribute, value in kg.get("attributes", {}).items(): snippets.append(f"{title} {attribute}: {value}.") for result in results[self.result_key_for_type[self.type]][: self.k]: if "snippet" in result: snippets.append(result["snippet"]) for attribute, value in result.get("attributes", {}).items(): snippets.append(f"{attribute}: {value}.") if len(snippets) == 0: return ["No good Google Search Result was found"] return snippets
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
1ef448ad7000-3
return ["No good Google Search Result was found"] return snippets def _parse_results(self, results: dict) -> str: return " ".join(self._parse_snippets(results)) def _google_serper_api_results( self, search_term: str, search_type: str = "search", **kwargs: Any ) -> dict: headers = { "X-API-KEY": self.serper_api_key or "", "Content-Type": "application/json", } params = { "q": search_term, **{key: value for key, value in kwargs.items() if value is not None}, } response = requests.post( f"https://google.serper.dev/{search_type}", headers=headers, params=params ) response.raise_for_status() search_results = response.json() return search_results async def _async_google_serper_search_results( self, search_term: str, search_type: str = "search", **kwargs: Any ) -> dict: headers = { "X-API-KEY": self.serper_api_key or "", "Content-Type": "application/json", } url = f"https://google.serper.dev/{search_type}" params = { "q": search_term, **{key: value for key, value in kwargs.items() if value is not None}, } if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.post( url, params=params, headers=headers, raise_for_status=False ) as response: search_results = await response.json() else: async with self.aiosession.post(
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
1ef448ad7000-4
else: async with self.aiosession.post( url, params=params, headers=headers, raise_for_status=True ) as response: search_results = await response.json() return search_results
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
77ab16697016-0
Source code for langchain.utilities.arxiv """Util that calls Arxiv.""" import logging import os from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.schema import Document logger = logging.getLogger(__name__) [docs]class ArxivAPIWrapper(BaseModel): """Wrapper around ArxivAPI. To use, you should have the ``arxiv`` python package installed. https://lukasschwab.me/arxiv.py/index.html This wrapper will use the Arxiv API to conduct searches and fetch document summaries. By default, it will return the document summaries of the top-k results. It limits the Document content by doc_content_chars_max. Set doc_content_chars_max=None if you don't want to limit the content size. Parameters: top_k_results: number of the top-scored document used for the arxiv tool ARXIV_MAX_QUERY_LENGTH: the cut limit on the query used for the arxiv tool. load_max_docs: a limit to the number of loaded documents load_all_available_meta: if True: the `metadata` of the loaded Documents gets all available meta info (see https://lukasschwab.me/arxiv.py/index.html#Result), if False: the `metadata` gets only the most informative fields. """ arxiv_search: Any #: :meta private: arxiv_exceptions: Any # :meta private: top_k_results: int = 3 ARXIV_MAX_QUERY_LENGTH = 300 load_max_docs: int = 100 load_all_available_meta: bool = False doc_content_chars_max: Optional[int] = 4000 [docs] class Config:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
77ab16697016-1
[docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environment.""" try: import arxiv values["arxiv_search"] = arxiv.Search values["arxiv_exceptions"] = ( arxiv.ArxivError, arxiv.UnexpectedEmptyPageError, arxiv.HTTPError, ) values["arxiv_result"] = arxiv.Result except ImportError: raise ImportError( "Could not import arxiv python package. " "Please install it with `pip install arxiv`." ) return values [docs] def run(self, query: str) -> str: """ Run Arxiv search and get the article meta information. See https://lukasschwab.me/arxiv.py/index.html#Search See https://lukasschwab.me/arxiv.py/index.html#Result It uses only the most informative fields of article meta information. """ try: results = self.arxiv_search( # type: ignore query[: self.ARXIV_MAX_QUERY_LENGTH], max_results=self.top_k_results ).results() except self.arxiv_exceptions as ex: return f"Arxiv exception: {ex}" docs = [ f"Published: {result.updated.date()}\nTitle: {result.title}\n" f"Authors: {', '.join(a.name for a in result.authors)}\n" f"Summary: {result.summary}" for result in results ] if docs:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
77ab16697016-2
for result in results ] if docs: return "\n\n".join(docs)[: self.doc_content_chars_max] else: return "No good Arxiv Result was found" [docs] def load(self, query: str) -> List[Document]: """ Run Arxiv search and get the article texts plus the article meta information. See https://lukasschwab.me/arxiv.py/index.html#Search Returns: a list of documents with the document.page_content in text format """ try: import fitz except ImportError: raise ImportError( "PyMuPDF package not found, please install it with " "`pip install pymupdf`" ) try: results = self.arxiv_search( # type: ignore query[: self.ARXIV_MAX_QUERY_LENGTH], max_results=self.load_max_docs ).results() except self.arxiv_exceptions as ex: logger.debug("Error on arxiv: %s", ex) return [] docs: List[Document] = [] for result in results: try: doc_file_name: str = result.download_pdf() with fitz.open(doc_file_name) as doc_file: text: str = "".join(page.get_text() for page in doc_file) except FileNotFoundError as f_ex: logger.debug(f_ex) continue if self.load_all_available_meta: extra_metadata = { "entry_id": result.entry_id, "published_first_time": str(result.published.date()), "comment": result.comment, "journal_ref": result.journal_ref, "doi": result.doi, "primary_category": result.primary_category,
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
77ab16697016-3
"doi": result.doi, "primary_category": result.primary_category, "categories": result.categories, "links": [link.href for link in result.links], } else: extra_metadata = {} metadata = { "Published": str(result.updated.date()), "Title": result.title, "Authors": ", ".join(a.name for a in result.authors), "Summary": result.summary, **extra_metadata, } doc = Document( page_content=text[: self.doc_content_chars_max], metadata=metadata ) docs.append(doc) os.remove(doc_file_name) return docs
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
bb0eecf50215-0
Source code for langchain.utilities.bibtex """Util that calls bibtexparser.""" import logging from typing import Any, Dict, List, Mapping from pydantic import BaseModel, Extra, root_validator logger = logging.getLogger(__name__) OPTIONAL_FIELDS = [ "annotate", "booktitle", "editor", "howpublished", "journal", "keywords", "note", "organization", "publisher", "school", "series", "type", "doi", "issn", "isbn", ] [docs]class BibtexparserWrapper(BaseModel): """Wrapper around bibtexparser. To use, you should have the ``bibtexparser`` python package installed. https://bibtexparser.readthedocs.io/en/master/ This wrapper will use bibtexparser to load a collection of references from a bibtex file and fetch document summaries. """ [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environment.""" try: import bibtexparser # noqa except ImportError: raise ImportError( "Could not import bibtexparser python package. " "Please install it with `pip install bibtexparser`." ) return values [docs] def load_bibtex_entries(self, path: str) -> List[Dict[str, Any]]: """Load bibtex entries from the bibtex file at the given path."""
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html
bb0eecf50215-1
"""Load bibtex entries from the bibtex file at the given path.""" import bibtexparser with open(path) as file: entries = bibtexparser.load(file).entries return entries [docs] def get_metadata( self, entry: Mapping[str, Any], load_extra: bool = False ) -> Dict[str, Any]: """Get metadata for the given entry.""" publication = entry.get("journal") or entry.get("booktitle") if "url" in entry: url = entry["url"] elif "doi" in entry: url = f'https://doi.org/{entry["doi"]}' else: url = None meta = { "id": entry.get("ID"), "published_year": entry.get("year"), "title": entry.get("title"), "publication": publication, "authors": entry.get("author"), "abstract": entry.get("abstract"), "url": url, } if load_extra: for field in OPTIONAL_FIELDS: meta[field] = entry.get(field) return {k: v for k, v in meta.items() if v is not None}
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html
86a50fc7c431-0
Source code for langchain.utilities.wikipedia """Util that calls Wikipedia.""" import logging from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.schema import Document logger = logging.getLogger(__name__) WIKIPEDIA_MAX_QUERY_LENGTH = 300 [docs]class WikipediaAPIWrapper(BaseModel): """Wrapper around WikipediaAPI. To use, you should have the ``wikipedia`` python package installed. This wrapper will use the Wikipedia API to conduct searches and fetch page summaries. By default, it will return the page summaries of the top-k results. It limits the Document content by doc_content_chars_max. """ wiki_client: Any #: :meta private: top_k_results: int = 3 lang: str = "en" load_all_available_meta: bool = False doc_content_chars_max: int = 4000 [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environment.""" try: import wikipedia wikipedia.set_lang(values["lang"]) values["wiki_client"] = wikipedia except ImportError: raise ImportError( "Could not import wikipedia python package. " "Please install it with `pip install wikipedia`." ) return values [docs] def run(self, query: str) -> str: """Run Wikipedia search and get page summaries.""" page_titles = self.wiki_client.search(query[:WIKIPEDIA_MAX_QUERY_LENGTH]) summaries = []
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
86a50fc7c431-1
summaries = [] for page_title in page_titles[: self.top_k_results]: if wiki_page := self._fetch_page(page_title): if summary := self._formatted_page_summary(page_title, wiki_page): summaries.append(summary) if not summaries: return "No good Wikipedia Search Result was found" return "\n\n".join(summaries)[: self.doc_content_chars_max] @staticmethod def _formatted_page_summary(page_title: str, wiki_page: Any) -> Optional[str]: return f"Page: {page_title}\nSummary: {wiki_page.summary}" def _page_to_document(self, page_title: str, wiki_page: Any) -> Document: main_meta = { "title": page_title, "summary": wiki_page.summary, "source": wiki_page.url, } add_meta = ( { "categories": wiki_page.categories, "page_url": wiki_page.url, "image_urls": wiki_page.images, "related_titles": wiki_page.links, "parent_id": wiki_page.parent_id, "references": wiki_page.references, "revision_id": wiki_page.revision_id, "sections": wiki_page.sections, } if self.load_all_available_meta else {} ) doc = Document( page_content=wiki_page.content[: self.doc_content_chars_max], metadata={ **main_meta, **add_meta, }, ) return doc def _fetch_page(self, page: str) -> Optional[str]: try: return self.wiki_client.page(title=page, auto_suggest=False) except ( self.wiki_client.exceptions.PageError,
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
86a50fc7c431-2
except ( self.wiki_client.exceptions.PageError, self.wiki_client.exceptions.DisambiguationError, ): return None [docs] def load(self, query: str) -> List[Document]: """ Run Wikipedia search and get the article text plus the meta information. See Returns: a list of documents. """ page_titles = self.wiki_client.search(query[:WIKIPEDIA_MAX_QUERY_LENGTH]) docs = [] for page_title in page_titles[: self.top_k_results]: if wiki_page := self._fetch_page(page_title): if doc := self._page_to_document(page_title, wiki_page): docs.append(doc) return docs
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
dd575ae805fe-0
Source code for langchain.utilities.twilio """Util that calls Twilio.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class TwilioAPIWrapper(BaseModel): """Messaging Client using Twilio. To use, you should have the ``twilio`` python package installed, and the environment variables ``TWILIO_ACCOUNT_SID``, ``TWILIO_AUTH_TOKEN``, and ``TWILIO_FROM_NUMBER``, or pass `account_sid`, `auth_token`, and `from_number` as named parameters to the constructor. Example: .. code-block:: python from langchain.utilities.twilio import TwilioAPIWrapper twilio = TwilioAPIWrapper( account_sid="ACxxx", auth_token="xxx", from_number="+10123456789" ) twilio.run('test', '+12484345508') """ client: Any #: :meta private: account_sid: Optional[str] = None """Twilio account string identifier.""" auth_token: Optional[str] = None """Twilio auth token.""" from_number: Optional[str] = None """A Twilio phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, an [alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id), or a [Channel Endpoint address](https://www.twilio.com/docs/sms/channels#channel-addresses) that is enabled for the type of message you want to send. Phone numbers or
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
dd575ae805fe-1
that is enabled for the type of message you want to send. Phone numbers or [short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from Twilio also work here. You cannot, for example, spoof messages from a private cell phone number. If you are using `messaging_service_sid`, this parameter must be empty. """ # noqa: E501 [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = False [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" try: from twilio.rest import Client except ImportError: raise ImportError( "Could not import twilio python package. " "Please install it with `pip install twilio`." ) account_sid = get_from_dict_or_env(values, "account_sid", "TWILIO_ACCOUNT_SID") auth_token = get_from_dict_or_env(values, "auth_token", "TWILIO_AUTH_TOKEN") values["from_number"] = get_from_dict_or_env( values, "from_number", "TWILIO_FROM_NUMBER" ) values["client"] = Client(account_sid, auth_token) return values [docs] def run(self, body: str, to: str) -> str: """Run body through Twilio and respond with message sid. Args: body: The text of the message you want to send. Can be up to 1,600 characters in length. to: The destination phone number in
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
dd575ae805fe-2
characters in length. to: The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format for SMS/MMS or [Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses) for other 3rd-party channels. """ # noqa: E501 message = self.client.messages.create(to, from_=self.from_number, body=body) return message.sid
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html
b8957b2ebd22-0
Source code for langchain.utilities.jira """Util that calls Jira.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.tools.jira.prompt import ( JIRA_CATCH_ALL_PROMPT, JIRA_CONFLUENCE_PAGE_CREATE_PROMPT, JIRA_GET_ALL_PROJECTS_PROMPT, JIRA_ISSUE_CREATE_PROMPT, JIRA_JQL_PROMPT, ) from langchain.utils import get_from_dict_or_env # TODO: think about error handling, more specific api specs, and jql/project limits [docs]class JiraAPIWrapper(BaseModel): """Wrapper for Jira API.""" jira: Any #: :meta private: confluence: Any jira_username: Optional[str] = None jira_api_token: Optional[str] = None jira_instance_url: Optional[str] = None operations: List[Dict] = [ { "mode": "jql", "name": "JQL Query", "description": JIRA_JQL_PROMPT, }, { "mode": "get_projects", "name": "Get Projects", "description": JIRA_GET_ALL_PROJECTS_PROMPT, }, { "mode": "create_issue", "name": "Create Issue", "description": JIRA_ISSUE_CREATE_PROMPT, }, { "mode": "other", "name": "Catch all Jira API call", "description": JIRA_CATCH_ALL_PROMPT, }, { "mode": "create_page", "name": "Create confluence page",
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
b8957b2ebd22-1
"mode": "create_page", "name": "Create confluence page", "description": JIRA_CONFLUENCE_PAGE_CREATE_PROMPT, }, ] [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] def list(self) -> List[Dict]: return self.operations [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" jira_username = get_from_dict_or_env(values, "jira_username", "JIRA_USERNAME") values["jira_username"] = jira_username jira_api_token = get_from_dict_or_env( values, "jira_api_token", "JIRA_API_TOKEN" ) values["jira_api_token"] = jira_api_token jira_instance_url = get_from_dict_or_env( values, "jira_instance_url", "JIRA_INSTANCE_URL" ) values["jira_instance_url"] = jira_instance_url try: from atlassian import Confluence, Jira except ImportError: raise ImportError( "atlassian-python-api is not installed. " "Please install it with `pip install atlassian-python-api`" ) jira = Jira( url=jira_instance_url, username=jira_username, password=jira_api_token, cloud=True, ) confluence = Confluence( url=jira_instance_url, username=jira_username, password=jira_api_token, cloud=True, ) values["jira"] = jira
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
b8957b2ebd22-2
cloud=True, ) values["jira"] = jira values["confluence"] = confluence return values [docs] def parse_issues(self, issues: Dict) -> List[dict]: parsed = [] for issue in issues["issues"]: key = issue["key"] summary = issue["fields"]["summary"] created = issue["fields"]["created"][0:10] priority = issue["fields"]["priority"]["name"] status = issue["fields"]["status"]["name"] try: assignee = issue["fields"]["assignee"]["displayName"] except Exception: assignee = "None" rel_issues = {} for related_issue in issue["fields"]["issuelinks"]: if "inwardIssue" in related_issue.keys(): rel_type = related_issue["type"]["inward"] rel_key = related_issue["inwardIssue"]["key"] rel_summary = related_issue["inwardIssue"]["fields"]["summary"] if "outwardIssue" in related_issue.keys(): rel_type = related_issue["type"]["outward"] rel_key = related_issue["outwardIssue"]["key"] rel_summary = related_issue["outwardIssue"]["fields"]["summary"] rel_issues = {"type": rel_type, "key": rel_key, "summary": rel_summary} parsed.append( { "key": key, "summary": summary, "created": created, "assignee": assignee, "priority": priority, "status": status, "related_issues": rel_issues, } ) return parsed [docs] def parse_projects(self, projects: List[dict]) -> List[dict]:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
b8957b2ebd22-3
parsed = [] for project in projects: id = project["id"] key = project["key"] name = project["name"] type = project["projectTypeKey"] style = project["style"] parsed.append( {"id": id, "key": key, "name": name, "type": type, "style": style} ) return parsed [docs] def search(self, query: str) -> str: issues = self.jira.jql(query) parsed_issues = self.parse_issues(issues) parsed_issues_str = ( "Found " + str(len(parsed_issues)) + " issues:\n" + str(parsed_issues) ) return parsed_issues_str [docs] def project(self) -> str: projects = self.jira.projects() parsed_projects = self.parse_projects(projects) parsed_projects_str = ( "Found " + str(len(parsed_projects)) + " projects:\n" + str(parsed_projects) ) return parsed_projects_str [docs] def issue_create(self, query: str) -> str: try: import json except ImportError: raise ImportError( "json is not installed. Please install it with `pip install json`" ) params = json.loads(query) return self.jira.issue_create(fields=dict(params)) [docs] def page_create(self, query: str) -> str: try: import json except ImportError: raise ImportError( "json is not installed. Please install it with `pip install json`" ) params = json.loads(query) return self.confluence.create_page(**dict(params))
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
b8957b2ebd22-4
params = json.loads(query) return self.confluence.create_page(**dict(params)) [docs] def other(self, query: str) -> str: context = {"self": self} exec(f"result = {query}", context) result = context["result"] return str(result) [docs] def run(self, mode: str, query: str) -> str: if mode == "jql": return self.search(query) elif mode == "get_projects": return self.project() elif mode == "create_issue": return self.issue_create(query) elif mode == "other": return self.other(query) elif mode == "create_page": return self.page_create(query) else: raise ValueError(f"Got unexpected mode {mode}")
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
940029a887e7-0
Source code for langchain.utilities.openapi """Utility functions for parsing an OpenAPI spec.""" import copy import json import logging import re from enum import Enum from pathlib import Path from typing import Dict, List, Optional, Union import requests import yaml from openapi_schema_pydantic import ( Components, OpenAPI, Operation, Parameter, PathItem, Paths, Reference, RequestBody, Schema, ) from pydantic import ValidationError logger = logging.getLogger(__name__) [docs]class HTTPVerb(str, Enum): """HTTP verbs.""" GET = "get" PUT = "put" POST = "post" DELETE = "delete" OPTIONS = "options" HEAD = "head" PATCH = "patch" TRACE = "trace" [docs] @classmethod def from_str(cls, verb: str) -> "HTTPVerb": """Parse an HTTP verb.""" try: return cls(verb) except ValueError: raise ValueError(f"Invalid HTTP verb. Valid values are {cls.__members__}") [docs]class OpenAPISpec(OpenAPI): """OpenAPI Model that removes misformatted parts of the spec.""" @property def _paths_strict(self) -> Paths: if not self.paths: raise ValueError("No paths found in spec") return self.paths def _get_path_strict(self, path: str) -> PathItem: path_item = self._paths_strict.get(path) if not path_item: raise ValueError(f"No path found for {path}") return path_item @property def _components_strict(self) -> Components:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
940029a887e7-1
@property def _components_strict(self) -> Components: """Get components or err.""" if self.components is None: raise ValueError("No components found in spec. ") return self.components @property def _parameters_strict(self) -> Dict[str, Union[Parameter, Reference]]: """Get parameters or err.""" parameters = self._components_strict.parameters if parameters is None: raise ValueError("No parameters found in spec. ") return parameters @property def _schemas_strict(self) -> Dict[str, Schema]: """Get the dictionary of schemas or err.""" schemas = self._components_strict.schemas if schemas is None: raise ValueError("No schemas found in spec. ") return schemas @property def _request_bodies_strict(self) -> Dict[str, Union[RequestBody, Reference]]: """Get the request body or err.""" request_bodies = self._components_strict.requestBodies if request_bodies is None: raise ValueError("No request body found in spec. ") return request_bodies def _get_referenced_parameter(self, ref: Reference) -> Union[Parameter, Reference]: """Get a parameter (or nested reference) or err.""" ref_name = ref.ref.split("/")[-1] parameters = self._parameters_strict if ref_name not in parameters: raise ValueError(f"No parameter found for {ref_name}") return parameters[ref_name] def _get_root_referenced_parameter(self, ref: Reference) -> Parameter: """Get the root reference or err.""" parameter = self._get_referenced_parameter(ref) while isinstance(parameter, Reference):
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
940029a887e7-2
parameter = self._get_referenced_parameter(ref) while isinstance(parameter, Reference): parameter = self._get_referenced_parameter(parameter) return parameter [docs] def get_referenced_schema(self, ref: Reference) -> Schema: """Get a schema (or nested reference) or err.""" ref_name = ref.ref.split("/")[-1] schemas = self._schemas_strict if ref_name not in schemas: raise ValueError(f"No schema found for {ref_name}") return schemas[ref_name] [docs] def get_schema(self, schema: Union[Reference, Schema]) -> Schema: if isinstance(schema, Reference): return self.get_referenced_schema(schema) return schema def _get_root_referenced_schema(self, ref: Reference) -> Schema: """Get the root reference or err.""" schema = self.get_referenced_schema(ref) while isinstance(schema, Reference): schema = self.get_referenced_schema(schema) return schema def _get_referenced_request_body( self, ref: Reference ) -> Optional[Union[Reference, RequestBody]]: """Get a request body (or nested reference) or err.""" ref_name = ref.ref.split("/")[-1] request_bodies = self._request_bodies_strict if ref_name not in request_bodies: raise ValueError(f"No request body found for {ref_name}") return request_bodies[ref_name] def _get_root_referenced_request_body( self, ref: Reference ) -> Optional[RequestBody]: """Get the root request Body or err.""" request_body = self._get_referenced_request_body(ref) while isinstance(request_body, Reference):
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
940029a887e7-3
while isinstance(request_body, Reference): request_body = self._get_referenced_request_body(request_body) return request_body @staticmethod def _alert_unsupported_spec(obj: dict) -> None: """Alert if the spec is not supported.""" warning_message = ( " This may result in degraded performance." + " Convert your OpenAPI spec to 3.1.* spec" + " for better support." ) swagger_version = obj.get("swagger") openapi_version = obj.get("openapi") if isinstance(openapi_version, str): if openapi_version != "3.1.0": logger.warning( f"Attempting to load an OpenAPI {openapi_version}" f" spec. {warning_message}" ) else: pass elif isinstance(swagger_version, str): logger.warning( f"Attempting to load a Swagger {swagger_version}" f" spec. {warning_message}" ) else: raise ValueError( "Attempting to load an unsupported spec:" f"\n\n{obj}\n{warning_message}" ) [docs] @classmethod def parse_obj(cls, obj: dict) -> "OpenAPISpec": try: cls._alert_unsupported_spec(obj) return super().parse_obj(obj) except ValidationError as e: # We are handling possibly misconfigured specs and want to do a best-effort # job to get a reasonable interface out of it. new_obj = copy.deepcopy(obj) for error in e.errors(): keys = error["loc"] item = new_obj for key in keys[:-1]: item = item[key]
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
940029a887e7-4
for key in keys[:-1]: item = item[key] item.pop(keys[-1], None) return cls.parse_obj(new_obj) [docs] @classmethod def from_spec_dict(cls, spec_dict: dict) -> "OpenAPISpec": """Get an OpenAPI spec from a dict.""" return cls.parse_obj(spec_dict) [docs] @classmethod def from_text(cls, text: str) -> "OpenAPISpec": """Get an OpenAPI spec from a text.""" try: spec_dict = json.loads(text) except json.JSONDecodeError: spec_dict = yaml.safe_load(text) return cls.from_spec_dict(spec_dict) [docs] @classmethod def from_file(cls, path: Union[str, Path]) -> "OpenAPISpec": """Get an OpenAPI spec from a file path.""" path_ = path if isinstance(path, Path) else Path(path) if not path_.exists(): raise FileNotFoundError(f"{path} does not exist") with path_.open("r") as f: return cls.from_text(f.read()) [docs] @classmethod def from_url(cls, url: str) -> "OpenAPISpec": """Get an OpenAPI spec from a URL.""" response = requests.get(url) return cls.from_text(response.text) @property def base_url(self) -> str: """Get the base url.""" return self.servers[0].url [docs] def get_methods_for_path(self, path: str) -> List[str]: """Return a list of valid methods for the specified path.""" path_item = self._get_path_strict(path) results = []
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
940029a887e7-5
path_item = self._get_path_strict(path) results = [] for method in HTTPVerb: operation = getattr(path_item, method.value, None) if isinstance(operation, Operation): results.append(method.value) return results [docs] def get_parameters_for_path(self, path: str) -> List[Parameter]: path_item = self._get_path_strict(path) parameters = [] if not path_item.parameters: return [] for parameter in path_item.parameters: if isinstance(parameter, Reference): parameter = self._get_root_referenced_parameter(parameter) parameters.append(parameter) return parameters [docs] def get_operation(self, path: str, method: str) -> Operation: """Get the operation object for a given path and HTTP method.""" path_item = self._get_path_strict(path) operation_obj = getattr(path_item, method, None) if not isinstance(operation_obj, Operation): raise ValueError(f"No {method} method found for {path}") return operation_obj [docs] def get_parameters_for_operation(self, operation: Operation) -> List[Parameter]: """Get the components for a given operation.""" parameters = [] if operation.parameters: for parameter in operation.parameters: if isinstance(parameter, Reference): parameter = self._get_root_referenced_parameter(parameter) parameters.append(parameter) return parameters [docs] def get_request_body_for_operation( self, operation: Operation ) -> Optional[RequestBody]: """Get the request body for a given operation.""" request_body = operation.requestBody if isinstance(request_body, Reference): request_body = self._get_root_referenced_request_body(request_body) return request_body
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
940029a887e7-6
return request_body [docs] @staticmethod def get_cleaned_operation_id(operation: Operation, path: str, method: str) -> str: """Get a cleaned operation id from an operation id.""" operation_id = operation.operationId if operation_id is None: # Replace all punctuation of any kind with underscore path = re.sub(r"[^a-zA-Z0-9]", "_", path.lstrip("/")) operation_id = f"{path}_{method}" return operation_id.replace("-", "_").replace(".", "_").replace("/", "_")
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1b11b5a773d7-0
Source code for langchain.utilities.duckduckgo_search """Util that calls DuckDuckGo Search. No setup required. Free. https://pypi.org/project/duckduckgo-search/ """ from typing import Dict, List, Optional from pydantic import BaseModel, Extra from pydantic.class_validators import root_validator [docs]class DuckDuckGoSearchAPIWrapper(BaseModel): """Wrapper for DuckDuckGo Search API. Free and does not require any setup """ k: int = 10 region: Optional[str] = "wt-wt" safesearch: str = "moderate" time: Optional[str] = "y" max_results: int = 5 [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that python package exists in environment.""" try: from duckduckgo_search import DDGS # noqa: F401 except ImportError: raise ValueError( "Could not import duckduckgo-search python package. " "Please install it with `pip install duckduckgo-search`." ) return values [docs] def get_snippets(self, query: str) -> List[str]: """Run query through DuckDuckGo and return concatenated results.""" from duckduckgo_search import DDGS with DDGS() as ddgs: results = ddgs.text( query, region=self.region, safesearch=self.safesearch, timelimit=self.time, ) if results is None:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
1b11b5a773d7-1
timelimit=self.time, ) if results is None: return ["No good DuckDuckGo Search Result was found"] snippets = [] for i, res in enumerate(results, 1): if res is not None: snippets.append(res["body"]) if len(snippets) == self.max_results: break return snippets [docs] def run(self, query: str) -> str: snippets = self.get_snippets(query) return " ".join(snippets) [docs] def results(self, query: str, num_results: int) -> List[Dict[str, str]]: """Run query through DuckDuckGo and return metadata. Args: query: The query to search for. num_results: The number of results to return. Returns: A list of dictionaries with the following keys: snippet - The description of the result. title - The title of the result. link - The link to the result. """ from duckduckgo_search import DDGS with DDGS() as ddgs: results = ddgs.text( query, region=self.region, safesearch=self.safesearch, timelimit=self.time, ) if results is None: return [{"Result": "No good DuckDuckGo Search Result was found"}] def to_metadata(result: Dict) -> Dict[str, str]: return { "snippet": result["body"], "title": result["title"], "link": result["href"], } formatted_results = [] for i, res in enumerate(results, 1): if res is not None:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
1b11b5a773d7-2
if res is not None: formatted_results.append(to_metadata(res)) if len(formatted_results) == num_results: break return formatted_results
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
6e0937d2a8db-0
Source code for langchain.utilities.vertexai """Utilities to init Vertex AI.""" from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from google.auth.credentials import Credentials [docs]def raise_vertex_import_error() -> None: """Raise ImportError related to Vertex SDK being not available. Raises: ImportError: an ImportError that mentions a required version of the SDK. """ sdk = "'google-cloud-aiplatform>=1.26.0'" raise ImportError( "Could not import VertexAI. Please, install it with " f"pip install {sdk}" ) [docs]def init_vertexai( project: Optional[str] = None, location: Optional[str] = None, credentials: Optional["Credentials"] = None, ) -> None: """Init vertexai. Args: project: The default GCP project to use when making Vertex API calls. location: The default location to use when making API calls. credentials: The default custom credentials to use when making API calls. If not provided credentials will be ascertained from the environment. Raises: ImportError: If importing vertexai SDK did not succeed. """ try: import vertexai except ImportError: raise_vertex_import_error() vertexai.init( project=project, location=location, credentials=credentials, )
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/vertexai.html
c29190fd321f-0
Source code for langchain.utilities.searx_search """Utility for using SearxNG meta search API. SearxNG is a privacy-friendly free metasearch engine that aggregates results from `multiple search engines <https://docs.searxng.org/admin/engines/configured_engines.html>`_ and databases and supports the `OpenSearch <https://github.com/dewitt/opensearch/blob/master/opensearch-1-1-draft-6.md>`_ specification. More details on the installation instructions `here. <../../integrations/searx.html>`_ For the search API refer to https://docs.searxng.org/dev/search_api.html Quick Start ----------- In order to use this utility you need to provide the searx host. This can be done by passing the named parameter :attr:`searx_host <SearxSearchWrapper.searx_host>` or exporting the environment variable SEARX_HOST. Note: this is the only required parameter. Then create a searx search instance like this: .. code-block:: python from langchain.utilities import SearxSearchWrapper # when the host starts with `http` SSL is disabled and the connection # is assumed to be on a private network searx_host='http://self.hosted' search = SearxSearchWrapper(searx_host=searx_host) You can now use the ``search`` instance to query the searx API. Searching --------- Use the :meth:`run() <SearxSearchWrapper.run>` and :meth:`results() <SearxSearchWrapper.results>` methods to query the searx API. Other methods are available for convenience. :class:`SearxResults` is a convenience wrapper around the raw json result.
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
c29190fd321f-1
:class:`SearxResults` is a convenience wrapper around the raw json result. Example usage of the ``run`` method to make a search: .. code-block:: python s.run(query="what is the best search engine?") Engine Parameters ----------------- You can pass any `accepted searx search API <https://docs.searxng.org/dev/search_api.html>`_ parameters to the :py:class:`SearxSearchWrapper` instance. In the following example we are using the :attr:`engines <SearxSearchWrapper.engines>` and the ``language`` parameters: .. code-block:: python # assuming the searx host is set as above or exported as an env variable s = SearxSearchWrapper(engines=['google', 'bing'], language='es') Search Tips ----------- Searx offers a special `search syntax <https://docs.searxng.org/user/index.html#search-syntax>`_ that can also be used instead of passing engine parameters. For example the following query: .. code-block:: python s = SearxSearchWrapper("langchain library", engines=['github']) # can also be written as: s = SearxSearchWrapper("langchain library !github") # or even: s = SearxSearchWrapper("langchain library !gh") In some situations you might want to pass an extra string to the search query. For example when the `run()` method is called by an agent. The search suffix can also be used as a way to pass extra parameters to searx or the underlying search engines. .. code-block:: python # select the github engine and pass the search suffix
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
c29190fd321f-2
.. code-block:: python # select the github engine and pass the search suffix s = SearchWrapper("langchain library", query_suffix="!gh") s = SearchWrapper("langchain library") # select github the conventional google search syntax s.run("large language models", query_suffix="site:github.com") *NOTE*: A search suffix can be defined on both the instance and the method level. The resulting query will be the concatenation of the two with the former taking precedence. See `SearxNG Configured Engines <https://docs.searxng.org/admin/engines/configured_engines.html>`_ and `SearxNG Search Syntax <https://docs.searxng.org/user/index.html#id1>`_ for more details. Notes ----- This wrapper is based on the SearxNG fork https://github.com/searxng/searxng which is better maintained than the original Searx project and offers more features. Public searxNG instances often use a rate limiter for API usage, so you might want to use a self hosted instance and disable the rate limiter. If you are self-hosting an instance you can customize the rate limiter for your own network as described `here <https://docs.searxng.org/src/searx.botdetection.html#limiter-src>`_. For a list of public SearxNG instances see https://searx.space/ """ import json from typing import Any, Dict, List, Optional import aiohttp import requests from pydantic import BaseModel, Extra, Field, PrivateAttr, root_validator, validator from langchain.utils import get_from_dict_or_env def _get_default_params() -> dict:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
c29190fd321f-3
def _get_default_params() -> dict: return {"language": "en", "format": "json"} [docs]class SearxResults(dict): """Dict like wrapper around search api results.""" _data = "" def __init__(self, data: str): """Take a raw result from Searx and make it into a dict like object.""" json_data = json.loads(data) super().__init__(json_data) self.__dict__ = self def __str__(self) -> str: """Text representation of searx result.""" return self._data @property def results(self) -> Any: """Silence mypy for accessing this field. :meta private: """ return self.get("results") @property def answers(self) -> Any: """Helper accessor on the json result.""" return self.get("answers") [docs]class SearxSearchWrapper(BaseModel): """Wrapper for Searx API. To use you need to provide the searx host by passing the named parameter ``searx_host`` or exporting the environment variable ``SEARX_HOST``. In some situations you might want to disable SSL verification, for example if you are running searx locally. You can do this by passing the named parameter ``unsecure``. You can also pass the host url scheme as ``http`` to disable SSL. Example: .. code-block:: python from langchain.utilities import SearxSearchWrapper searx = SearxSearchWrapper(searx_host="http://localhost:8888") Example with SSL disabled: .. code-block:: python
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
c29190fd321f-4
Example with SSL disabled: .. code-block:: python from langchain.utilities import SearxSearchWrapper # note the unsecure parameter is not needed if you pass the url scheme as # http searx = SearxSearchWrapper(searx_host="http://localhost:8888", unsecure=True) """ _result: SearxResults = PrivateAttr() searx_host: str = "" unsecure: bool = False params: dict = Field(default_factory=_get_default_params) headers: Optional[dict] = None engines: Optional[List[str]] = [] categories: Optional[List[str]] = [] query_suffix: Optional[str] = "" k: int = 10 aiosession: Optional[Any] = None [docs] @validator("unsecure") def disable_ssl_warnings(cls, v: bool) -> bool: """Disable SSL warnings.""" if v: # requests.urllib3.disable_warnings() try: import urllib3 urllib3.disable_warnings() except ImportError as e: print(e) return v [docs] @root_validator() def validate_params(cls, values: Dict) -> Dict: """Validate that custom searx params are merged with default ones.""" user_params = values["params"] default = _get_default_params() values["params"] = {**default, **user_params} engines = values.get("engines") if engines: values["params"]["engines"] = ",".join(engines) categories = values.get("categories") if categories: values["params"]["categories"] = ",".join(categories)
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
c29190fd321f-5
if categories: values["params"]["categories"] = ",".join(categories) searx_host = get_from_dict_or_env(values, "searx_host", "SEARX_HOST") if not searx_host.startswith("http"): print( f"Warning: missing the url scheme on host \ ! assuming secure https://{searx_host} " ) searx_host = "https://" + searx_host elif searx_host.startswith("http://"): values["unsecure"] = True cls.disable_ssl_warnings(True) values["searx_host"] = searx_host return values [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def _searx_api_query(self, params: dict) -> SearxResults: """Actual request to searx API.""" raw_result = requests.get( self.searx_host, headers=self.headers, params=params, verify=not self.unsecure, ) # test if http result is ok if not raw_result.ok: raise ValueError("Searx API returned an error: ", raw_result.text) res = SearxResults(raw_result.text) self._result = res return res async def _asearx_api_query(self, params: dict) -> SearxResults: if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.get( self.searx_host, headers=self.headers, params=params, ssl=(lambda: False if self.unsecure else None)(), ) as response:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
c29190fd321f-6
) as response: if not response.ok: raise ValueError("Searx API returned an error: ", response.text) result = SearxResults(await response.text()) self._result = result else: async with self.aiosession.get( self.searx_host, headers=self.headers, params=params, verify=not self.unsecure, ) as response: if not response.ok: raise ValueError("Searx API returned an error: ", response.text) result = SearxResults(await response.text()) self._result = result return result [docs] def run( self, query: str, engines: Optional[List[str]] = None, categories: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> str: """Run query through Searx API and parse results. You can pass any other params to the searx query API. Args: query: The query to search for. query_suffix: Extra suffix appended to the query. engines: List of engines to use for the query. categories: List of categories to use for the query. **kwargs: extra parameters to pass to the searx API. Returns: str: The result of the query. Raises: ValueError: If an error occurred with the query. Example: This will make a query to the qwant engine: .. code-block:: python from langchain.utilities import SearxSearchWrapper searx = SearxSearchWrapper(searx_host="http://my.searx.host")
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
c29190fd321f-7
searx.run("what is the weather in France ?", engine="qwant") # the same result can be achieved using the `!` syntax of searx # to select the engine using `query_suffix` searx.run("what is the weather in France ?", query_suffix="!qwant") """ _params = { "q": query, } params = {**self.params, **_params, **kwargs} if self.query_suffix and len(self.query_suffix) > 0: params["q"] += " " + self.query_suffix if isinstance(query_suffix, str) and len(query_suffix) > 0: params["q"] += " " + query_suffix if isinstance(engines, list) and len(engines) > 0: params["engines"] = ",".join(engines) if isinstance(categories, list) and len(categories) > 0: params["categories"] = ",".join(categories) res = self._searx_api_query(params) if len(res.answers) > 0: toret = res.answers[0] # only return the content of the results list elif len(res.results) > 0: toret = "\n\n".join([r.get("content", "") for r in res.results[: self.k]]) else: toret = "No good search result found" return toret [docs] async def arun( self, query: str, engines: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> str: """Asynchronously version of `run`."""
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
c29190fd321f-8
) -> str: """Asynchronously version of `run`.""" _params = { "q": query, } params = {**self.params, **_params, **kwargs} if self.query_suffix and len(self.query_suffix) > 0: params["q"] += " " + self.query_suffix if isinstance(query_suffix, str) and len(query_suffix) > 0: params["q"] += " " + query_suffix if isinstance(engines, list) and len(engines) > 0: params["engines"] = ",".join(engines) res = await self._asearx_api_query(params) if len(res.answers) > 0: toret = res.answers[0] # only return the content of the results list elif len(res.results) > 0: toret = "\n\n".join([r.get("content", "") for r in res.results[: self.k]]) else: toret = "No good search result found" return toret [docs] def results( self, query: str, num_results: int, engines: Optional[List[str]] = None, categories: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> List[Dict]: """Run query through Searx API and returns the results with metadata. Args: query: The query to search for. query_suffix: Extra suffix appended to the query. num_results: Limit the number of results to return. engines: List of engines to use for the query.
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
c29190fd321f-9
engines: List of engines to use for the query. categories: List of categories to use for the query. **kwargs: extra parameters to pass to the searx API. Returns: Dict with the following keys: { snippet: The description of the result. title: The title of the result. link: The link to the result. engines: The engines used for the result. category: Searx category of the result. } """ _params = { "q": query, } params = {**self.params, **_params, **kwargs} if self.query_suffix and len(self.query_suffix) > 0: params["q"] += " " + self.query_suffix if isinstance(query_suffix, str) and len(query_suffix) > 0: params["q"] += " " + query_suffix if isinstance(engines, list) and len(engines) > 0: params["engines"] = ",".join(engines) if isinstance(categories, list) and len(categories) > 0: params["categories"] = ",".join(categories) results = self._searx_api_query(params).results[:num_results] if len(results) == 0: return [{"Result": "No good Search Result was found"}] return [ { "snippet": result.get("content", ""), "title": result["title"], "link": result["url"], "engines": result["engines"], "category": result["category"], } for result in results ] [docs] async def aresults( self,
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
c29190fd321f-10
] [docs] async def aresults( self, query: str, num_results: int, engines: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> List[Dict]: """Asynchronously query with json results. Uses aiohttp. See `results` for more info. """ _params = { "q": query, } params = {**self.params, **_params, **kwargs} if self.query_suffix and len(self.query_suffix) > 0: params["q"] += " " + self.query_suffix if isinstance(query_suffix, str) and len(query_suffix) > 0: params["q"] += " " + query_suffix if isinstance(engines, list) and len(engines) > 0: params["engines"] = ",".join(engines) results = (await self._asearx_api_query(params)).results[:num_results] if len(results) == 0: return [{"Result": "No good Search Result was found"}] return [ { "snippet": result.get("content", ""), "title": result["title"], "link": result["url"], "engines": result["engines"], "category": result["category"], } for result in results ]
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
d04b5323a297-0
Source code for langchain.utilities.loading """Utilities for loading configurations from langchain-hub.""" import os import re import tempfile from pathlib import Path, PurePosixPath from typing import Any, Callable, Optional, Set, TypeVar, Union from urllib.parse import urljoin import requests DEFAULT_REF = os.environ.get("LANGCHAIN_HUB_DEFAULT_REF", "master") URL_BASE = os.environ.get( "LANGCHAIN_HUB_URL_BASE", "https://raw.githubusercontent.com/hwchase17/langchain-hub/{ref}/", ) HUB_PATH_RE = re.compile(r"lc(?P<ref>@[^:]+)?://(?P<path>.*)") T = TypeVar("T") [docs]def try_load_from_hub( path: Union[str, Path], loader: Callable[[str], T], valid_prefix: str, valid_suffixes: Set[str], **kwargs: Any, ) -> Optional[T]: """Load configuration from hub. Returns None if path is not a hub path.""" if not isinstance(path, str) or not (match := HUB_PATH_RE.match(path)): return None ref, remote_path_str = match.groups() ref = ref[1:] if ref else DEFAULT_REF remote_path = Path(remote_path_str) if remote_path.parts[0] != valid_prefix: return None if remote_path.suffix[1:] not in valid_suffixes: raise ValueError("Unsupported file type.") # Using Path with URLs is not recommended, because on Windows # the backslash is used as the path separator, which can cause issues # when working with URLs that use forward slashes as the path separator.
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/loading.html
d04b5323a297-1
# when working with URLs that use forward slashes as the path separator. # Instead, use PurePosixPath to ensure that forward slashes are used as the # path separator, regardless of the operating system. full_url = urljoin(URL_BASE.format(ref=ref), PurePosixPath(remote_path).__str__()) r = requests.get(full_url, timeout=5) if r.status_code != 200: raise ValueError(f"Could not find file at {full_url}") with tempfile.TemporaryDirectory() as tmpdirname: file = Path(tmpdirname) / remote_path.name with open(file, "wb") as f: f.write(r.content) return loader(str(file), **kwargs)
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/loading.html
89c41aeee7c0-0
Source code for langchain.utilities.metaphor_search """Util that calls Metaphor Search API. In order to set this up, follow instructions at: """ import json from typing import Dict, List, Optional import aiohttp import requests from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env METAPHOR_API_URL = "https://api.metaphor.systems" [docs]class MetaphorSearchAPIWrapper(BaseModel): """Wrapper for Metaphor Search API.""" metaphor_api_key: str k: int = 10 [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def _metaphor_search_results( self, query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None, ) -> List[dict]: headers = {"X-Api-Key": self.metaphor_api_key} params = { "numResults": num_results, "query": query, "includeDomains": include_domains, "excludeDomains": exclude_domains, "startCrawlDate": start_crawl_date, "endCrawlDate": end_crawl_date, "startPublishedDate": start_published_date, "endPublishedDate": end_published_date, } response = requests.post( # type: ignore
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
89c41aeee7c0-1
} response = requests.post( # type: ignore f"{METAPHOR_API_URL}/search", headers=headers, json=params, ) response.raise_for_status() search_results = response.json() print(search_results) return search_results["results"] [docs] @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and endpoint exists in environment.""" metaphor_api_key = get_from_dict_or_env( values, "metaphor_api_key", "METAPHOR_API_KEY" ) values["metaphor_api_key"] = metaphor_api_key return values [docs] def results( self, query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None, ) -> List[Dict]: """Run query through Metaphor Search and return metadata. Args: query: The query to search for. num_results: The number of results to return. Returns: A list of dictionaries with the following keys: title - The title of the url - The url author - Author of the content, if applicable. Otherwise, None. published_date - Estimated date published in YYYY-MM-DD format. Otherwise, None. """ raw_search_results = self._metaphor_search_results( query, num_results=num_results,
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
89c41aeee7c0-2
query, num_results=num_results, include_domains=include_domains, exclude_domains=exclude_domains, start_crawl_date=start_crawl_date, end_crawl_date=end_crawl_date, start_published_date=start_published_date, end_published_date=end_published_date, ) return self._clean_results(raw_search_results) [docs] async def results_async( self, query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None, ) -> List[Dict]: """Get results from the Metaphor Search API asynchronously.""" # Function to perform the API call async def fetch() -> str: headers = {"X-Api-Key": self.metaphor_api_key} params = { "numResults": num_results, "query": query, "includeDomains": include_domains, "excludeDomains": exclude_domains, "startCrawlDate": start_crawl_date, "endCrawlDate": end_crawl_date, "startPublishedDate": start_published_date, "endPublishedDate": end_published_date, } async with aiohttp.ClientSession() as session: async with session.post( f"{METAPHOR_API_URL}/search", json=params, headers=headers ) as res: if res.status == 200: data = await res.text() return data else:
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
89c41aeee7c0-3
data = await res.text() return data else: raise Exception(f"Error {res.status}: {res.reason}") results_json_str = await fetch() results_json = json.loads(results_json_str) return self._clean_results(results_json["results"]) def _clean_results(self, raw_search_results: List[Dict]) -> List[Dict]: cleaned_results = [] for result in raw_search_results: cleaned_results.append( { "title": result["title"], "url": result["url"], "author": result["author"], "published_date": result["publishedDate"], } ) return cleaned_results
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html
633d67ff795d-0
Source code for langchain.utilities.python import sys from io import StringIO from typing import Dict, Optional from pydantic import BaseModel, Field [docs]class PythonREPL(BaseModel): """Simulates a standalone Python REPL.""" globals: Optional[Dict] = Field(default_factory=dict, alias="_globals") locals: Optional[Dict] = Field(default_factory=dict, alias="_locals") [docs] def run(self, command: str) -> str: """Run command with own globals/locals and returns anything printed.""" old_stdout = sys.stdout sys.stdout = mystdout = StringIO() try: exec(command, self.globals, self.locals) sys.stdout = old_stdout output = mystdout.getvalue() except Exception as e: sys.stdout = old_stdout output = repr(e) return output
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/python.html
d970cf8e9306-0
Source code for langchain.utilities.brave_search import json import requests from pydantic import BaseModel, Field [docs]class BraveSearchWrapper(BaseModel): api_key: str search_kwargs: dict = Field(default_factory=dict) [docs] def run(self, query: str) -> str: headers = { "X-Subscription-Token": self.api_key, "Accept": "application/json", } base_url = "https://api.search.brave.com/res/v1/web/search" req = requests.PreparedRequest() params = {**self.search_kwargs, **{"q": query}} req.prepare_url(base_url, params) if req.url is None: raise ValueError("prepared url is None, this should not happen") response = requests.get(req.url, headers=headers) if not response.ok: raise Exception(f"HTTP error {response.status_code}") parsed_response = response.json() web_search_results = parsed_response.get("web", {}).get("results", []) final_results = [] if isinstance(web_search_results, list): for item in web_search_results: final_results.append( { "title": item.get("title"), "link": item.get("url"), "snippet": item.get("description"), } ) return json.dumps(final_results)
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/brave_search.html
2b98891db38a-0
Source code for langchain.output_parsers.pydantic import json import re from typing import Type, TypeVar from pydantic import BaseModel, ValidationError from langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS from langchain.schema import BaseOutputParser, OutputParserException T = TypeVar("T", bound=BaseModel) [docs]class PydanticOutputParser(BaseOutputParser[T]): pydantic_object: Type[T] [docs] def parse(self, text: str) -> T: try: # Greedy search for 1st json candidate. match = re.search( r"\{.*\}", text.strip(), re.MULTILINE | re.IGNORECASE | re.DOTALL ) json_str = "" if match: json_str = match.group() json_object = json.loads(json_str, strict=False) return self.pydantic_object.parse_obj(json_object) except (json.JSONDecodeError, ValidationError) as e: name = self.pydantic_object.__name__ msg = f"Failed to parse {name} from completion {text}. Got: {e}" raise OutputParserException(msg) [docs] def get_format_instructions(self) -> str: schema = self.pydantic_object.schema() # Remove extraneous fields. reduced_schema = schema if "title" in reduced_schema: del reduced_schema["title"] if "type" in reduced_schema: del reduced_schema["type"] # Ensure json in context is well-formed with double quotes. schema_str = json.dumps(reduced_schema) return PYDANTIC_FORMAT_INSTRUCTIONS.format(schema=schema_str) @property def _type(self) -> str:
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html
2b98891db38a-1
@property def _type(self) -> str: return "pydantic"
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html
306df427de8e-0
Source code for langchain.output_parsers.combining from __future__ import annotations from typing import Any, Dict, List from pydantic import root_validator from langchain.schema import BaseOutputParser [docs]class CombiningOutputParser(BaseOutputParser): """Class to combine multiple output parsers into one.""" parsers: List[BaseOutputParser] [docs] @root_validator() def validate_parsers(cls, values: Dict[str, Any]) -> Dict[str, Any]: """Validate the parsers.""" parsers = values["parsers"] if len(parsers) < 2: raise ValueError("Must have at least two parsers") for parser in parsers: if parser._type == "combining": raise ValueError("Cannot nest combining parsers") if parser._type == "list": raise ValueError("Cannot comine list parsers") return values @property def _type(self) -> str: """Return the type key.""" return "combining" [docs] def get_format_instructions(self) -> str: """Instructions on how the LLM output should be formatted.""" initial = f"For your first output: {self.parsers[0].get_format_instructions()}" subsequent = "\n".join( f"Complete that output fully. Then produce another output, separated by two newline characters: {p.get_format_instructions()}" # noqa: E501 for p in self.parsers[1:] ) return f"{initial}\n{subsequent}" [docs] def parse(self, text: str) -> Dict[str, Any]: """Parse the output of an LLM call.""" texts = text.split("\n\n") output = dict()
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/combining.html
306df427de8e-1
texts = text.split("\n\n") output = dict() for txt, parser in zip(texts, self.parsers): output.update(parser.parse(txt.strip())) return output
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/combining.html
cf614e418373-0
Source code for langchain.output_parsers.datetime import random from datetime import datetime, timedelta from typing import List from langchain.schema import BaseOutputParser, OutputParserException from langchain.utils import comma_list def _generate_random_datetime_strings( pattern: str, n: int = 3, start_date: datetime = datetime(1, 1, 1), end_date: datetime = datetime.now() + timedelta(days=3650), ) -> List[str]: """ Generates n random datetime strings conforming to the given pattern within the specified date range. Pattern should be a string containing the desired format codes. start_date and end_date should be datetime objects representing the start and end of the date range. """ examples = [] delta = end_date - start_date for i in range(n): random_delta = random.uniform(0, delta.total_seconds()) dt = start_date + timedelta(seconds=random_delta) date_string = dt.strftime(pattern) examples.append(date_string) return examples [docs]class DatetimeOutputParser(BaseOutputParser[datetime]): format: str = "%Y-%m-%dT%H:%M:%S.%fZ" [docs] def get_format_instructions(self) -> str: examples = comma_list(_generate_random_datetime_strings(self.format)) return f"""Write a datetime string that matches the following pattern: "{self.format}". Examples: {examples}""" [docs] def parse(self, response: str) -> datetime: try: return datetime.strptime(response.strip(), self.format) except ValueError as e: raise OutputParserException( f"Could not parse datetime string: {response}" ) from e @property
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html
cf614e418373-1
) from e @property def _type(self) -> str: return "datetime"
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html
dfc78299dfa0-0
Source code for langchain.output_parsers.list from __future__ import annotations from abc import abstractmethod from typing import List from langchain.schema import BaseOutputParser [docs]class ListOutputParser(BaseOutputParser): """Class to parse the output of an LLM call to a list.""" @property def _type(self) -> str: return "list" [docs] @abstractmethod def parse(self, text: str) -> List[str]: """Parse the output of an LLM call.""" [docs]class CommaSeparatedListOutputParser(ListOutputParser): """Parse out comma separated lists.""" [docs] def get_format_instructions(self) -> str: return ( "Your response should be a list of comma separated values, " "eg: `foo, bar, baz`" ) [docs] def parse(self, text: str) -> List[str]: """Parse the output of an LLM call.""" return text.strip().split(", ")
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html
63e383c26b87-0
Source code for langchain.output_parsers.json from __future__ import annotations import json import re from typing import List from langchain.schema import OutputParserException [docs]def parse_json_markdown(json_string: str) -> dict: """ Parse a JSON string from a Markdown string. Args: json_string: The Markdown string. Returns: The parsed JSON object as a Python dictionary. """ # Try to find JSON string within triple backticks match = re.search(r"```(json)?(.*?)```", json_string, re.DOTALL) # If no match found, assume the entire string is a JSON string if match is None: json_str = json_string else: # If match found, use the content within the backticks json_str = match.group(2) # Strip whitespace and newlines from the start and end json_str = json_str.strip() # Parse the JSON string into a Python dictionary parsed = json.loads(json_str) return parsed [docs]def parse_and_check_json_markdown(text: str, expected_keys: List[str]) -> dict: """ Parse a JSON string from a Markdown string and check that it contains the expected keys. Args: text: The Markdown string. expected_keys: The expected keys in the JSON string. Returns: The parsed JSON object as a Python dictionary. """ try: json_obj = parse_json_markdown(text) except json.JSONDecodeError as e: raise OutputParserException(f"Got invalid JSON object. Error: {e}") for key in expected_keys: if key not in json_obj: raise OutputParserException(
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html
63e383c26b87-1
if key not in json_obj: raise OutputParserException( f"Got invalid return object. Expected key `{key}` " f"to be present, but got {json_obj}" ) return json_obj
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html
5d50b5bfdcbb-0
Source code for langchain.output_parsers.retry from __future__ import annotations from typing import TypeVar from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.prompts.base import BasePromptTemplate from langchain.prompts.prompt import PromptTemplate from langchain.schema import ( BaseOutputParser, OutputParserException, PromptValue, ) NAIVE_COMPLETION_RETRY = """Prompt: {prompt} Completion: {completion} Above, the Completion did not satisfy the constraints given in the Prompt. Please try again:""" NAIVE_COMPLETION_RETRY_WITH_ERROR = """Prompt: {prompt} Completion: {completion} Above, the Completion did not satisfy the constraints given in the Prompt. Details: {error} Please try again:""" NAIVE_RETRY_PROMPT = PromptTemplate.from_template(NAIVE_COMPLETION_RETRY) NAIVE_RETRY_WITH_ERROR_PROMPT = PromptTemplate.from_template( NAIVE_COMPLETION_RETRY_WITH_ERROR ) T = TypeVar("T") [docs]class RetryOutputParser(BaseOutputParser[T]): """Wraps a parser and tries to fix parsing errors. Does this by passing the original prompt and the completion to another LLM, and telling it the completion did not satisfy criteria in the prompt. """ parser: BaseOutputParser[T] retry_chain: LLMChain [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, parser: BaseOutputParser[T], prompt: BasePromptTemplate = NAIVE_RETRY_PROMPT, ) -> RetryOutputParser[T]: chain = LLMChain(llm=llm, prompt=prompt)
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html
5d50b5bfdcbb-1
chain = LLMChain(llm=llm, prompt=prompt) return cls(parser=parser, retry_chain=chain) [docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T: try: parsed_completion = self.parser.parse(completion) except OutputParserException: new_completion = self.retry_chain.run( prompt=prompt_value.to_string(), completion=completion ) parsed_completion = self.parser.parse(new_completion) return parsed_completion [docs] def parse(self, completion: str) -> T: raise NotImplementedError( "This OutputParser can only be called by the `parse_with_prompt` method." ) [docs] def get_format_instructions(self) -> str: return self.parser.get_format_instructions() @property def _type(self) -> str: return "retry" [docs]class RetryWithErrorOutputParser(BaseOutputParser[T]): """Wraps a parser and tries to fix parsing errors. Does this by passing the original prompt, the completion, AND the error that was raised to another language model and telling it that the completion did not work, and raised the given error. Differs from RetryOutputParser in that this implementation provides the error that was raised back to the LLM, which in theory should give it more information on how to fix it. """ parser: BaseOutputParser[T] retry_chain: LLMChain [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, parser: BaseOutputParser[T], prompt: BasePromptTemplate = NAIVE_RETRY_WITH_ERROR_PROMPT, ) -> RetryWithErrorOutputParser[T]:
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html
5d50b5bfdcbb-2
) -> RetryWithErrorOutputParser[T]: chain = LLMChain(llm=llm, prompt=prompt) return cls(parser=parser, retry_chain=chain) [docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T: try: parsed_completion = self.parser.parse(completion) except OutputParserException as e: new_completion = self.retry_chain.run( prompt=prompt_value.to_string(), completion=completion, error=repr(e) ) parsed_completion = self.parser.parse(new_completion) return parsed_completion [docs] def parse(self, completion: str) -> T: raise NotImplementedError( "This OutputParser can only be called by the `parse_with_prompt` method." ) [docs] def get_format_instructions(self) -> str: return self.parser.get_format_instructions() @property def _type(self) -> str: return "retry_with_error"
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html
f8af651048fa-0
Source code for langchain.output_parsers.regex_dict from __future__ import annotations import re from typing import Dict, Optional from langchain.schema import BaseOutputParser [docs]class RegexDictParser(BaseOutputParser): """Class to parse the output into a dictionary.""" regex_pattern: str = r"{}:\s?([^.'\n']*)\.?" # : :meta private: output_key_to_format: Dict[str, str] no_update_value: Optional[str] = None @property def _type(self) -> str: """Return the type key.""" return "regex_dict_parser" [docs] def parse(self, text: str) -> Dict[str, str]: """Parse the output of an LLM call.""" result = {} for output_key, expected_format in self.output_key_to_format.items(): specific_regex = self.regex_pattern.format(re.escape(expected_format)) matches = re.findall(specific_regex, text) if not matches: raise ValueError( f"No match found for output key: {output_key} with expected format \ {expected_format} on text {text}" ) elif len(matches) > 1: raise ValueError( f"Multiple matches found for output key: {output_key} with \ expected format {expected_format} on text {text}" ) elif ( self.no_update_value is not None and matches[0] == self.no_update_value ): continue else: result[output_key] = matches[0] return result
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html
f946aa55c271-0
Source code for langchain.output_parsers.enum from enum import Enum from typing import Any, Dict, List, Type from pydantic import root_validator from langchain.schema import BaseOutputParser, OutputParserException [docs]class EnumOutputParser(BaseOutputParser): enum: Type[Enum] [docs] @root_validator() def raise_deprecation(cls, values: Dict) -> Dict: enum = values["enum"] if not all(isinstance(e.value, str) for e in enum): raise ValueError("Enum values must be strings") return values @property def _valid_values(self) -> List[str]: return [e.value for e in self.enum] [docs] def parse(self, response: str) -> Any: try: return self.enum(response.strip()) except ValueError: raise OutputParserException( f"Response '{response}' is not one of the " f"expected values: {self._valid_values}" ) [docs] def get_format_instructions(self) -> str: return f"Select one of the following options: {', '.join(self._valid_values)}"
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/enum.html
c24c09d526ff-0
Source code for langchain.output_parsers.openai_functions import json from typing import Any, List from langchain.schema import BaseLLMOutputParser, ChatGeneration, Generation [docs]class OutputFunctionsParser(BaseLLMOutputParser[Any]): args_only: bool = True [docs] def parse_result(self, result: List[Generation]) -> Any: generation = result[0] if not isinstance(generation, ChatGeneration): raise ValueError( "This output parser can only be used with a chat generation." ) message = generation.message try: func_call = message.additional_kwargs["function_call"] except ValueError as exc: raise ValueError(f"Could not parse function call: {exc}") if self.args_only: return func_call["arguments"] return func_call [docs]class JsonOutputFunctionsParser(OutputFunctionsParser): [docs] def parse_result(self, result: List[Generation]) -> Any: func = super().parse_result(result) if self.args_only: return json.loads(func) func["arguments"] = json.loads(func["arguments"]) return func [docs]class JsonKeyOutputFunctionsParser(JsonOutputFunctionsParser): key_name: str [docs] def parse_result(self, result: List[Generation]) -> Any: res = super().parse_result(result) return res[self.key_name] [docs]class PydanticOutputFunctionsParser(OutputFunctionsParser): pydantic_schema: Any [docs] def parse_result(self, result: List[Generation]) -> Any: _args = super().parse_result(result) pydantic_args = self.pydantic_schema.parse_raw(_args) return pydantic_args
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html
c24c09d526ff-1
return pydantic_args [docs]class PydanticAttrOutputFunctionsParser(PydanticOutputFunctionsParser): attr_name: str [docs] def parse_result(self, result: List[Generation]) -> Any: result = super().parse_result(result) return getattr(result, self.attr_name)
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html
f6cd49ab50c4-0
Source code for langchain.output_parsers.structured from __future__ import annotations from typing import Any, List from pydantic import BaseModel from langchain.output_parsers.format_instructions import STRUCTURED_FORMAT_INSTRUCTIONS from langchain.output_parsers.json import parse_and_check_json_markdown from langchain.schema import BaseOutputParser line_template = '\t"{name}": {type} // {description}' [docs]class ResponseSchema(BaseModel): name: str description: str type: str = "string" def _get_sub_string(schema: ResponseSchema) -> str: return line_template.format( name=schema.name, description=schema.description, type=schema.type ) [docs]class StructuredOutputParser(BaseOutputParser): response_schemas: List[ResponseSchema] [docs] @classmethod def from_response_schemas( cls, response_schemas: List[ResponseSchema] ) -> StructuredOutputParser: return cls(response_schemas=response_schemas) [docs] def get_format_instructions(self) -> str: schema_str = "\n".join( [_get_sub_string(schema) for schema in self.response_schemas] ) return STRUCTURED_FORMAT_INSTRUCTIONS.format(format=schema_str) [docs] def parse(self, text: str) -> Any: expected_keys = [rs.name for rs in self.response_schemas] return parse_and_check_json_markdown(text, expected_keys) @property def _type(self) -> str: return "structured"
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html
1196e8a21ace-0
Source code for langchain.output_parsers.boolean from langchain.schema import BaseOutputParser [docs]class BooleanOutputParser(BaseOutputParser[bool]): true_val: str = "YES" false_val: str = "NO" [docs] def parse(self, text: str) -> bool: """Parse the output of an LLM call to a boolean. Args: text: output of language model Returns: boolean """ cleaned_text = text.strip() if cleaned_text.upper() not in (self.true_val.upper(), self.false_val.upper()): raise ValueError( f"BooleanOutputParser expected output value to either be " f"{self.true_val} or {self.false_val}. Received {cleaned_text}." ) return cleaned_text.upper() == self.true_val.upper() @property def _type(self) -> str: """Snake-case string identifier for output parser type.""" return "boolean_output_parser"
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/boolean.html
26a99ebbc90f-0
Source code for langchain.output_parsers.fix from __future__ import annotations from typing import TypeVar from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.output_parsers.prompts import NAIVE_FIX_PROMPT from langchain.prompts.base import BasePromptTemplate from langchain.schema import BaseOutputParser, OutputParserException T = TypeVar("T") [docs]class OutputFixingParser(BaseOutputParser[T]): """Wraps a parser and tries to fix parsing errors.""" parser: BaseOutputParser[T] retry_chain: LLMChain [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, parser: BaseOutputParser[T], prompt: BasePromptTemplate = NAIVE_FIX_PROMPT, ) -> OutputFixingParser[T]: chain = LLMChain(llm=llm, prompt=prompt) return cls(parser=parser, retry_chain=chain) [docs] def parse(self, completion: str) -> T: try: parsed_completion = self.parser.parse(completion) except OutputParserException as e: new_completion = self.retry_chain.run( instructions=self.parser.get_format_instructions(), completion=completion, error=repr(e), ) parsed_completion = self.parser.parse(new_completion) return parsed_completion [docs] def get_format_instructions(self) -> str: return self.parser.get_format_instructions() @property def _type(self) -> str: return "output_fixing"
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html
48ac0df5d07a-0
Source code for langchain.output_parsers.regex from __future__ import annotations import re from typing import Dict, List, Optional from langchain.schema import BaseOutputParser [docs]class RegexParser(BaseOutputParser): """Class to parse the output into a dictionary.""" regex: str output_keys: List[str] default_output_key: Optional[str] = None @property def _type(self) -> str: """Return the type key.""" return "regex_parser" [docs] def parse(self, text: str) -> Dict[str, str]: """Parse the output of an LLM call.""" match = re.search(self.regex, text) if match: return {key: match.group(i + 1) for i, key in enumerate(self.output_keys)} else: if self.default_output_key is None: raise ValueError(f"Could not parse output: {text}") else: return { key: text if key == self.default_output_key else "" for key in self.output_keys }
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/regex.html
27c506f26eb3-0
Source code for langchain.output_parsers.loading from langchain.output_parsers.regex import RegexParser [docs]def load_output_parser(config: dict) -> dict: """Load output parser.""" if "output_parsers" in config: if config["output_parsers"] is not None: _config = config["output_parsers"] output_parser_type = _config["_type"] if output_parser_type == "regex_parser": output_parser = RegexParser(**_config) else: raise ValueError(f"Unsupported output parser {output_parser_type}") config["output_parsers"] = output_parser return config
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/loading.html