Utilities
General utilities.
class langchain.utilities.ApifyWrapper(*, apify_client=None, apify_client_async=None)[source]
Bases: pydantic.main.BaseModel
Wrapper around Apify.
To use, you should have the apify-client python package installed,
and the environment variable APIFY_API_TOKEN set with your API key, or pass
apify_api_token as a named parameter to the constructor.
Parameters
apify_client (Any) – 
apify_client_async (Any) – 
Return type
None
attribute apify_client: Any = None
attribute apify_client_async: Any = None
async acall_actor(actor_id, run_input, dataset_mapping_function, *, build=None, memory_mbytes=None, timeout_secs=None)[source]
Run an Actor on the Apify platform and wait for results to be ready.
Parameters
actor_id (str) – The ID or name of the Actor on the Apify platform.
run_input (Dict) – The input object of the Actor that you’re trying to run.
dataset_mapping_function (Callable) – A function that takes a single
dictionary (an Apify dataset item) and converts it to
an instance of the Document class.
build (str, optional) – Optionally specifies the actor build to run.
It can be either a build tag or build number.
memory_mbytes (int, optional) – Optional memory limit for the run,
in megabytes.
timeout_secs (int, optional) – Optional timeout for the run, in seconds.
Returns
A loader that will fetch the records from theActor run’s default dataset.
Return type
ApifyDatasetLoader
call_actor(actor_id, run_input, dataset_mapping_function, *, build=None, memory_mbytes=None, timeout_secs=None)[source]
Run an Actor on the Apify platform and wait for results to be ready.
Parameters
actor_id (str) – The ID or name of the Actor on the Apify platform.
run_input (Dict) – The input object of the Actor that you’re trying to run.
dataset_mapping_function (Callable) – A function that takes a single
dictionary (an Apify dataset item) and converts it to an
instance of the Document class.
build (str, optional) – Optionally specifies the actor build to run.
It can be either a build tag or build number.
memory_mbytes (int, optional) – Optional memory limit for the run,
in megabytes.
timeout_secs (int, optional) – Optional timeout for the run, in seconds.
Returns
A loader that will fetch the records from theActor run’s default dataset.
Return type
ApifyDatasetLoader
class langchain.utilities.ArxivAPIWrapper(*, arxiv_search=None, arxiv_exceptions=None, top_k_results=3, load_max_docs=100, load_all_available_meta=False, doc_content_chars_max=4000, ARXIV_MAX_QUERY_LENGTH=300)[source]
Bases: pydantic.main.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 (int) – number of the top-scored document used for the arxiv tool
ARXIV_MAX_QUERY_LENGTH (int) – the cut limit on the query used for the arxiv tool.
load_max_docs (int) – a limit to the number of loaded documents
load_all_available_meta (bool) – 
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) – 
arxiv_exceptions (Any) – 
doc_content_chars_max (Optional[int]) – 
Return type
None
attribute arxiv_exceptions: Any = None
attribute doc_content_chars_max: Optional[int] = 4000
attribute load_all_available_meta: bool = False
attribute load_max_docs: int = 100
attribute top_k_results: int = 3
load(query)[source]
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
Parameters
query (str) – 
Return type
List[langchain.schema.Document]
run(query)[source]
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.
Parameters
query (str) – 
Return type
str
class langchain.utilities.BashProcess(strip_newlines=False, return_err_output=False, persistent=False)[source]
Bases: object
Executes bash commands and returns the output.
Parameters
strip_newlines (bool) – 
return_err_output (bool) – 
persistent (bool) – 
run(commands)[source]
Run commands and return final output.
Parameters
commands (Union[str, List[str]]) – 
Return type
str
process_output(output, command)[source]
Parameters
output (str) – 
command (str) – 
Return type
str
class langchain.utilities.BibtexparserWrapper[source]
Bases: pydantic.main.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.
Return type
None
get_metadata(entry, load_extra=False)[source]
Get metadata for the given entry.
Parameters
entry (Mapping[str, Any]) – 
load_extra (bool) – 
Return type
Dict[str, Any]
load_bibtex_entries(path)[source]
Load bibtex entries from the bibtex file at the given path.
Parameters
path (str) – 
Return type
List[Dict[str, Any]]
class langchain.utilities.BingSearchAPIWrapper(*, bing_subscription_key, bing_search_url, k=10)[source]
Bases: pydantic.main.BaseModel
Wrapper for Bing Search API.
In order to set this up, follow instructions at:
https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e
Parameters
bing_subscription_key (str) – 
bing_search_url (str) – 
k (int) – 
Return type
None
attribute bing_search_url: str [Required]
attribute bing_subscription_key: str [Required]
attribute k: int = 10
results(query, num_results)[source]
Run query through BingSearch and return metadata.
Parameters
query (str) – The query to search for.
num_results (int) – The number of results to return.
Returns
snippet - The description of the result.
title - The title of the result.
link - The link to the result.
Return type
A list of dictionaries with the following keys
run(query)[source]
Run query through BingSearch and parse result.
Parameters
query (str) – 
Return type
str
class langchain.utilities.BraveSearchWrapper(*, api_key, search_kwargs=None)[source]
Bases: pydantic.main.BaseModel
Parameters
api_key (str) – 
search_kwargs (dict) – 
Return type
None
attribute api_key: str [Required]
attribute search_kwargs: dict [Optional]
run(query)[source]
Parameters
query (str) – 
Return type
str
class langchain.utilities.DuckDuckGoSearchAPIWrapper(*, k=10, region='wt-wt', safesearch='moderate', time='y', max_results=5)[source]
Bases: pydantic.main.BaseModel
Wrapper for DuckDuckGo Search API.
Free and does not require any setup
Parameters
k (int) – 
region (Optional[str]) – 
safesearch (str) – 
time (Optional[str]) – 
max_results (int) – 
Return type
None
attribute k: int = 10
attribute max_results: int = 5
attribute region: Optional[str] = 'wt-wt'
attribute safesearch: str = 'moderate'
attribute time: Optional[str] = 'y'
get_snippets(query)[source]
Run query through DuckDuckGo and return concatenated results.
Parameters
query (str) – 
Return type
List[str]
results(query, num_results)[source]
Run query through DuckDuckGo and return metadata.
Parameters
query (str) – The query to search for.
num_results (int) – The number of results to return.
Returns
snippet - The description of the result.
title - The title of the result.
link - The link to the result.
Return type
A list of dictionaries with the following keys
run(query)[source]
Parameters
query (str) – 
Return type
str
class langchain.utilities.GooglePlacesAPIWrapper(*, gplaces_api_key=None, google_map_client=None, top_k_results=None)[source]
Bases: pydantic.main.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
from langchain import GooglePlacesAPIWrapper
gplaceapi = GooglePlacesAPIWrapper()
Parameters
gplaces_api_key (Optional[str]) – 
google_map_client (Any) – 
top_k_results (Optional[int]) – 
Return type
None
attribute gplaces_api_key: Optional[str] = None
attribute top_k_results: Optional[int] = None
fetch_place_details(place_id)[source]
Parameters
place_id (str) – 
Return type
Optional[str]
format_place_details(place_details)[source]
Parameters
place_details (Dict[str, Any]) – 
Return type
Optional[str]
run(query)[source]
Run Places search and get k number of places that exists that match.
Parameters
query (str) – 
Return type
str
class langchain.utilities.GoogleSearchAPIWrapper(*, search_engine=None, google_api_key=None, google_cse_id=None, k=10, siterestrict=False)[source]
Bases: pydantic.main.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.
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
Parameters
search_engine (Any) – 
google_api_key (Optional[str]) – 
google_cse_id (Optional[str]) – 
k (int) – 
siterestrict (bool) – 
Return type
None
attribute google_api_key: Optional[str] = None
attribute google_cse_id: Optional[str] = None
attribute k: int = 10
attribute siterestrict: bool = False
results(query, num_results)[source]
Run query through GoogleSearch and return metadata.
Parameters
query (str) – The query to search for.
num_results (int) – The number of results to return.
Returns
snippet - The description of the result.
title - The title of the result.
link - The link to the result.
Return type
A list of dictionaries with the following keys
run(query)[source]
Run query through GoogleSearch and parse result.
Parameters
query (str) – 
Return type
str
class langchain.utilities.GoogleSerperAPIWrapper(*, k=10, gl='us', hl='en', type='search', tbs=None, serper_api_key=None, aiosession=None, result_key_for_type={'images': 'images', 'news': 'news', 'places': 'places', 'search': 'organic'})[source]
Bases: pydantic.main.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
from langchain import GoogleSerperAPIWrapper
google_serper = GoogleSerperAPIWrapper()
Parameters
k (int) – 
gl (str) – 
hl (str) – 
type (Literal['news', 'search', 'places', 'images']) – 
tbs (Optional[str]) – 
serper_api_key (Optional[str]) – 
aiosession (Optional[aiohttp.client.ClientSession]) – 
result_key_for_type (dict) – 
Return type
None
attribute aiosession: Optional[aiohttp.client.ClientSession] = None
attribute gl: str = 'us'
attribute hl: str = 'en'
attribute k: int = 10
attribute serper_api_key: Optional[str] = None
attribute tbs: Optional[str] = None
attribute type: Literal['news', 'search', 'places', 'images'] = 'search'
async aresults(query, **kwargs)[source]
Run query through GoogleSearch.
Parameters
query (str) – 
kwargs (Any) – 
Return type
Dict
async arun(query, **kwargs)[source]
Run query through GoogleSearch and parse result async.
Parameters
query (str) – 
kwargs (Any) – 
Return type
str
results(query, **kwargs)[source]
Run query through GoogleSearch.
Parameters
query (str) – 
kwargs (Any) – 
Return type
Dict
run(query, **kwargs)[source]
Run query through GoogleSearch and parse result.
Parameters
query (str) – 
kwargs (Any) – 
Return type
str
class langchain.utilities.GraphQLAPIWrapper(*, custom_headers=None, graphql_endpoint, gql_client=None, gql_function)[source]
Bases: pydantic.main.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.
Parameters
custom_headers (Optional[Dict[str, str]]) – 
graphql_endpoint (str) – 
gql_client (Any) – 
gql_function (Callable[[str], Any]) – 
Return type
None
attribute custom_headers: Optional[Dict[str, str]] = None
attribute graphql_endpoint: str [Required]
run(query)[source]
Run a GraphQL query and get the results.
Parameters
query (str) – 
Return type
str
class langchain.utilities.JiraAPIWrapper(*, jira=None, confluence=None, jira_username=None, jira_api_token=None, jira_instance_url=None, operations=[{'mode': 'jql', 'name': 'JQL Query', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira jql API, useful when you need to search for Jira issues.\n    The input to this tool is a JQL query string, and will be passed into atlassian-python-api\'s Jira `jql` function,\n    For example, to find all the issues in project "Test" assigned to the me, you would pass in the following string:\n    project = Test AND assignee = currentUser()\n    or to find issues with summaries that contain the word "test", you would pass in the following string:\n    summary ~ \'test\'\n    '}, {'mode': 'get_projects', 'name': 'Get Projects', 'description': "\n    This tool is a wrapper around atlassian-python-api's Jira project API, \n    useful when you need to fetch all the projects the user has access to, find out how many projects there are, or as an intermediary step that involv searching by projects. \n    there is no input to this tool.\n    "}, {'mode': 'create_issue', 'name': 'Create Issue', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira issue_create API, useful when you need to create a Jira issue. \n    The input to this tool is a dictionary specifying the fields of the Jira issue, and will be passed into atlassian-python-api\'s Jira `issue_create` function.\n    For example, to create a low priority task called "test issue" with description "test description", you would pass in the following dictionary: \n    {{"summary": "test issue", "description": "test description", "issuetype": {{"name": "Task"}}, "priority": {{"name": "Low"}}}}\n    '}, {'mode': 'other', 'name': 'Catch all Jira API call', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira API.\n    There are other dedicated tools for fetching all projects, and creating and searching for issues, \n    use this tool if you need to perform any other actions allowed by the atlassian-python-api Jira API.\n    The input to this tool is line of python code that calls a function from atlassian-python-api\'s Jira API\n    For example, to update the summary field of an issue, you would pass in the following string:\n    self.jira.update_issue_field(key, {{"summary": "New summary"}})\n    or to find out how many projects are in the Jira instance, you would pass in the following string:\n    self.jira.projects()\n    For more information on the Jira API, refer to https://atlassian-python-api.readthedocs.io/jira.html\n    '}, {'mode': 'create_page', 'name': 'Create confluence page', 'description': 'This tool is a wrapper around atlassian-python-api\'s Confluence \natlassian-python-api API, useful when you need to create a Confluence page. The input to this tool is a dictionary \nspecifying the fields of the Confluence page, and will be passed into atlassian-python-api\'s Confluence `create_page` \nfunction. For example, to create a page in the DEMO space titled "This is the title" with body "This is the body. You can use \n<strong>HTML tags</strong>!", you would pass in the following dictionary: {{"space": "DEMO", "title":"This is the \ntitle","body":"This is the body. You can use <strong>HTML tags</strong>!"}} '}])[source]
Bases: pydantic.main.BaseModel
Wrapper for Jira API.
Parameters
jira (Any) – 
confluence (Any) – 
jira_username (Optional[str]) – 
jira_api_token (Optional[str]) – 
jira_instance_url (Optional[str]) – 
operations (List[Dict]) – 
Return type
None
attribute confluence: Any = None
attribute jira_api_token: Optional[str] = None
attribute jira_instance_url: Optional[str] = None
attribute jira_username: Optional[str] = None
attribute operations: List[Dict] = [{'mode': 'jql', 'name': 'JQL Query', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira jql API, useful when you need to search for Jira issues.\n    The input to this tool is a JQL query string, and will be passed into atlassian-python-api\'s Jira `jql` function,\n    For example, to find all the issues in project "Test" assigned to the me, you would pass in the following string:\n    project = Test AND assignee = currentUser()\n    or to find issues with summaries that contain the word "test", you would pass in the following string:\n    summary ~ \'test\'\n    '}, {'mode': 'get_projects', 'name': 'Get Projects', 'description': "\n    This tool is a wrapper around atlassian-python-api's Jira project API, \n    useful when you need to fetch all the projects the user has access to, find out how many projects there are, or as an intermediary step that involv searching by projects. \n    there is no input to this tool.\n    "}, {'mode': 'create_issue', 'name': 'Create Issue', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira issue_create API, useful when you need to create a Jira issue. \n    The input to this tool is a dictionary specifying the fields of the Jira issue, and will be passed into atlassian-python-api\'s Jira `issue_create` function.\n    For example, to create a low priority task called "test issue" with description "test description", you would pass in the following dictionary: \n    {{"summary": "test issue", "description": "test description", "issuetype": {{"name": "Task"}}, "priority": {{"name": "Low"}}}}\n    '}, {'mode': 'other', 'name': 'Catch all Jira API call', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira API.\n    There are other dedicated tools for fetching all projects, and creating and searching for issues, \n    use this tool if you need to perform any other actions allowed by the atlassian-python-api Jira API.\n    The input to this tool is line of python code that calls a function from atlassian-python-api\'s Jira API\n    For example, to update the summary field of an issue, you would pass in the following string:\n    self.jira.update_issue_field(key, {{"summary": "New summary"}})\n    or to find out how many projects are in the Jira instance, you would pass in the following string:\n    self.jira.projects()\n    For more information on the Jira API, refer to https://atlassian-python-api.readthedocs.io/jira.html\n    '}, {'mode': 'create_page', 'name': 'Create confluence page', 'description': 'This tool is a wrapper around atlassian-python-api\'s Confluence \natlassian-python-api API, useful when you need to create a Confluence page. The input to this tool is a dictionary \nspecifying the fields of the Confluence page, and will be passed into atlassian-python-api\'s Confluence `create_page` \nfunction. For example, to create a page in the DEMO space titled "This is the title" with body "This is the body. You can use \n<strong>HTML tags</strong>!", you would pass in the following dictionary: {{"space": "DEMO", "title":"This is the \ntitle","body":"This is the body. You can use <strong>HTML tags</strong>!"}} '}]
issue_create(query)[source]
Parameters
query (str) – 
Return type
str
list()[source]
Return type
List[Dict]
other(query)[source]
Parameters
query (str) – 
Return type
str
page_create(query)[source]
Parameters
query (str) – 
Return type
str
parse_issues(issues)[source]
Parameters
issues (Dict) – 
Return type
List[dict]
parse_projects(projects)[source]
Parameters
projects (List[dict]) – 
Return type
List[dict]
project()[source]
Return type
str
run(mode, query)[source]
Parameters
mode (str) – 
query (str) – 
Return type
str
search(query)[source]
Parameters
query (str) – 
Return type
str
class langchain.utilities.LambdaWrapper(*, lambda_client=None, function_name=None, awslambda_tool_name=None, awslambda_tool_description=None)[source]
Bases: pydantic.main.BaseModel
Wrapper for AWS Lambda SDK.
Docs for using:
pip install boto3
Create a lambda function using the AWS Console or CLI
Run aws configure and enter your AWS credentials
Parameters
lambda_client (Any) – 
function_name (Optional[str]) – 
awslambda_tool_name (Optional[str]) – 
awslambda_tool_description (Optional[str]) – 
Return type
None
attribute awslambda_tool_description: Optional[str] = None
attribute awslambda_tool_name: Optional[str] = None
attribute function_name: Optional[str] = None
run(query)[source]
Invoke Lambda function and parse result.
Parameters
query (str) – 
Return type
str
class langchain.utilities.MaxComputeAPIWrapper(client)[source]
Bases: object
Interface for querying Alibaba Cloud MaxCompute tables.
Parameters
client (ODPS) – 
classmethod from_params(endpoint, project, *, access_id=None, secret_access_key=None)[source]
Convenience constructor that builds the odsp.ODPS MaxCompute client fromgiven parameters.
Parameters
endpoint (str) – MaxCompute endpoint.
project (str) – A project is a basic organizational unit of MaxCompute, which is
similar to a database.
access_id (Optional[str]) – MaxCompute access ID. Should be passed in directly or set as the
environment variable MAX_COMPUTE_ACCESS_ID.
secret_access_key (Optional[str]) – MaxCompute secret access key. Should be passed in
directly or set as the environment variable
MAX_COMPUTE_SECRET_ACCESS_KEY.
Return type
langchain.utilities.max_compute.MaxComputeAPIWrapper
lazy_query(query)[source]
Parameters
query (str) – 
Return type
Iterator[dict]
query(query)[source]
Parameters
query (str) – 
Return type
List[dict]
class langchain.utilities.MetaphorSearchAPIWrapper(*, metaphor_api_key, k=10)[source]
Bases: pydantic.main.BaseModel
Wrapper for Metaphor Search API.
Parameters
metaphor_api_key (str) – 
k (int) – 
Return type
None
attribute k: int = 10
attribute metaphor_api_key: str [Required]
results(query, num_results, include_domains=None, exclude_domains=None, start_crawl_date=None, end_crawl_date=None, start_published_date=None, end_published_date=None)[source]
Run query through Metaphor Search and return metadata.
Parameters
query (str) – The query to search for.
num_results (int) – The number of results to return.
include_domains (Optional[List[str]]) – 
exclude_domains (Optional[List[str]]) – 
start_crawl_date (Optional[str]) – 
end_crawl_date (Optional[str]) – 
start_published_date (Optional[str]) – 
end_published_date (Optional[str]) – 
Returns
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.
Return type
A list of dictionaries with the following keys
async results_async(query, num_results, include_domains=None, exclude_domains=None, start_crawl_date=None, end_crawl_date=None, start_published_date=None, end_published_date=None)[source]
Get results from the Metaphor Search API asynchronously.
Parameters
query (str) – 
num_results (int) – 
include_domains (Optional[List[str]]) – 
exclude_domains (Optional[List[str]]) – 
start_crawl_date (Optional[str]) – 
end_crawl_date (Optional[str]) – 
start_published_date (Optional[str]) – 
end_published_date (Optional[str]) – 
Return type
List[Dict]
class langchain.utilities.OpenWeatherMapAPIWrapper(*, owm=None, openweathermap_api_key=None)[source]
Bases: pydantic.main.BaseModel
Wrapper for OpenWeatherMap API using PyOWM.
Docs for using:
Go to OpenWeatherMap and sign up for an API key
Save your API KEY into OPENWEATHERMAP_API_KEY env variable
pip install pyowm
Parameters
owm (Any) – 
openweathermap_api_key (Optional[str]) – 
Return type
None
attribute openweathermap_api_key: Optional[str] = None
attribute owm: Any = None
run(location)[source]
Get the current weather information for a specified location.
Parameters
location (str) – 
Return type
str
class langchain.utilities.PowerBIDataset(*, dataset_id, table_names, group_id=None, credential=None, token=None, impersonated_user_name=None, sample_rows_in_table_info=1, schemas=None, aiosession=None)[source]
Bases: pydantic.main.BaseModel
Create PowerBI engine from dataset ID and credential or token.
Use either the credential or a supplied token to authenticate.
If both are supplied the credential is used to generate a token.
The impersonated_user_name is the UPN of a user to be impersonated.
If the model is not RLS enabled, this will be ignored.
Parameters
dataset_id (str) – 
table_names (List[str]) – 
group_id (Optional[str]) – 
credential (Optional[TokenCredential]) – 
token (Optional[str]) – 
impersonated_user_name (Optional[str]) – 
sample_rows_in_table_info (langchain.utilities.powerbi.ConstrainedIntValue) – 
schemas (Dict[str, str]) – 
aiosession (Optional[aiohttp.client.ClientSession]) – 
Return type
None
attribute aiosession: Optional[aiohttp.ClientSession] = None
attribute credential: Optional[TokenCredential] = None
attribute dataset_id: str [Required]
attribute group_id: Optional[str] = None
attribute impersonated_user_name: Optional[str] = None
attribute sample_rows_in_table_info: int = 1
Constraints
exclusiveMinimum = 0
maximum = 10
attribute schemas: Dict[str, str] [Optional]
attribute table_names: List[str] [Required]
attribute token: Optional[str] = None
async aget_table_info(table_names=None)[source]
Get information about specified tables.
Parameters
table_names (Optional[Union[List[str], str]]) – 
Return type
str
async arun(command)[source]
Execute a DAX command and return the result asynchronously.
Parameters
command (str) – 
Return type
Any
get_schemas()[source]
Get the available schema’s.
Return type
str
get_table_info(table_names=None)[source]
Get information about specified tables.
Parameters
table_names (Optional[Union[List[str], str]]) – 
Return type
str
get_table_names()[source]
Get names of tables available.
Return type
Iterable[str]
run(command)[source]
Execute a DAX command and return a json representing the results.
Parameters
command (str) – 
Return type
Any
property headers: Dict[str, str]
Get the token.
property request_url: str
Get the request url.
property table_info: str
Information about all tables in the database.
class langchain.utilities.PubMedAPIWrapper(*, top_k_results=3, load_max_docs=25, doc_content_chars_max=2000, load_all_available_meta=False, email='your_email@example.com', 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, ARXIV_MAX_QUERY_LENGTH=300)[source]
Bases: pydantic.main.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 (int) – number of the top-scored document used for the PubMed tool
load_max_docs (int) – a limit to the number of loaded documents
load_all_available_meta (bool) – 
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.
doc_content_chars_max (int) – 
email (str) – 
base_url_esearch (str) – 
base_url_efetch (str) – 
max_retry (int) – 
sleep_time (float) – 
ARXIV_MAX_QUERY_LENGTH (int) – 
Return type
None
attribute doc_content_chars_max: int = 2000
attribute email: str = 'your_email@example.com'
attribute load_all_available_meta: bool = False
attribute load_max_docs: int = 25
attribute top_k_results: int = 3
load(query)[source]
Search PubMed for documents matching the query.
Return a list of dictionaries containing the document metadata.
Parameters
query (str) – 
Return type
List[dict]
load_docs(query)[source]
Parameters
query (str) – 
Return type
List[langchain.schema.Document]
retrieve_article(uid, webenv)[source]
Parameters
uid (str) – 
webenv (str) – 
Return type
dict
run(query)[source]
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.
Parameters
query (str) – 
Return type
str
class langchain.utilities.PythonREPL(*, _globals=None, _locals=None)[source]
Bases: pydantic.main.BaseModel
Simulates a standalone Python REPL.
Parameters
_globals (Optional[Dict]) – 
_locals (Optional[Dict]) – 
Return type
None
attribute globals: Optional[Dict] [Optional] (alias '_globals')
attribute locals: Optional[Dict] [Optional] (alias '_locals')
run(command)[source]
Run command with own globals/locals and returns anything printed.
Parameters
command (str) – 
Return type
str
pydantic settings langchain.utilities.SceneXplainAPIWrapper[source]
Bases: pydantic.env_settings.BaseSettings, pydantic.main.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.
Show JSON schema{
   "title": "SceneXplainAPIWrapper",
   "description": "Wrapper for SceneXplain API.\n\nIn order to set this up, you need API key for the SceneXplain API.\nYou can obtain a key by following the steps below.\n- Sign up for a free account at https://scenex.jina.ai/.\n- Navigate to the API Access page (https://scenex.jina.ai/api)\n  and create a new API key.",
   "type": "object",
   "properties": {
      "scenex_api_key": {
         "title": "Scenex Api Key",
         "env": "SCENEX_API_KEY",
         "env_names": "{'scenex_api_key'}",
         "type": "string"
      },
      "scenex_api_url": {
         "title": "Scenex Api Url",
         "default": "https://us-central1-causal-diffusion.cloudfunctions.net/describe",
         "env_names": "{'scenex_api_url'}",
         "type": "string"
      }
   },
   "required": [
      "scenex_api_key"
   ],
   "additionalProperties": false
}
Fields
scenex_api_key (str)
scenex_api_url (str)
attribute scenex_api_key: str [Required]
attribute scenex_api_url: str = 'https://us-central1-causal-diffusion.cloudfunctions.net/describe'
run(image)[source]
Run SceneXplain image explainer.
Parameters
image (str) – 
Return type
str
validator validate_environment  »  all fields[source]
Validate that api key exists in environment.
Parameters
values (Dict) – 
Return type
Dict
class langchain.utilities.SearxSearchWrapper(*, searx_host='', unsecure=False, params=None, headers=None, engines=[], categories=[], query_suffix='', k=10, aiosession=None)[source]
Bases: pydantic.main.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
from langchain.utilities import SearxSearchWrapper
searx = SearxSearchWrapper(searx_host="http://localhost:8888")
Example with SSL disabled: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)
Parameters
searx_host (str) – 
unsecure (bool) – 
params (dict) – 
headers (Optional[dict]) – 
engines (Optional[List[str]]) – 
categories (Optional[List[str]]) – 
query_suffix (Optional[str]) – 
k (int) – 
aiosession (Optional[Any]) – 
Return type
None
attribute aiosession: Optional[Any] = None
attribute categories: Optional[List[str]] = []
attribute engines: Optional[List[str]] = []
attribute headers: Optional[dict] = None
attribute k: int = 10
attribute params: dict [Optional]
attribute query_suffix: Optional[str] = ''
attribute searx_host: str = ''
attribute unsecure: bool = False
async aresults(query, num_results, engines=None, query_suffix='', **kwargs)[source]
Asynchronously query with json results.
Uses aiohttp. See results for more info.
Parameters
query (str) – 
num_results (int) – 
engines (Optional[List[str]]) – 
query_suffix (Optional[str]) – 
kwargs (Any) – 
Return type
List[Dict]
async arun(query, engines=None, query_suffix='', **kwargs)[source]
Asynchronously version of run.
Parameters
query (str) – 
engines (Optional[List[str]]) – 
query_suffix (Optional[str]) – 
kwargs (Any) – 
Return type
str
results(query, num_results, engines=None, categories=None, query_suffix='', **kwargs)[source]
Run query through Searx API and returns the results with metadata.
Parameters
query (str) – The query to search for.
query_suffix (Optional[str]) – Extra suffix appended to the query.
num_results (int) – Limit the number of results to return.
engines (Optional[List[str]]) – List of engines to use for the query.
categories (Optional[List[str]]) – List of categories to use for the query.
**kwargs – extra parameters to pass to the searx API.
kwargs (Any) – 
Returns
{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.
}
Return type
Dict with the following keys
run(query, engines=None, categories=None, query_suffix='', **kwargs)[source]
Run query through Searx API and parse results.
You can pass any other params to the searx query API.
Parameters
query (str) – The query to search for.
query_suffix (Optional[str]) – Extra suffix appended to the query.
engines (Optional[List[str]]) – List of engines to use for the query.
categories (Optional[List[str]]) – List of categories to use for the query.
**kwargs – extra parameters to pass to the searx API.
kwargs (Any) – 
Returns
The result of the query.
Return type
str
Raises
ValueError – If an error occured with the query.
Example
This will make a query to the qwant engine:
from langchain.utilities import SearxSearchWrapper
searx = SearxSearchWrapper(searx_host="http://my.searx.host")
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")
class langchain.utilities.SerpAPIWrapper(*, search_engine=None, params={'engine': 'google', 'gl': 'us', 'google_domain': 'google.com', 'hl': 'en'}, serpapi_api_key=None, aiosession=None)[source]
Bases: pydantic.main.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
from langchain import SerpAPIWrapper
serpapi = SerpAPIWrapper()
Parameters
search_engine (Any) – 
params (dict) – 
serpapi_api_key (Optional[str]) – 
aiosession (Optional[aiohttp.client.ClientSession]) – 
Return type
None
attribute aiosession: Optional[aiohttp.client.ClientSession] = None
attribute params: dict = {'engine': 'google', 'gl': 'us', 'google_domain': 'google.com', 'hl': 'en'}
attribute serpapi_api_key: Optional[str] = None
async aresults(query)[source]
Use aiohttp to run query through SerpAPI and return the results async.
Parameters
query (str) – 
Return type
dict
async arun(query, **kwargs)[source]
Run query through SerpAPI and parse result async.
Parameters
query (str) – 
kwargs (Any) – 
Return type
str
get_params(query)[source]
Get parameters for SerpAPI.
Parameters
query (str) – 
Return type
Dict[str, str]
results(query)[source]
Run query through SerpAPI and return the raw result.
Parameters
query (str) – 
Return type
dict
run(query, **kwargs)[source]
Run query through SerpAPI and parse result.
Parameters
query (str) – 
kwargs (Any) – 
Return type
str
class langchain.utilities.SparkSQL(spark_session=None, catalog=None, schema=None, ignore_tables=None, include_tables=None, sample_rows_in_table_info=3)[source]
Bases: object
Parameters
spark_session (Optional[SparkSession]) – 
catalog (Optional[str]) – 
schema (Optional[str]) – 
ignore_tables (Optional[List[str]]) – 
include_tables (Optional[List[str]]) – 
sample_rows_in_table_info (int) – 
classmethod from_uri(database_uri, engine_args=None, **kwargs)[source]
Creating a remote Spark Session via Spark connect.
For example: SparkSQL.from_uri(“sc://localhost:15002”)
Parameters
database_uri (str) – 
engine_args (Optional[dict]) – 
kwargs (Any) – 
Return type
langchain.utilities.spark_sql.SparkSQL
get_usable_table_names()[source]
Get names of tables available.
Return type
Iterable[str]
get_table_info(table_names=None)[source]
Parameters
table_names (Optional[List[str]]) – 
Return type
str
run(command, fetch='all')[source]
Parameters
command (str) – 
fetch (str) – 
Return type
str
get_table_info_no_throw(table_names=None)[source]
Get information about specified tables.
Follows best practices as specified in: Rajkumar et al, 2022
(https://arxiv.org/abs/2204.00498)
If sample_rows_in_table_info, the specified number of sample rows will be
appended to each table description. This can increase performance as
demonstrated in the paper.
Parameters
table_names (Optional[List[str]]) – 
Return type
str
run_no_throw(command, fetch='all')[source]
Execute a SQL command and return a string representing the results.
If the statement returns rows, a string of the results is returned.
If the statement returns no rows, an empty string is returned.
If the statement throws an error, the error message is returned.
Parameters
command (str) – 
fetch (str) – 
Return type
str
class langchain.utilities.TextRequestsWrapper(*, headers=None, aiosession=None)[source]
Bases: pydantic.main.BaseModel
Lightweight wrapper around requests library.
The main purpose of this wrapper is to always return a text output.
Parameters
headers (Optional[Dict[str, str]]) – 
aiosession (Optional[aiohttp.client.ClientSession]) – 
Return type
None
attribute aiosession: Optional[aiohttp.client.ClientSession] = None
attribute headers: Optional[Dict[str, str]] = None
async adelete(url, **kwargs)[source]
DELETE the URL and return the text asynchronously.
Parameters
url (str) – 
kwargs (Any) – 
Return type
str
async aget(url, **kwargs)[source]
GET the URL and return the text asynchronously.
Parameters
url (str) – 
kwargs (Any) – 
Return type
str
async apatch(url, data, **kwargs)[source]
PATCH the URL and return the text asynchronously.
Parameters
url (str) – 
data (Dict[str, Any]) – 
kwargs (Any) – 
Return type
str
async apost(url, data, **kwargs)[source]
POST to the URL and return the text asynchronously.
Parameters
url (str) – 
data (Dict[str, Any]) – 
kwargs (Any) – 
Return type
str
async aput(url, data, **kwargs)[source]
PUT the URL and return the text asynchronously.
Parameters
url (str) – 
data (Dict[str, Any]) – 
kwargs (Any) – 
Return type
str
delete(url, **kwargs)[source]
DELETE the URL and return the text.
Parameters
url (str) – 
kwargs (Any) – 
Return type
str
get(url, **kwargs)[source]
GET the URL and return the text.
Parameters
url (str) – 
kwargs (Any) – 
Return type
str
patch(url, data, **kwargs)[source]
PATCH the URL and return the text.
Parameters
url (str) – 
data (Dict[str, Any]) – 
kwargs (Any) – 
Return type
str
post(url, data, **kwargs)[source]
POST to the URL and return the text.
Parameters
url (str) – 
data (Dict[str, Any]) – 
kwargs (Any) – 
Return type
str
put(url, data, **kwargs)[source]
PUT the URL and return the text.
Parameters
url (str) – 
data (Dict[str, Any]) – 
kwargs (Any) – 
Return type
str
property requests: langchain.requests.Requests
class langchain.utilities.TwilioAPIWrapper(*, client=None, account_sid=None, auth_token=None, from_number=None)[source]
Bases: pydantic.main.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
from langchain.utilities.twilio import TwilioAPIWrapper
twilio = TwilioAPIWrapper(
    account_sid="ACxxx",
    auth_token="xxx",
    from_number="+10123456789"
)
twilio.run('test', '+12484345508')
Parameters
client (Any) – 
account_sid (Optional[str]) – 
auth_token (Optional[str]) – 
from_number (Optional[str]) – 
Return type
None
attribute account_sid: Optional[str] = None
Twilio account string identifier.
attribute auth_token: Optional[str] = None
Twilio auth token.
attribute 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
[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.
run(body, to)[source]
Run body through Twilio and respond with message sid.
Parameters
body (str) – The text of the message you want to send. Can be up to 1,600
characters in length.
to (str) – 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.
Return type
str
class langchain.utilities.WikipediaAPIWrapper(*, wiki_client=None, top_k_results=3, lang='en', load_all_available_meta=False, doc_content_chars_max=4000)[source]
Bases: pydantic.main.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.
Parameters
wiki_client (Any) – 
top_k_results (int) – 
lang (str) – 
load_all_available_meta (bool) – 
doc_content_chars_max (int) – 
Return type
None
attribute doc_content_chars_max: int = 4000
attribute lang: str = 'en'
attribute load_all_available_meta: bool = False
attribute top_k_results: int = 3
load(query)[source]
Run Wikipedia search and get the article text plus the meta information.
See
Returns: a list of documents.
Parameters
query (str) – 
Return type
List[langchain.schema.Document]
run(query)[source]
Run Wikipedia search and get page summaries.
Parameters
query (str) – 
Return type
str
class langchain.utilities.WolframAlphaAPIWrapper(*, wolfram_client=None, wolfram_alpha_appid=None)[source]
Bases: pydantic.main.BaseModel
Wrapper for Wolfram Alpha.
Docs for using:
Go to wolfram alpha and sign up for a developer account
Create an app and get your APP ID
Save your APP ID into WOLFRAM_ALPHA_APPID env variable
pip install wolframalpha
Parameters
wolfram_client (Any) – 
wolfram_alpha_appid (Optional[str]) – 
Return type
None
attribute wolfram_alpha_appid: Optional[str] = None
run(query)[source]
Run query through WolframAlpha and parse result.
Parameters
query (str) – 
Return type
str
class langchain.utilities.ZapierNLAWrapper(*, zapier_nla_api_key, zapier_nla_oauth_access_token, zapier_nla_api_base='https://nla.zapier.com/api/v1/')[source]
Bases: pydantic.main.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)
For use-cases where LangChain + Zapier NLA is powering a user-facing application,
and LangChain needs access to the end-user’s connected accounts on Zapier.com,
you’ll need to use oauth. Review the full docs above and reach out to
nla@zapier.com for developer support.
Parameters
zapier_nla_api_key (str) – 
zapier_nla_oauth_access_token (str) – 
zapier_nla_api_base (str) – 
Return type
None
attribute zapier_nla_api_base: str = 'https://nla.zapier.com/api/v1/'
attribute zapier_nla_api_key: str [Required]
attribute zapier_nla_oauth_access_token: str [Required]
list()[source]
Returns a list of all exposed (enabled) actions associated with
current user (associated with the set api_key). Change your exposed
actions here: https://nla.zapier.com/demo/start/
The return list can be empty if no actions exposed. Else will contain
a list of action objects:
[{“id”: str,
“description”: str,
“params”: Dict[str, str]
}]
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)
Return type
List[Dict]
list_as_str()[source]
Same as list, but returns a stringified version of the JSON for
insertting back into an LLM.
Return type
str
preview(action_id, instructions, params=None)[source]
Same as run, but instead of actually executing the action, will
instead return a preview of params that have been guessed by the AI in
case you need to explicitly review before executing.
Parameters
action_id (str) – 
instructions (str) – 
params (Optional[Dict]) – 
Return type
Dict
preview_as_str(*args, **kwargs)[source]
Same as preview, but returns a stringified version of the JSON for
insertting back into an LLM.
Return type
str
run(action_id, instructions, params=None)[source]
Executes an action that is identified by action_id, must be exposed
(enabled) by the current user (associated with the set api_key). Change
your exposed actions here: https://nla.zapier.com/demo/start/
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.
Parameters
action_id (str) – 
instructions (str) – 
params (Optional[Dict]) – 
Return type
Dict
run_as_str(*args, **kwargs)[source]
Same as run, but returns a stringified version of the JSON for
insertting back into an LLM.
Return type
str