id
stringlengths
14
16
text
stringlengths
4
1.28k
source
stringlengths
54
121
6b8a3e42080e-3
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 = Sea...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-4
# 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 Configur...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-5
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 fr...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-6
"""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) -> ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-7
``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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-8
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[...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-9
return v @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.g...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-10
! 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 class Config: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-11
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 aioht...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-12
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.te...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-13
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...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-14
# 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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-15
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 go...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-16
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(en...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-17
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 re...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-18
{ 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 = { ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-19
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 [ { ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-20
**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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6b8a3e42080e-21
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"], "ca...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
2afdd281f292-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
2afdd281f292-1
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}" ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html
2afdd281f292-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
d64b83149afd-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
d64b83149afd-1
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_re...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/brave_search.html
525ac6fc5066-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
525ac6fc5066-1
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_PR...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
525ac6fc5066-2
"description": JIRA_CONFLUENCE_PAGE_CREATE_PROMPT, }, ] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] def list(self) -> List[Dict]: return self.operations @root_validator() def validate_environment(cls, values: Dict) -> Dict: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
525ac6fc5066-3
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
525ac6fc5066-4
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"]...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
525ac6fc5066-5
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_ke...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
525ac6fc5066-6
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: st...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
525ac6fc5066-7
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( ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
525ac6fc5066-8
[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...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html
1b0464732351-0
Source code for langchain.utilities.spark_sql from __future__ import annotations from typing import TYPE_CHECKING, Any, Iterable, List, Optional if TYPE_CHECKING: from pyspark.sql import DataFrame, Row, SparkSession [docs]class SparkSQL: def __init__( self, spark_session: Optional[SparkSession] ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
1b0464732351-1
) self._spark = ( spark_session if spark_session else SparkSession.builder.getOrCreate() ) if catalog is not None: self._spark.catalog.setCurrentCatalog(catalog) if schema is not None: self._spark.catalog.setCurrentDatabase(schema) self._all_ta...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
1b0464732351-2
raise ValueError( f"ignore_tables {missing_tables} not found in database" ) usable_tables = self.get_usable_table_names() self._usable_tables = set(usable_tables) if usable_tables else self._all_tables if not isinstance(sample_rows_in_table_info, int): ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
1b0464732351-3
except ImportError: raise ValueError( "pyspark is not installed. Please install it with `pip install pyspark`" ) spark = SparkSession.builder.remote(database_uri).getOrCreate() return cls(spark, **kwargs) [docs] def get_usable_table_names(self) -> Iterable[str]...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
1b0464732351-4
statement = ( self._spark.sql(f"SHOW CREATE TABLE {table}").collect()[0].createtab_stmt ) # Ignore the data source provider and options to reduce the number of tokens. using_clause_index = statement.find("USING") return statement[:using_clause_index] + ";" [docs] def get_t...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
1b0464732351-5
if self._sample_rows_in_table_info: table_info += "\n\n/*" table_info += f"\n{self._get_sample_spark_rows(table_name)}\n" table_info += "*/" tables.append(table_info) final_str = "\n\n".join(tables) return final_str def _get_sample_spark_ro...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
1b0464732351-6
except Exception: sample_rows_str = "" return ( f"{self._sample_rows_in_table_info} rows from {table} table:\n" f"{columns_str}\n" f"{sample_rows_str}" ) def _convert_row_as_tuple(self, row: Row) -> tuple: return tuple(map(str, row.asDict().val...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
1b0464732351-7
[docs] def get_table_info_no_throw(self, table_names: Optional[List[str]] = None) -> str: """Get information about specified tables. Follows best practices as specified in: Rajkumar et al, 2022 (https://arxiv.org/abs/2204.00498) If `sample_rows_in_table_info`, the specified number of ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
1b0464732351-8
If the statement returns rows, a string of the results is returned. If the statement returns no rows, an empty string is returned. If the statement throws an error, the error message is returned. """ try: from pyspark.errors import PySparkException except ImportError:...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html
45d20154fa3c-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
45d20154fa3c-1
load_all_available_meta: bool = False doc_content_chars_max: int = 4000 class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environmen...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
45d20154fa3c-2
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
45d20154fa3c-3
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.reference...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
45d20154fa3c-4
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
5029ad25d731-0
Source code for langchain.utilities.apify from typing import Any, Callable, Dict, Optional from pydantic import BaseModel, root_validator from langchain.document_loaders import ApifyDatasetLoader from langchain.document_loaders.base import Document from langchain.utils import get_from_dict_or_env [docs]class ApifyWrapp...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
5029ad25d731-1
Python package exists in the current environment. """ apify_api_token = get_from_dict_or_env( values, "apify_api_token", "APIFY_API_TOKEN" ) try: from apify_client import ApifyClient, ApifyClientAsync values["apify_client"] = ApifyClient(apify_api_toke...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
5029ad25d731-2
build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None, ) -> ApifyDatasetLoader: """Run an Actor on the Apify platform and wait for results to be ready. Args: actor_id (str): The ID or name of the Actor on the Apify platform. ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
5029ad25d731-3
in megabytes. timeout_secs (int, optional): Optional timeout for the run, in seconds. Returns: ApifyDatasetLoader: A loader that will fetch the records from the Actor run's default dataset. """ actor_call = self.apify_client.actor(actor_id).call( ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
5029ad25d731-4
build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None, ) -> ApifyDatasetLoader: """Run an Actor on the Apify platform and wait for results to be ready. Args: actor_id (str): The ID or name of the Actor on the Apify platform. ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
5029ad25d731-5
in megabytes. timeout_secs (int, optional): Optional timeout for the run, in seconds. Returns: ApifyDatasetLoader: A loader that will fetch the records from the Actor run's default dataset. """ actor_call = await self.apify_client_async.actor(actor_id).cal...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
fe09f456f229-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
fe09f456f229-1
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
fe09f456f229-2
""" 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 = [...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
fe09f456f229-3
[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.qu...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
fe09f456f229-4
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
fe09f456f229-5
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"wai...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
fe09f456f229-6
] # 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)...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
fe09f456f229-7
"summary": abstract, "pub_date": pub_date, } return article
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html
2bfbe53a229d-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
2bfbe53a229d-1
@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-se...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
2bfbe53a229d-2
) 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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
2bfbe53a229d-3
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, ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html
2bfbe53a229d-4
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
1cd1b477b756-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
1cd1b477b756-1
@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 m...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1cd1b477b756-2
return path_item @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...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1cd1b477b756-3
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. ") ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1cd1b477b756-4
"""Get the root reference or err.""" 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 sc...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1cd1b477b756-5
"""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, RequestBo...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1cd1b477b756-6
request_body = self._get_referenced_request_body(ref) 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 suppor...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1cd1b477b756-7
) 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1cd1b477b756-8
keys = error["loc"] item = new_obj 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...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1cd1b477b756-9
[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(...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1cd1b477b756-10
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 = [] for method in HTTPVerb: operation = getattr(path_item, method.value, ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1cd1b477b756-11
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
1cd1b477b756-12
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 [d...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html
c00e8ea1e57b-0
Source code for langchain.utilities.zapier """Util that can interact with Zapier NLA. Full docs here: https://nla.zapier.com/api/v1/docs Note: this wrapper currently only implemented the `api_key` auth method for testing and server-side production use cases (using the developer's connected accounts on Zapier.com) For u...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
c00e8ea1e57b-1
[docs]class ZapierNLAWrapper(BaseModel): """Wrapper for Zapier NLA. Full docs here: https://nla.zapier.com/api/v1/docs Note: this wrapper currently only implemented the `api_key` auth method for testingand server-side production use cases (using the developer's connected accounts on Zapier.com) ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
c00e8ea1e57b-2
class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def _get_session(self) -> Session: session = requests.Session() session.headers.update( { "Accept": "application/json", "Content-Type": "application/json", ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
c00e8ea1e57b-3
data.update( { "instructions": instructions, } ) return Request( "POST", self.zapier_nla_api_base + f"exposed/{action_id}/execute/", json=data, ) @root_validator(pre=True) def validate_environment(cls, values: Di...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
c00e8ea1e57b-4
# we require at least one API Key zapier_nla_api_key = get_from_dict_or_env( values, "zapier_nla_api_key", "ZAPIER_NLA_API_KEY", zapier_nla_api_key_default, ) values["zapier_nla_api_key"] = zapier_nla_api_key return values [docs] def lis...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
c00e8ea1e57b-5
}] `params` will always contain an `instructions` key, the only required param. All others optional and if provided will override any AI guesses (see "understanding the AI guessing flow" here: https://nla.zapier.com/api/v1/docs) """ session = self._get_session() r...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
c00e8ea1e57b-6
The return JSON is guaranteed to be less than ~500 words (350 tokens) making it safe to inject into the prompt of another LLM call. """ session = self._get_session() request = self._get_action_request(action_id, instructions, params) response = session.send(session.prepar...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
c00e8ea1e57b-7
params.update({"preview_only": True}) request = self._get_action_request(action_id, instructions, params) response = session.send(session.prepare_request(request)) response.raise_for_status() return response.json()["input_params"] [docs] def run_as_str(self, *args, **kwargs) -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
c00e8ea1e57b-8
return json.dumps(data) [docs] def list_as_str(self) -> str: # type: ignore[no-untyped-def] """Same as list, but returns a stringified version of the JSON for insertting back into an LLM.""" actions = self.list() return json.dumps(actions)
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html
fd20b1fd5412-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
fd20b1fd5412-1
- 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/desc...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html
fd20b1fd5412-2
} ] } 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 v...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html
fd20b1fd5412-3
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
d6403b19c952-0
Source code for langchain.utilities.wolfram_alpha """Util that calls WolframAlpha.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class WolframAlphaAPIWrapper(BaseModel): """Wrapper for Wolfram Alpha. Docs fo...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
d6403b19c952-1
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" wolfram_alpha_appid = get_from_dict_or_env( values, "wolfram_alpha_appid", "WOLFRAM_ALPHA_APPID" ) values["wolfram_alpha_appid"] = ...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
d6403b19c952-2
res = self.wolfram_client.query(query) try: assumption = next(res.pods).text answer = next(res.results).text except StopIteration: return "Wolfram Alpha wasn't able to answer it" if answer is None or answer == "": # We don't want to return the assu...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
01c3490947ed-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
01c3490947ed-1
""" 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", "p...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
01c3490947ed-2
@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 [d...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
01c3490947ed-3
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, **...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
01c3490947ed-4
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, resu...
https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html