id
stringlengths 14
15
| text
stringlengths 22
2.51k
| source
stringlengths 61
160
|
---|---|---|
fb25a9683669-0 | langchain.utilities.graphql.GraphQLAPIWrapper¶
class langchain.utilities.graphql.GraphQLAPIWrapper(*, custom_headers: Optional[Dict[str, str]] = None, graphql_endpoint: str, gql_client: Any = None, gql_function: Callable[[str], Any])[source]¶
Bases: 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.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param custom_headers: Optional[Dict[str, str]] = None¶
param graphql_endpoint: str [Required]¶
run(query: str) → str[source]¶
Run a GraphQL query and get the results.
validator validate_environment » all fields[source]¶
Validate that the python package exists in the environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶
Examples using GraphQLAPIWrapper¶
GraphQL tool | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.graphql.GraphQLAPIWrapper.html |
d1c445c5c497-0 | langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper¶
class langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper(*, default_params: dict = {'depth': 10, 'language_code': 'en', 'location_name': 'United States', 'se_name': 'google', 'se_type': 'organic'}, params: dict = {}, api_login: Optional[str] = None, api_password: Optional[str] = None, json_result_types: Optional[list] = None, json_result_fields: Optional[list] = None, top_count: Optional[int] = None, aiosession: Optional[ClientSession] = None)[source]¶
Bases: BaseModel
Wrapper around the DataForSeo API.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[aiohttp.client.ClientSession] = None¶
The aiohttp session to use for the DataForSEO SERP API.
param api_login: Optional[str] = None¶
The API login to use for the DataForSEO SERP API.
param api_password: Optional[str] = None¶
The API password to use for the DataForSEO SERP API.
param default_params: dict = {'depth': 10, 'language_code': 'en', 'location_name': 'United States', 'se_name': 'google', 'se_type': 'organic'}¶
Default parameters to use for the DataForSEO SERP API.
param json_result_fields: Optional[list] = None¶
The JSON result fields.
param json_result_types: Optional[list] = None¶
The JSON result types.
param params: dict = {}¶
Additional parameters to pass to the DataForSEO SERP API.
param top_count: Optional[int] = None¶ | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper.html |
d1c445c5c497-1 | param top_count: Optional[int] = None¶
The number of top results to return.
async aresults(url: str) → list[source]¶
async arun(url: str) → str[source]¶
Run request to DataForSEO SERP API and parse result async.
results(url: str) → list[source]¶
run(url: str) → str[source]¶
Run request to DataForSEO SERP API and parse result async.
validator validate_environment » all fields[source]¶
Validate that login and password exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶
extra = 'forbid'¶
Examples using DataForSeoAPIWrapper¶
DataForSeo API Wrapper
DataForSEO | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.dataforseo_api_search.DataForSeoAPIWrapper.html |
a34e09a0f634-0 | langchain.utilities.powerbi.json_to_md¶
langchain.utilities.powerbi.json_to_md(json_contents: List[Dict[str, Union[str, int, float]]], table_name: Optional[str] = None) → str[source]¶
Converts a JSON object to a markdown table. | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.powerbi.json_to_md.html |
40e4abc15267-0 | langchain.utilities.wikipedia.WikipediaAPIWrapper¶
class langchain.utilities.wikipedia.WikipediaAPIWrapper(*, wiki_client: Any = None, top_k_results: int = 3, lang: str = 'en', load_all_available_meta: bool = False, doc_content_chars_max: int = 4000)[source]¶
Bases: 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.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param doc_content_chars_max: int = 4000¶
param lang: str = 'en'¶
param load_all_available_meta: bool = False¶
param top_k_results: int = 3¶
load(query: str) → List[Document][source]¶
Run Wikipedia search and get the article text plus the meta information.
See
Returns: a list of documents.
run(query: str) → str[source]¶
Run Wikipedia search and get page summaries.
validator validate_environment » all fields[source]¶
Validate that the python package exists in environment.
Examples using WikipediaAPIWrapper¶
Wikipedia
Zep Memory | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.wikipedia.WikipediaAPIWrapper.html |
ea79480ef399-0 | langchain.utilities.google_search.GoogleSearchAPIWrapper¶
class langchain.utilities.google_search.GoogleSearchAPIWrapper(*, search_engine: Any = None, google_api_key: Optional[str] = None, google_cse_id: Optional[str] = None, k: int = 10, siterestrict: bool = False)[source]¶
Bases: 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 | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.google_search.GoogleSearchAPIWrapper.html |
ea79480ef399-1 | 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
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param google_api_key: Optional[str] = None¶
param google_cse_id: Optional[str] = None¶
param k: int = 10¶
param siterestrict: bool = False¶
results(query: str, num_results: int, search_params: Optional[Dict[str, str]] = None) → List[Dict][source]¶
Run query through GoogleSearch and return metadata.
Parameters
query – The query to search for.
num_results – The number of results to return.
search_params – Parameters to be passed on search
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: str) → str[source]¶
Run query through GoogleSearch and parse result.
validator validate_environment » all fields[source]¶
Validate that api key and python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶
Examples using GoogleSearchAPIWrapper¶
Google Search
WebResearchRetriever
Adding Message Memory backed by a database to an Agent
How to add Memory to an Agent
Shared memory across agents and tools | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.google_search.GoogleSearchAPIWrapper.html |
2fa460d2b94c-0 | langchain.utilities.powerbi.PowerBIDataset¶
class langchain.utilities.powerbi.PowerBIDataset(*, dataset_id: str, table_names: List[str], group_id: Optional[str] = None, credential: Optional[TokenCredential] = None, token: Optional[str] = None, impersonated_user_name: Optional[str] = None, sample_rows_in_table_info: ConstrainedIntValue = 1, schemas: Dict[str, str] = None, aiosession: Optional[ClientSession] = None)[source]¶
Bases: 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.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[aiohttp.ClientSession] = None¶
param credential: Optional[TokenCredential] = None¶
param dataset_id: str [Required]¶
param group_id: Optional[str] = None¶
param impersonated_user_name: Optional[str] = None¶
param sample_rows_in_table_info: int = 1¶
Constraints
exclusiveMinimum = 0
maximum = 10
param schemas: Dict[str, str] [Optional]¶
param table_names: List[str] [Required]¶
param token: Optional[str] = None¶
async aget_table_info(table_names: Optional[Union[List[str], str]] = None) → str[source]¶
Get information about specified tables.
async arun(command: str) → Any[source]¶
Execute a DAX command and return the result asynchronously. | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.powerbi.PowerBIDataset.html |
2fa460d2b94c-1 | Execute a DAX command and return the result asynchronously.
validator fix_table_names » table_names[source]¶
Fix the table names.
get_schemas() → str[source]¶
Get the available schema’s.
get_table_info(table_names: Optional[Union[List[str], str]] = None) → str[source]¶
Get information about specified tables.
get_table_names() → Iterable[str][source]¶
Get names of tables available.
run(command: str) → Any[source]¶
Execute a DAX command and return a json representing the results.
validator token_or_credential_present » all fields[source]¶
Validate that at least one of token and credentials is present.
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.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶
Examples using PowerBIDataset¶
PowerBI Dataset Agent | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.powerbi.PowerBIDataset.html |
8e2757a7289e-0 | langchain.utilities.multion.MultionClientAPIWrapper¶
class langchain.utilities.multion.MultionClientAPIWrapper(*, client: ~typing.Any = <langchain.utilities.multion.MultionAPI object>)[source]¶
Bases: BaseModel
Wrapper for Multion Client API.
In order to set this up, follow instructions at:
NEED TO ADD
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param client: Any = <langchain.utilities.multion.MultionAPI object>¶
run(task: str, url: str, tabId: Optional[Any]) → str[source]¶
Run body through Multion Client and respond with action.
Parameters
task –
url –
tabId – | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.multion.MultionClientAPIWrapper.html |
9ad4f17dbc47-0 | langchain.utilities.vertexai.init_vertexai¶
langchain.utilities.vertexai.init_vertexai(project: Optional[str] = None, location: Optional[str] = None, credentials: Optional[Credentials] = None) → None[source]¶
Init vertexai.
Parameters
project – The default GCP project to use when making Vertex API calls.
location – The default location to use when making API calls.
credentials – The default custom
credentials to use when making API calls. If not provided credentials
will be ascertained from the environment.
Raises
ImportError – If importing vertexai SDK did not succeed. | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.vertexai.init_vertexai.html |
0053f1fdd7ee-0 | langchain.utilities.pupmed.PubMedAPIWrapper¶
class langchain.utilities.pupmed.PubMedAPIWrapper(*, top_k_results: int = 3, load_max_docs: int = 25, doc_content_chars_max: int = 2000, load_all_available_meta: bool = False, email: str = 'your_email@example.com', base_url_esearch: str = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?', base_url_efetch: str = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?', max_retry: int = 5, sleep_time: float = 0.2, ARXIV_MAX_QUERY_LENGTH: int = 300)[source]¶
Bases: BaseModel
Wrapper around PubMed API.
This wrapper will use the PubMed API to conduct searches and fetch
document summaries. By default, it will return the document summaries
of the top-k results of an input search.
Parameters
top_k_results – number of the top-scored document used for the PubMed tool
load_max_docs – a limit to the number of loaded documents
load_all_available_meta –
if True: the metadata of the loaded Documents gets all available meta info(see https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch)
if False: the metadata gets only the most informative fields.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param doc_content_chars_max: int = 2000¶
param email: str = 'your_email@example.com'¶
param load_all_available_meta: bool = False¶
param load_max_docs: int = 25¶
param top_k_results: int = 3¶ | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.pupmed.PubMedAPIWrapper.html |
0053f1fdd7ee-1 | param top_k_results: int = 3¶
load(query: str) → List[dict][source]¶
Search PubMed for documents matching the query.
Return a list of dictionaries containing the document metadata.
load_docs(query: str) → List[Document][source]¶
retrieve_article(uid: str, webenv: str) → dict[source]¶
run(query: str) → str[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. | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.pupmed.PubMedAPIWrapper.html |
687572e33c73-0 | langchain.utilities.searx_search.SearxSearchWrapper¶
class langchain.utilities.searx_search.SearxSearchWrapper(*, searx_host: str = '', unsecure: bool = False, params: dict = None, headers: Optional[dict] = None, engines: Optional[List[str]] = [], categories: Optional[List[str]] = [], query_suffix: Optional[str] = '', k: int = 10, aiosession: Optional[Any] = None)[source]¶
Bases: 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)
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[Any] = None¶
param categories: Optional[List[str]] = []¶
param engines: Optional[List[str]] = []¶
param headers: Optional[dict] = None¶
param k: int = 10¶
param params: dict [Optional]¶ | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.searx_search.SearxSearchWrapper.html |
687572e33c73-1 | param k: int = 10¶
param params: dict [Optional]¶
param query_suffix: Optional[str] = ''¶
param searx_host: str = ''¶
param unsecure: bool = False¶
async aresults(query: str, num_results: int, engines: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) → List[Dict][source]¶
Asynchronously query with json results.
Uses aiohttp. See results for more info.
async arun(query: str, engines: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) → str[source]¶
Asynchronously version of run.
validator disable_ssl_warnings » unsecure[source]¶
Disable SSL warnings.
results(query: str, num_results: int, engines: Optional[List[str]] = None, categories: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) → List[Dict][source]¶
Run query through Searx API and returns the results with metadata.
Parameters
query – The query to search for.
query_suffix – Extra suffix appended to the query.
num_results – Limit the number of results to return.
engines – List of engines to use for the query.
categories – List of categories to use for the query.
**kwargs – extra parameters to pass to the searx API.
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 | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.searx_search.SearxSearchWrapper.html |
687572e33c73-2 | }
Return type
Dict with the following keys
run(query: str, engines: Optional[List[str]] = None, categories: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) → str[source]¶
Run query through Searx API and parse results.
You can pass any other params to the searx query API.
Parameters
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
The result of the query.
Return type
str
Raises
ValueError – If an error occurred 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")
validator validate_params » all fields[source]¶
Validate that custom searx params are merged with default ones.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶
Examples using SearxSearchWrapper¶
SearxNG Search API | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.searx_search.SearxSearchWrapper.html |
38ec3c509ac2-0 | langchain.utilities.requests.Requests¶
class langchain.utilities.requests.Requests(*, headers: Optional[Dict[str, str]] = None, aiosession: Optional[ClientSession] = None, auth: Optional[Any] = None)[source]¶
Bases: BaseModel
Wrapper around requests to handle auth and async.
The main purpose of this wrapper is to handle authentication (by saving
headers) and enable easy async methods on the same base object.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[aiohttp.client.ClientSession] = None¶
param auth: Optional[Any] = None¶
param headers: Optional[Dict[str, str]] = None¶
adelete(url: str, **kwargs: Any) → AsyncGenerator[ClientResponse, None][source]¶
DELETE the URL and return the text asynchronously.
aget(url: str, **kwargs: Any) → AsyncGenerator[ClientResponse, None][source]¶
GET the URL and return the text asynchronously.
apatch(url: str, data: Dict[str, Any], **kwargs: Any) → AsyncGenerator[ClientResponse, None][source]¶
PATCH the URL and return the text asynchronously.
apost(url: str, data: Dict[str, Any], **kwargs: Any) → AsyncGenerator[ClientResponse, None][source]¶
POST to the URL and return the text asynchronously.
aput(url: str, data: Dict[str, Any], **kwargs: Any) → AsyncGenerator[ClientResponse, None][source]¶
PUT the URL and return the text asynchronously.
delete(url: str, **kwargs: Any) → Response[source]¶
DELETE the URL and return the text.
get(url: str, **kwargs: Any) → Response[source]¶ | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.Requests.html |
38ec3c509ac2-1 | get(url: str, **kwargs: Any) → Response[source]¶
GET the URL and return the text.
patch(url: str, data: Dict[str, Any], **kwargs: Any) → Response[source]¶
PATCH the URL and return the text.
post(url: str, data: Dict[str, Any], **kwargs: Any) → Response[source]¶
POST to the URL and return the text.
put(url: str, data: Dict[str, Any], **kwargs: Any) → Response[source]¶
PUT the URL and return the text.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶
extra = 'forbid'¶
Examples using Requests¶
Natural Language APIs
Evaluating an OpenAPI Chain
OpenAPI chain | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.Requests.html |
8bc8753c2961-0 | langchain.utilities.powerbi.fix_table_name¶
langchain.utilities.powerbi.fix_table_name(table: str) → str[source]¶
Add single quotes around table names that contain spaces. | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.powerbi.fix_table_name.html |
9d340dc86bcf-0 | langchain.utilities.awslambda.LambdaWrapper¶
class langchain.utilities.awslambda.LambdaWrapper(*, lambda_client: Any = None, function_name: Optional[str] = None, awslambda_tool_name: Optional[str] = None, awslambda_tool_description: Optional[str] = None)[source]¶
Bases: BaseModel
Wrapper for AWS Lambda SDK.
To use, you should have the boto3 package installed
and a lambda functions built from the AWS Console or
CLI. Set up your AWS credentials with aws configure
Example
pip install boto3
aws configure
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param awslambda_tool_description: Optional[str] = None¶
If passing to an agent as a tool, the description
param awslambda_tool_name: Optional[str] = None¶
If passing to an agent as a tool, the tool name
param function_name: Optional[str] = None¶
The name of your lambda function
param lambda_client: Any = None¶
The configured boto3 client
run(query: str) → str[source]¶
Invokes the lambda function and returns the
result.
Parameters
query – an input to passed to the lambda
function as the body of a JSON
object.
validator validate_environment » all fields[source]¶
Validate that python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶ | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.awslambda.LambdaWrapper.html |
a322c008af0b-0 | langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper¶
class langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper(*, wolfram_client: Any = None, wolfram_alpha_appid: Optional[str] = None)[source]¶
Bases: 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
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param wolfram_alpha_appid: Optional[str] = None¶
run(query: str) → str[source]¶
Run query through WolframAlpha and parse result.
validator validate_environment » all fields[source]¶
Validate that api key and python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶
Examples using WolframAlphaAPIWrapper¶
Wolfram Alpha | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper.html |
93ea0bd77735-0 | langchain.utilities.golden_query.GoldenQueryAPIWrapper¶
class langchain.utilities.golden_query.GoldenQueryAPIWrapper(*, golden_api_key: Optional[str] = None)[source]¶
Bases: BaseModel
Wrapper for Golden.
Docs for using:
Go to https://golden.com and sign up for an account
Get your API Key from https://golden.com/settings/api
Save your API Key into GOLDEN_API_KEY env variable
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param golden_api_key: Optional[str] = None¶
run(query: str) → str[source]¶
Run query through Golden Query API and return the JSON raw result.
validator validate_environment » all fields[source]¶
Validate that api key and python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶
Examples using GoldenQueryAPIWrapper¶
Golden Query
Golden | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.golden_query.GoldenQueryAPIWrapper.html |
0cc5b2ef0f6a-0 | langchain.utilities.openweathermap.OpenWeatherMapAPIWrapper¶
class langchain.utilities.openweathermap.OpenWeatherMapAPIWrapper(*, owm: Any = None, openweathermap_api_key: Optional[str] = None)[source]¶
Bases: 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
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param openweathermap_api_key: Optional[str] = None¶
param owm: Any = None¶
run(location: str) → str[source]¶
Get the current weather information for a specified location.
validator validate_environment » all fields[source]¶
Validate that api key exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶
Examples using OpenWeatherMapAPIWrapper¶
OpenWeatherMap API
OpenWeatherMap | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.openweathermap.OpenWeatherMapAPIWrapper.html |
a448c8c69253-0 | langchain.utilities.openapi.OpenAPISpec¶
class langchain.utilities.openapi.OpenAPISpec(*, openapi: str = '3.1.0', info: Info, jsonSchemaDialect: Optional[str] = None, servers: List[Server] = [Server(url='/', description=None, variables=None)], paths: Optional[Dict[str, PathItem]] = None, webhooks: Optional[Dict[str, Union[PathItem, Reference]]] = None, components: Optional[Components] = None, security: Optional[List[Dict[str, List[str]]]] = None, tags: Optional[List[Tag]] = None, externalDocs: Optional[ExternalDocumentation] = None)[source]¶
Bases: OpenAPI
OpenAPI Model that removes misformatted parts of the spec.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param components: Optional[openapi_schema_pydantic.v3.v3_1_0.components.Components] = None¶
An element to hold various schemas for the document.
param externalDocs: Optional[openapi_schema_pydantic.v3.v3_1_0.external_documentation.ExternalDocumentation] = None¶
Additional external documentation.
param info: openapi_schema_pydantic.v3.v3_1_0.info.Info [Required]¶
REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required.
param jsonSchemaDialect: Optional[str] = None¶
The default value for the $schema keyword within [Schema Objects](#schemaObject)
contained within this OAS document. This MUST be in the form of a URI.
param openapi: str = '3.1.0'¶
REQUIRED. This string MUST be the [version number](#versions) | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.openapi.OpenAPISpec.html |
a448c8c69253-1 | REQUIRED. This string MUST be the [version number](#versions)
of the OpenAPI Specification that the OpenAPI document uses.
The openapi field SHOULD be used by tooling to interpret the OpenAPI document.
This is not related to the API [info.version](#infoVersion) string.
param paths: Optional[Dict[str, openapi_schema_pydantic.v3.v3_1_0.path_item.PathItem]] = None¶
The available paths and operations for the API.
param security: Optional[List[Dict[str, List[str]]]] = None¶
A declaration of which security mechanisms can be used across the API.
The list of values includes alternative security requirement objects that can be used.
Only one of the security requirement objects need to be satisfied to authorize a request.
Individual operations can override this definition.
To make security optional, an empty security requirement ({}) can be included in the array.
param servers: List[openapi_schema_pydantic.v3.v3_1_0.server.Server] = [Server(url='/', description=None, variables=None)]¶
An array of Server Objects, which provide connectivity information to a target server.
If the servers property is not provided, or is an empty array,
the default value would be a [Server Object](#serverObject) with a [url](#serverUrl) value of /.
param tags: Optional[List[openapi_schema_pydantic.v3.v3_1_0.tag.Tag]] = None¶
A list of tags used by the document with additional metadata.
The order of the tags can be used to reflect on their order by the parsing tools.
Not all tags that are used by the [Operation Object](#operationObject) must be declared.
The tags that are not declared MAY be organized randomly or based on the tools’ logic.
Each tag name in the list MUST be unique. | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.openapi.OpenAPISpec.html |
a448c8c69253-2 | Each tag name in the list MUST be unique.
param webhooks: Optional[Dict[str, Union[openapi_schema_pydantic.v3.v3_1_0.path_item.PathItem, openapi_schema_pydantic.v3.v3_1_0.reference.Reference]]] = None¶
The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement.
Closely related to the callbacks feature, this section describes requests initiated other than by an API call,
for example by an out of band registration.
The key name is a unique string to refer to each webhook,
while the (optionally referenced) Path Item Object describes a request
that may be initiated by the API provider and the expected responses.
An [example](../examples/v3.1/webhook-example.yaml) is available.
classmethod from_file(path: Union[str, Path]) → OpenAPISpec[source]¶
Get an OpenAPI spec from a file path.
classmethod from_spec_dict(spec_dict: dict) → OpenAPISpec[source]¶
Get an OpenAPI spec from a dict.
classmethod from_text(text: str) → OpenAPISpec[source]¶
Get an OpenAPI spec from a text.
classmethod from_url(url: str) → OpenAPISpec[source]¶
Get an OpenAPI spec from a URL.
static get_cleaned_operation_id(operation: Operation, path: str, method: str) → str[source]¶
Get a cleaned operation id from an operation id.
get_methods_for_path(path: str) → List[str][source]¶
Return a list of valid methods for the specified path.
get_operation(path: str, method: str) → Operation[source]¶
Get the operation object for a given path and HTTP method.
get_parameters_for_operation(operation: Operation) → List[Parameter][source]¶ | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.openapi.OpenAPISpec.html |
a448c8c69253-3 | get_parameters_for_operation(operation: Operation) → List[Parameter][source]¶
Get the components for a given operation.
get_parameters_for_path(path: str) → List[Parameter][source]¶
get_referenced_schema(ref: Reference) → Schema[source]¶
Get a schema (or nested reference) or err.
get_request_body_for_operation(operation: Operation) → Optional[RequestBody][source]¶
Get the request body for a given operation.
get_schema(schema: Union[Reference, Schema]) → Schema[source]¶
classmethod parse_obj(obj: dict) → OpenAPISpec[source]¶
property base_url: str¶
Get the base url.
model Config¶
Bases: object
extra = 'ignore'¶
Examples using OpenAPISpec¶
Natural Language APIs
Evaluating an OpenAPI Chain
OpenAPI chain | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.openapi.OpenAPISpec.html |
b77a7d34f50a-0 | langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper¶
class langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper(*, region: Optional[str] = 'wt-wt', safesearch: str = 'moderate', time: Optional[str] = 'y', max_results: int = 5)[source]¶
Bases: BaseModel
Wrapper for DuckDuckGo Search API.
Free and does not require any setup.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param max_results: int = 5¶
param region: Optional[str] = 'wt-wt'¶
param safesearch: str = 'moderate'¶
param time: Optional[str] = 'y'¶
get_snippets(query: str) → List[str][source]¶
Run query through DuckDuckGo and return concatenated results.
results(query: str, num_results: int, backend: str = 'api') → List[Dict[str, str]][source]¶
Run query through DuckDuckGo and return metadata.
Parameters
query – The query to search for.
num_results – 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: str) → str[source]¶
validator validate_environment » all fields[source]¶
Validate that python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶
Examples using DuckDuckGoSearchAPIWrapper¶
DuckDuckGo Search | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper.html |
4431fa6095c9-0 | langchain.utilities.serpapi.SerpAPIWrapper¶
class langchain.utilities.serpapi.SerpAPIWrapper(*, search_engine: Any = None, params: dict = {'engine': 'google', 'gl': 'us', 'google_domain': 'google.com', 'hl': 'en'}, serpapi_api_key: Optional[str] = None, aiosession: Optional[ClientSession] = None)[source]¶
Bases: 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.utilities import SerpAPIWrapper
serpapi = SerpAPIWrapper()
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[aiohttp.client.ClientSession] = None¶
param params: dict = {'engine': 'google', 'gl': 'us', 'google_domain': 'google.com', 'hl': 'en'}¶
param serpapi_api_key: Optional[str] = None¶
async aresults(query: str) → dict[source]¶
Use aiohttp to run query through SerpAPI and return the results async.
async arun(query: str, **kwargs: Any) → str[source]¶
Run query through SerpAPI and parse result async.
get_params(query: str) → Dict[str, str][source]¶
Get parameters for SerpAPI.
results(query: str) → dict[source]¶
Run query through SerpAPI and return the raw result.
run(query: str, **kwargs: Any) → str[source]¶
Run query through SerpAPI and parse result. | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.serpapi.SerpAPIWrapper.html |
4431fa6095c9-1 | Run query through SerpAPI and parse result.
validator validate_environment » all fields[source]¶
Validate that api key and python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶
extra = 'forbid'¶
Examples using SerpAPIWrapper¶
SerpAPI
AutoGPT | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.serpapi.SerpAPIWrapper.html |
4e95f2ed9700-0 | langchain.utilities.requests.TextRequestsWrapper¶
class langchain.utilities.requests.TextRequestsWrapper(*, headers: Optional[Dict[str, str]] = None, aiosession: Optional[ClientSession] = None, auth: Optional[Any] = None)[source]¶
Bases: BaseModel
Lightweight wrapper around requests library.
The main purpose of this wrapper is to always return a text output.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[aiohttp.client.ClientSession] = None¶
param auth: Optional[Any] = None¶
param headers: Optional[Dict[str, str]] = None¶
async adelete(url: str, **kwargs: Any) → str[source]¶
DELETE the URL and return the text asynchronously.
async aget(url: str, **kwargs: Any) → str[source]¶
GET the URL and return the text asynchronously.
async apatch(url: str, data: Dict[str, Any], **kwargs: Any) → str[source]¶
PATCH the URL and return the text asynchronously.
async apost(url: str, data: Dict[str, Any], **kwargs: Any) → str[source]¶
POST to the URL and return the text asynchronously.
async aput(url: str, data: Dict[str, Any], **kwargs: Any) → str[source]¶
PUT the URL and return the text asynchronously.
delete(url: str, **kwargs: Any) → str[source]¶
DELETE the URL and return the text.
get(url: str, **kwargs: Any) → str[source]¶
GET the URL and return the text.
patch(url: str, data: Dict[str, Any], **kwargs: Any) → str[source]¶
PATCH the URL and return the text. | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.TextRequestsWrapper.html |
4e95f2ed9700-1 | PATCH the URL and return the text.
post(url: str, data: Dict[str, Any], **kwargs: Any) → str[source]¶
POST to the URL and return the text.
put(url: str, data: Dict[str, Any], **kwargs: Any) → str[source]¶
PUT the URL and return the text.
property requests: langchain.utilities.requests.Requests¶
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶
extra = 'forbid'¶
Examples using TextRequestsWrapper¶
Requests
JSON Agent
OpenAPI agents
Tool Input Schema | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.requests.TextRequestsWrapper.html |
d4b508340e10-0 | langchain.utilities.redis.get_client¶
langchain.utilities.redis.get_client(redis_url: str, **kwargs: Any) → RedisType[source]¶
Get a redis client from the connection url given. This helper accepts
urls for Redis server (TCP with/without TLS or UnixSocket) as well as
Redis Sentinel connections.
Redis Cluster is not supported.
Before creating a connection the existence of the database driver is checked
an and ValueError raised otherwise
To use, you should have the redis python package installed.
Example
from langchain.utilities.redis import get_client
redis_client = get_client(
redis_url="redis://username:password@localhost:6379"
index_name="my-index",
embedding_function=embeddings.embed_query,
)
To use a redis replication setup with multiple redis server and redis sentinels
set “redis_url” to “redis+sentinel://” scheme. With this url format a path is
needed holding the name of the redis service within the sentinels to get the
correct redis server connection. The default service name is “mymaster”. The
optional second part of the path is the redis db number to connect to.
An optional username or password is used for booth connections to the rediserver
and the sentinel, different passwords for server and sentinel are not supported.
And as another constraint only one sentinel instance can be given:
Example
from langchain.utilities.redis import get_client
redis_client = get_client(
redis_url="redis+sentinel://username:password@sentinelhost:26379/mymaster/0"
index_name="my-index",
embedding_function=embeddings.embed_query,
) | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.redis.get_client.html |
0bb836b9aaf9-0 | langchain.utilities.vertexai.raise_vertex_import_error¶
langchain.utilities.vertexai.raise_vertex_import_error() → None[source]¶
Raise ImportError related to Vertex SDK being not available.
Raises
ImportError – an ImportError that mentions a required version of the SDK. | https://api.python.langchain.com/en/latest/utilities/langchain.utilities.vertexai.raise_vertex_import_error.html |
0e4fc7241bb9-0 | langchain_experimental.sql.base.SQLDatabaseChain¶
class langchain_experimental.sql.base.SQLDatabaseChain(*, memory: Optional[BaseMemory] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, callback_manager: Optional[BaseCallbackManager] = None, verbose: bool = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, llm_chain: LLMChain, llm: Optional[BaseLanguageModel] = None, database: SQLDatabase, prompt: Optional[BasePromptTemplate] = None, top_k: int = 5, input_key: str = 'query', output_key: str = 'result', return_sql: bool = False, return_intermediate_steps: bool = False, return_direct: bool = False, use_query_checker: bool = False, query_checker_prompt: Optional[BasePromptTemplate] = None)[source]¶
Bases: Chain
Chain for interacting with SQL Database.
Example
from langchain_experimental.sql import SQLDatabaseChain
from langchain import OpenAI, SQLDatabase
db = SQLDatabase(...)
db_chain = SQLDatabaseChain.from_llm(OpenAI(), db)
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param callback_manager: Optional[BaseCallbackManager] = None¶
Deprecated, use callbacks instead.
param callbacks: Callbacks = None¶
Optional list of callback handlers (or callback manager). Defaults to None.
Callback handlers are called throughout the lifecycle of a call to a chain,
starting with on_chain_start, ending with on_chain_end or on_chain_error.
Each custom chain can optionally call additional callback methods, see Callback docs
for full details.
param database: SQLDatabase [Required]¶
SQL Database to connect to. | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html |
0e4fc7241bb9-1 | param database: SQLDatabase [Required]¶
SQL Database to connect to.
param llm: Optional[BaseLanguageModel] = None¶
[Deprecated] LLM wrapper to use.
param llm_chain: LLMChain [Required]¶
param memory: Optional[BaseMemory] = None¶
Optional memory object. Defaults to None.
Memory is a class that gets called at the start
and at the end of every chain. At the start, memory loads variables and passes
them along in the chain. At the end, it saves any returned variables.
There are many different types of memory - please see memory docs
for the full catalog.
param metadata: Optional[Dict[str, Any]] = None¶
Optional metadata associated with the chain. Defaults to None.
This metadata will be associated with each call to this chain,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a chain with its use case.
param prompt: Optional[BasePromptTemplate] = None¶
[Deprecated] Prompt to use to translate natural language to SQL.
param query_checker_prompt: Optional[BasePromptTemplate] = None¶
The prompt template that should be used by the query checker
param return_direct: bool = False¶
Whether or not to return the result of querying the SQL table directly.
param return_intermediate_steps: bool = False¶
Whether or not to return the intermediate steps along with the final answer.
param return_sql: bool = False¶
Will return sql-command directly without executing it
param tags: Optional[List[str]] = None¶
Optional list of tags associated with the chain. Defaults to None.
These tags will be associated with each call to this chain,
and passed as arguments to the handlers defined in callbacks. | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html |
0e4fc7241bb9-2 | and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a chain with its use case.
param top_k: int = 5¶
Number of results to return from the query
param use_query_checker: bool = False¶
Whether or not the query checker tool should be used to attempt
to fix the initial SQL from the LLM.
param verbose: bool [Optional]¶
Whether or not run in verbose mode. In verbose mode, some intermediate logs
will be printed to the console. Defaults to langchain.verbose value.
__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, include_run_info: bool = False) → Dict[str, Any]¶
Execute the chain.
Parameters
inputs – Dictionary of inputs, or single input if chain expects
only one param. Should contain all inputs specified in
Chain.input_keys except for inputs that will be set by the chain’s
memory.
return_only_outputs – Whether to return only outputs in the
response. If True, only new keys generated by this chain will be
returned. If False, both input keys and new keys generated by this
chain will be returned. Defaults to False.
callbacks – Callbacks to use for this chain run. These will be called in
addition to callbacks passed to the chain during construction, but only
these runtime callbacks will propagate to calls to other objects.
tags – List of string tags to pass to all callbacks. These will be passed in
addition to tags passed to the chain during construction, but only
these runtime tags will propagate to calls to other objects. | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html |
0e4fc7241bb9-3 | these runtime tags will propagate to calls to other objects.
metadata – Optional metadata associated with the chain. Defaults to None
include_run_info – Whether to include run info in the response. Defaults
to False.
Returns
A dict of named outputs. Should contain all outputs specified inChain.output_keys.
async acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, include_run_info: bool = False) → Dict[str, Any]¶
Asynchronously execute the chain.
Parameters
inputs – Dictionary of inputs, or single input if chain expects
only one param. Should contain all inputs specified in
Chain.input_keys except for inputs that will be set by the chain’s
memory.
return_only_outputs – Whether to return only outputs in the
response. If True, only new keys generated by this chain will be
returned. If False, both input keys and new keys generated by this
chain will be returned. Defaults to False.
callbacks – Callbacks to use for this chain run. These will be called in
addition to callbacks passed to the chain during construction, but only
these runtime callbacks will propagate to calls to other objects.
tags – List of string tags to pass to all callbacks. These will be passed in
addition to tags passed to the chain during construction, but only
these runtime tags will propagate to calls to other objects.
metadata – Optional metadata associated with the chain. Defaults to None
include_run_info – Whether to include run info in the response. Defaults
to False.
Returns
A dict of named outputs. Should contain all outputs specified inChain.output_keys. | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html |
0e4fc7241bb9-4 | Returns
A dict of named outputs. Should contain all outputs specified inChain.output_keys.
async ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None) → Dict[str, Any]¶
apply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → List[Dict[str, str]]¶
Call the chain on all inputs in the list.
async arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) → Any¶
Convenience method for executing chain.
The main difference between this method and Chain.__call__ is that this
method expects inputs to be passed directly in as positional arguments or
keyword arguments, whereas Chain.__call__ expects a single input dictionary
with all the inputs
Parameters
*args – If the chain expects a single input, it can be passed in as the
sole positional argument.
callbacks – Callbacks to use for this chain run. These will be called in
addition to callbacks passed to the chain during construction, but only
these runtime callbacks will propagate to calls to other objects.
tags – List of string tags to pass to all callbacks. These will be passed in
addition to tags passed to the chain during construction, but only
these runtime tags will propagate to calls to other objects.
**kwargs – If the chain expects multiple inputs, they can be passed in
directly as keyword arguments.
Returns
The chain output.
Example
# Suppose we have a single-input chain that takes a 'question' string:
await chain.arun("What's the temperature in Boise, Idaho?")
# -> "The temperature in Boise is..." | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html |
0e4fc7241bb9-5 | # -> "The temperature in Boise is..."
# Suppose we have a multi-input chain that takes a 'question' string
# and 'context' string:
question = "What's the temperature in Boise, Idaho?"
context = "Weather report for Boise, Idaho on 07/03/23..."
await chain.arun(question=question, context=context)
# -> "The temperature in Boise is..."
dict(**kwargs: Any) → Dict¶
Dictionary representation of chain.
Expects Chain._chain_type property to be implemented and for memory to benull.
Parameters
**kwargs – Keyword arguments passed to default pydantic.BaseModel.dict
method.
Returns
A dictionary representation of the chain.
Example
..code-block:: python
chain.dict(exclude_unset=True)
# -> {“_type”: “foo”, “verbose”: False, …}
classmethod from_llm(llm: BaseLanguageModel, db: SQLDatabase, prompt: Optional[BasePromptTemplate] = None, **kwargs: Any) → SQLDatabaseChain[source]¶
invoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None) → Dict[str, Any]¶
prep_inputs(inputs: Union[Dict[str, Any], Any]) → Dict[str, str]¶
Validate and prepare chain inputs, including adding inputs from memory.
Parameters
inputs – Dictionary of raw inputs, or single input if chain expects
only one param. Should contain all inputs specified in
Chain.input_keys except for inputs that will be set by the chain’s
memory.
Returns
A dictionary of all inputs, including those added by the chain’s memory.
prep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) → Dict[str, str]¶
Validate and prepare chain outputs, and save info about this run to memory.
Parameters | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html |
0e4fc7241bb9-6 | Validate and prepare chain outputs, and save info about this run to memory.
Parameters
inputs – Dictionary of chain inputs, including any inputs added by chain
memory.
outputs – Dictionary of initial chain outputs.
return_only_outputs – Whether to only return the chain outputs. If False,
inputs are also added to the final outputs.
Returns
A dict of the final chain outputs.
validator raise_callback_manager_deprecation » all fields¶
Raise deprecation warning if callback_manager is used.
validator raise_deprecation » all fields[source]¶
run(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) → Any¶
Convenience method for executing chain.
The main difference between this method and Chain.__call__ is that this
method expects inputs to be passed directly in as positional arguments or
keyword arguments, whereas Chain.__call__ expects a single input dictionary
with all the inputs
Parameters
*args – If the chain expects a single input, it can be passed in as the
sole positional argument.
callbacks – Callbacks to use for this chain run. These will be called in
addition to callbacks passed to the chain during construction, but only
these runtime callbacks will propagate to calls to other objects.
tags – List of string tags to pass to all callbacks. These will be passed in
addition to tags passed to the chain during construction, but only
these runtime tags will propagate to calls to other objects.
**kwargs – If the chain expects multiple inputs, they can be passed in
directly as keyword arguments.
Returns
The chain output.
Example
# Suppose we have a single-input chain that takes a 'question' string: | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html |
0e4fc7241bb9-7 | Example
# Suppose we have a single-input chain that takes a 'question' string:
chain.run("What's the temperature in Boise, Idaho?")
# -> "The temperature in Boise is..."
# Suppose we have a multi-input chain that takes a 'question' string
# and 'context' string:
question = "What's the temperature in Boise, Idaho?"
context = "Weather report for Boise, Idaho on 07/03/23..."
chain.run(question=question, context=context)
# -> "The temperature in Boise is..."
save(file_path: Union[Path, str]) → None¶
Save the chain.
Expects Chain._chain_type property to be implemented and for memory to benull.
Parameters
file_path – Path to file to save the chain to.
Example
chain.save(file_path="path/chain.yaml")
validator set_verbose » verbose¶
Set the chain verbosity.
Defaults to the global setting if not specified by the user.
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
to_json_not_implemented() → SerializedNotImplemented¶
property lc_attributes: Dict¶
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]¶
Return the namespace of the langchain object.
eg. [“langchain”, “llms”, “openai”]
property lc_secrets: Dict[str, str]¶
Return a map of constructor argument names to secret ids.
eg. {“openai_api_key”: “OPENAI_API_KEY”}
property lc_serializable: bool¶
Return whether or not the class is serializable.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶ | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html |
0e4fc7241bb9-8 | Configuration for this pydantic object.
arbitrary_types_allowed = True¶
extra = 'forbid'¶ | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseChain.html |
58124ee1e836-0 | langchain_experimental.sql.base.SQLDatabaseSequentialChain¶
class langchain_experimental.sql.base.SQLDatabaseSequentialChain(*, memory: Optional[BaseMemory] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, callback_manager: Optional[BaseCallbackManager] = None, verbose: bool = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, decider_chain: LLMChain, sql_chain: SQLDatabaseChain, input_key: str = 'query', output_key: str = 'result', return_intermediate_steps: bool = False)[source]¶
Bases: Chain
Chain for querying SQL database that is a sequential chain.
The chain is as follows:
1. Based on the query, determine which tables to use.
2. Based on those tables, call the normal SQL database chain.
This is useful in cases where the number of tables in the database is large.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param callback_manager: Optional[BaseCallbackManager] = None¶
Deprecated, use callbacks instead.
param callbacks: Callbacks = None¶
Optional list of callback handlers (or callback manager). Defaults to None.
Callback handlers are called throughout the lifecycle of a call to a chain,
starting with on_chain_start, ending with on_chain_end or on_chain_error.
Each custom chain can optionally call additional callback methods, see Callback docs
for full details.
param decider_chain: LLMChain [Required]¶
param memory: Optional[BaseMemory] = None¶
Optional memory object. Defaults to None.
Memory is a class that gets called at the start
and at the end of every chain. At the start, memory loads variables and passes | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html |
58124ee1e836-1 | and at the end of every chain. At the start, memory loads variables and passes
them along in the chain. At the end, it saves any returned variables.
There are many different types of memory - please see memory docs
for the full catalog.
param metadata: Optional[Dict[str, Any]] = None¶
Optional metadata associated with the chain. Defaults to None.
This metadata will be associated with each call to this chain,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a chain with its use case.
param return_intermediate_steps: bool = False¶
param sql_chain: SQLDatabaseChain [Required]¶
param tags: Optional[List[str]] = None¶
Optional list of tags associated with the chain. Defaults to None.
These tags will be associated with each call to this chain,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a chain with its use case.
param verbose: bool [Optional]¶
Whether or not run in verbose mode. In verbose mode, some intermediate logs
will be printed to the console. Defaults to langchain.verbose value.
__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, include_run_info: bool = False) → Dict[str, Any]¶
Execute the chain.
Parameters
inputs – Dictionary of inputs, or single input if chain expects
only one param. Should contain all inputs specified in
Chain.input_keys except for inputs that will be set by the chain’s
memory.
return_only_outputs – Whether to return only outputs in the | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html |
58124ee1e836-2 | memory.
return_only_outputs – Whether to return only outputs in the
response. If True, only new keys generated by this chain will be
returned. If False, both input keys and new keys generated by this
chain will be returned. Defaults to False.
callbacks – Callbacks to use for this chain run. These will be called in
addition to callbacks passed to the chain during construction, but only
these runtime callbacks will propagate to calls to other objects.
tags – List of string tags to pass to all callbacks. These will be passed in
addition to tags passed to the chain during construction, but only
these runtime tags will propagate to calls to other objects.
metadata – Optional metadata associated with the chain. Defaults to None
include_run_info – Whether to include run info in the response. Defaults
to False.
Returns
A dict of named outputs. Should contain all outputs specified inChain.output_keys.
async acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, include_run_info: bool = False) → Dict[str, Any]¶
Asynchronously execute the chain.
Parameters
inputs – Dictionary of inputs, or single input if chain expects
only one param. Should contain all inputs specified in
Chain.input_keys except for inputs that will be set by the chain’s
memory.
return_only_outputs – Whether to return only outputs in the
response. If True, only new keys generated by this chain will be
returned. If False, both input keys and new keys generated by this
chain will be returned. Defaults to False.
callbacks – Callbacks to use for this chain run. These will be called in | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html |
58124ee1e836-3 | callbacks – Callbacks to use for this chain run. These will be called in
addition to callbacks passed to the chain during construction, but only
these runtime callbacks will propagate to calls to other objects.
tags – List of string tags to pass to all callbacks. These will be passed in
addition to tags passed to the chain during construction, but only
these runtime tags will propagate to calls to other objects.
metadata – Optional metadata associated with the chain. Defaults to None
include_run_info – Whether to include run info in the response. Defaults
to False.
Returns
A dict of named outputs. Should contain all outputs specified inChain.output_keys.
async ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None) → Dict[str, Any]¶
apply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → List[Dict[str, str]]¶
Call the chain on all inputs in the list.
async arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) → Any¶
Convenience method for executing chain.
The main difference between this method and Chain.__call__ is that this
method expects inputs to be passed directly in as positional arguments or
keyword arguments, whereas Chain.__call__ expects a single input dictionary
with all the inputs
Parameters
*args – If the chain expects a single input, it can be passed in as the
sole positional argument.
callbacks – Callbacks to use for this chain run. These will be called in
addition to callbacks passed to the chain during construction, but only
these runtime callbacks will propagate to calls to other objects. | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html |
58124ee1e836-4 | these runtime callbacks will propagate to calls to other objects.
tags – List of string tags to pass to all callbacks. These will be passed in
addition to tags passed to the chain during construction, but only
these runtime tags will propagate to calls to other objects.
**kwargs – If the chain expects multiple inputs, they can be passed in
directly as keyword arguments.
Returns
The chain output.
Example
# Suppose we have a single-input chain that takes a 'question' string:
await chain.arun("What's the temperature in Boise, Idaho?")
# -> "The temperature in Boise is..."
# Suppose we have a multi-input chain that takes a 'question' string
# and 'context' string:
question = "What's the temperature in Boise, Idaho?"
context = "Weather report for Boise, Idaho on 07/03/23..."
await chain.arun(question=question, context=context)
# -> "The temperature in Boise is..."
dict(**kwargs: Any) → Dict¶
Dictionary representation of chain.
Expects Chain._chain_type property to be implemented and for memory to benull.
Parameters
**kwargs – Keyword arguments passed to default pydantic.BaseModel.dict
method.
Returns
A dictionary representation of the chain.
Example
..code-block:: python
chain.dict(exclude_unset=True)
# -> {“_type”: “foo”, “verbose”: False, …} | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html |
58124ee1e836-5 | # -> {“_type”: “foo”, “verbose”: False, …}
classmethod from_llm(llm: BaseLanguageModel, database: SQLDatabase, query_prompt: BasePromptTemplate = PromptTemplate(input_variables=['input', 'table_info', 'dialect', 'top_k'], output_parser=None, partial_variables={}, template='Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer. Unless the user specifies in his question a specific number of examples he wishes to obtain, always limit your query to at most {top_k} results. You can order the results by a relevant column to return the most interesting examples in the database.\n\nNever query for all the columns from a specific table, only ask for a the few relevant columns given the question.\n\nPay attention to use only the column names that you can see in the schema description. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.\n\nUse the following format:\n\nQuestion: Question here\nSQLQuery: SQL Query to run\nSQLResult: Result of the SQLQuery\nAnswer: Final answer here\n\nOnly use the following tables:\n{table_info}\n\nQuestion: {input}', template_format='f-string', validate_template=True), decider_prompt: BasePromptTemplate = PromptTemplate(input_variables=['query', 'table_names'], output_parser=CommaSeparatedListOutputParser(), partial_variables={}, template='Given the below input question and list of potential tables, output a comma separated list of the table names that may be necessary to answer this question.\n\nQuestion: {query}\n\nTable Names: {table_names}\n\nRelevant Table Names:', template_format='f-string', validate_template=True), **kwargs: Any) → SQLDatabaseSequentialChain[source]¶ | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html |
58124ee1e836-6 | Load the necessary chains.
invoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None) → Dict[str, Any]¶
prep_inputs(inputs: Union[Dict[str, Any], Any]) → Dict[str, str]¶
Validate and prepare chain inputs, including adding inputs from memory.
Parameters
inputs – Dictionary of raw inputs, or single input if chain expects
only one param. Should contain all inputs specified in
Chain.input_keys except for inputs that will be set by the chain’s
memory.
Returns
A dictionary of all inputs, including those added by the chain’s memory.
prep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) → Dict[str, str]¶
Validate and prepare chain outputs, and save info about this run to memory.
Parameters
inputs – Dictionary of chain inputs, including any inputs added by chain
memory.
outputs – Dictionary of initial chain outputs.
return_only_outputs – Whether to only return the chain outputs. If False,
inputs are also added to the final outputs.
Returns
A dict of the final chain outputs.
validator raise_callback_manager_deprecation » all fields¶
Raise deprecation warning if callback_manager is used.
run(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) → Any¶
Convenience method for executing chain.
The main difference between this method and Chain.__call__ is that this
method expects inputs to be passed directly in as positional arguments or
keyword arguments, whereas Chain.__call__ expects a single input dictionary
with all the inputs
Parameters
*args – If the chain expects a single input, it can be passed in as the | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html |
58124ee1e836-7 | *args – If the chain expects a single input, it can be passed in as the
sole positional argument.
callbacks – Callbacks to use for this chain run. These will be called in
addition to callbacks passed to the chain during construction, but only
these runtime callbacks will propagate to calls to other objects.
tags – List of string tags to pass to all callbacks. These will be passed in
addition to tags passed to the chain during construction, but only
these runtime tags will propagate to calls to other objects.
**kwargs – If the chain expects multiple inputs, they can be passed in
directly as keyword arguments.
Returns
The chain output.
Example
# Suppose we have a single-input chain that takes a 'question' string:
chain.run("What's the temperature in Boise, Idaho?")
# -> "The temperature in Boise is..."
# Suppose we have a multi-input chain that takes a 'question' string
# and 'context' string:
question = "What's the temperature in Boise, Idaho?"
context = "Weather report for Boise, Idaho on 07/03/23..."
chain.run(question=question, context=context)
# -> "The temperature in Boise is..."
save(file_path: Union[Path, str]) → None¶
Save the chain.
Expects Chain._chain_type property to be implemented and for memory to benull.
Parameters
file_path – Path to file to save the chain to.
Example
chain.save(file_path="path/chain.yaml")
validator set_verbose » verbose¶
Set the chain verbosity.
Defaults to the global setting if not specified by the user.
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
to_json_not_implemented() → SerializedNotImplemented¶
property lc_attributes: Dict¶
Return a list of attribute names that should be included in the | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html |
58124ee1e836-8 | property lc_attributes: Dict¶
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]¶
Return the namespace of the langchain object.
eg. [“langchain”, “llms”, “openai”]
property lc_secrets: Dict[str, str]¶
Return a map of constructor argument names to secret ids.
eg. {“openai_api_key”: “OPENAI_API_KEY”}
property lc_serializable: bool¶
Return whether or not the class is serializable.
model Config¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶ | https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.