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_ta...
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: st...
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"...
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: ...
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 lambd...
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: retu...
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): """ Wrappe...
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...
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") ...
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>" ...
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. ...
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.googl...
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"...
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(BaseMode...
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}...
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) an...
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] ...
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_dic...
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.""" ser...
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.serpap...
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() ): tor...
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 w...
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 arou...
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 tha...
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}\nAddre...
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 ...
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"] ...
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, ) r...
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: heade...
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): """Wra...
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["...
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 me...
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 = { "Pu...
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", ...
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]...
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 Wikiped...
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 Wik...
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 ...
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 hav...
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`, th...
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 chann...
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_...
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.oper...
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"] ...
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, ...
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) -> ...
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...
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]]: ...
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.""" ...
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 res...
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...
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, pat...
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 kin...
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 DuckDuckGoSe...
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(...
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: ...
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:/...
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...
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:g...
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 = ...
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", ...
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 ht...
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( ...
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 = { ...
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) an...
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. ...
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 i...
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...
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(f...
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_d...
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"] [do...
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_publis...
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"]) ...
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: O...
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...
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(...
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.""" ...
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_...
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(...
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...
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 lang...
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_completio...
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 Outp...
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'...
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 r...
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...
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 langchai...
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:...
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 f...
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] ...
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"] ...
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/loading.html