id
stringlengths
14
15
text
stringlengths
49
2.47k
source
stringlengths
61
166
7bf0abc60dd5-3
Performs an arxiv search and A single string with the publish date, title, authors, and summary for each article separated by two newlines. If an error occurs or no documents found, error text is returned instead. Wrapper for https://lukasschwab.me/arxiv.py/index.html#Search Parameters query – a plaintext search query classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using ArxivAPIWrapper¶ ArXiv API Tool
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.arxiv.ArxivAPIWrapper.html
f9f06cbe81e9-0
langchain.utilities.github.GitHubAPIWrapper¶ class langchain.utilities.github.GitHubAPIWrapper[source]¶ Bases: BaseModel Wrapper for GitHub 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 github_app_id: Optional[str] = None¶ param github_app_private_key: Optional[str] = None¶ param github_base_branch: Optional[str] = None¶ param github_branch: Optional[str] = None¶ param github_repository: Optional[str] = None¶ comment_on_issue(comment_query: str) → str[source]¶ Adds a comment to a github issue Parameters: comment_query(str): a string which contains the issue number, two newlines, and the comment. for example: “1 Working on it now” adds the comment “working on it now” to issue 1 Returns:str: A success or failure message classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.github.GitHubAPIWrapper.html
f9f06cbe81e9-1
exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance create_file(file_query: str) → str[source]¶ Creates a new file on the Github repo Parameters: file_query(str): a string which contains the file path and the file contents. The file path is the first line in the string, and the contents are the rest of the string. For example, “hello_world.md # Hello World!” Returns:str: A success or failure message create_pull_request(pr_query: str) → str[source]¶ Makes a pull request from the bot’s branch to the base branch Parameters: pr_query(str): a string which contains the PR title and the PR body. The title is the first line in the string, and the body are the rest of the string. For example, “Updated README made changes to add info” Returns:str: A success or failure message delete_file(file_path: str) → str[source]¶ Deletes a file from the repo :param file_path: Where the file is :type file_path: str Returns Success or failure message Return type str dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.github.GitHubAPIWrapper.html
f9f06cbe81e9-2
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶ get_issue(issue_number: int) → Dict[str, Any][source]¶ Fetches a specific issue and its first 10 comments :param issue_number: The number for the github issue :type issue_number: int Returns A doctionary containing the issue’s title, body, and comments as a string Return type dict get_issues() → str[source]¶ Fetches all open issues from the repo Returns A plaintext report containing the number of issues and each issue’s title and number. Return type str json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ parse_issues(issues: List[Issue]) → List[dict][source]¶ Extracts title and number from each Issue and puts them in a dictionary :param issues: A list of Github Issue objects :type issues: List[Issue] Returns A dictionary of issue titles and numbers
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.github.GitHubAPIWrapper.html
f9f06cbe81e9-3
:type issues: List[Issue] Returns A dictionary of issue titles and numbers Return type List[dict] classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ read_file(file_path: str) → str[source]¶ Reads a file from the github repo :param file_path: the file path :type file_path: str Returns The file decoded as a string Return type str run(mode: str, query: str) → str[source]¶ classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ update_file(file_query: str) → str[source]¶ Updates a file with new content. :param file_query: Contains the file path and the file contents. The old file contents is wrapped in OLD <<<< and >>>> OLD The new file contents is wrapped in NEW <<<< and >>>> NEW For example: /test/hello.txt OLD <<<< Hello Earth! >>>> OLD NEW <<<< Hello Mars! >>>> NEW Returns A success or failure message classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using GitHubAPIWrapper¶ Github Toolkit
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.github.GitHubAPIWrapper.html
f96a71bb1e98-0
langchain.utilities.twilio.TwilioAPIWrapper¶ class langchain.utilities.twilio.TwilioAPIWrapper[source]¶ Bases: 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') 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 account_sid: Optional[str] = None¶ Twilio account string identifier. param auth_token: Optional[str] = None¶ Twilio auth token. param 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.
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.twilio.TwilioAPIWrapper.html
f96a71bb1e98-1
cell phone number. If you are using messaging_service_sid, this parameter must be empty. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.twilio.TwilioAPIWrapper.html
f96a71bb1e98-2
classmethod from_orm(obj: Any) → Model¶ json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ run(body: str, to: str) → str[source]¶ Run body through Twilio and respond with message sid. Parameters body – The text of the message you want to send. Can be up to 1,600 characters in length. to – The destination phone number in [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.
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.twilio.TwilioAPIWrapper.html
f96a71bb1e98-3
for other 3rd-party channels. classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using TwilioAPIWrapper¶ Twilio
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.twilio.TwilioAPIWrapper.html
2ca12f8f336e-0
langchain.utilities.scenexplain.SceneXplainAPIWrapper¶ class langchain.utilities.scenexplain.SceneXplainAPIWrapper[source]¶ Bases: BaseSettings, BaseModel Wrapper for SceneXplain API. In order to set this up, you need API key for the SceneXplain API. You can obtain a key by following the steps below. - Sign up for a free account at https://scenex.jina.ai/. - Navigate to the API Access page (https://scenex.jina.ai/api) and create a new API key. 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 scenex_api_key: str [Required]¶ param scenex_api_url: str = 'https://api.scenex.jina.ai/v1/describe'¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.scenexplain.SceneXplainAPIWrapper.html
2ca12f8f336e-1
the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶ json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.scenexplain.SceneXplainAPIWrapper.html
2ca12f8f336e-2
run(image: str) → str[source]¶ Run SceneXplain image explainer. classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.scenexplain.SceneXplainAPIWrapper.html
1004299b087e-0
langchain.utilities.loading.try_load_from_hub¶ langchain.utilities.loading.try_load_from_hub(path: Union[str, Path], loader: Callable[[str], T], valid_prefix: str, valid_suffixes: Set[str], **kwargs: Any) → Optional[T][source]¶ Load configuration from hub. Returns None if path is not a hub path.
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.loading.try_load_from_hub.html
a5e0c3279cd7-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
4201253defb5-0
langchain.utilities.graphql.GraphQLAPIWrapper¶ class langchain.utilities.graphql.GraphQLAPIWrapper[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]¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.graphql.GraphQLAPIWrapper.html
4201253defb5-1
deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶ json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ run(query: str) → str[source]¶
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.graphql.GraphQLAPIWrapper.html
4201253defb5-2
run(query: str) → str[source]¶ Run a GraphQL query and get the results. classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using GraphQLAPIWrapper¶ GraphQL tool
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.graphql.GraphQLAPIWrapper.html
f9195d6fa8d0-0
langchain.utilities.sql_database.SQLDatabase¶ class langchain.utilities.sql_database.SQLDatabase(engine: Engine, schema: Optional[str] = None, metadata: Optional[MetaData] = None, ignore_tables: Optional[List[str]] = None, include_tables: Optional[List[str]] = None, sample_rows_in_table_info: int = 3, indexes_in_table_info: bool = False, custom_table_info: Optional[dict] = None, view_support: bool = False, max_string_length: int = 300)[source]¶ SQLAlchemy wrapper around a database. Create engine from database URI. Attributes dialect Return string representation of dialect to use. table_info Information about all tables in the database. Methods __init__(engine[, schema, metadata, ...]) Create engine from database URI. from_cnosdb([url, user, password, tenant, ...]) Class method to create an SQLDatabase instance from a CnosDB connection. from_databricks(catalog, schema[, host, ...]) Class method to create an SQLDatabase instance from a Databricks connection. from_uri(database_uri[, engine_args]) Construct a SQLAlchemy engine from URI. get_table_info([table_names]) Get information about specified tables. get_table_info_no_throw([table_names]) Get information about specified tables. get_table_names() Get names of tables available. get_usable_table_names() Get names of tables available. run(command[, fetch]) Execute a SQL command and return a string representing the results. run_no_throw(command[, fetch]) Execute a SQL command and return a string representing the results.
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.sql_database.SQLDatabase.html
f9195d6fa8d0-1
Execute a SQL command and return a string representing the results. __init__(engine: Engine, schema: Optional[str] = None, metadata: Optional[MetaData] = None, ignore_tables: Optional[List[str]] = None, include_tables: Optional[List[str]] = None, sample_rows_in_table_info: int = 3, indexes_in_table_info: bool = False, custom_table_info: Optional[dict] = None, view_support: bool = False, max_string_length: int = 300)[source]¶ Create engine from database URI. classmethod from_cnosdb(url: str = '127.0.0.1:8902', user: str = 'root', password: str = '', tenant: str = 'cnosdb', database: str = 'public') → SQLDatabase[source]¶ Class method to create an SQLDatabase instance from a CnosDB connection. This method requires the ‘cnos-connector’ package. If not installed, it can be added using pip install cnos-connector. Parameters url (str) – The HTTP connection host name and port number of the CnosDB service, excluding “http://” or “https://”, with a default value of “127.0.0.1:8902”. user (str) – The username used to connect to the CnosDB service, with a default value of “root”. password (str) – The password of the user connecting to the CnosDB service, with a default value of “”. tenant (str) – The name of the tenant used to connect to the CnosDB service, with a default value of “cnosdb”. database (str) – The name of the database in the CnosDB tenant. Returns An instance of SQLDatabase configured with the provided CnosDB connection details. Return type SQLDatabase
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.sql_database.SQLDatabase.html
f9195d6fa8d0-2
CnosDB connection details. Return type SQLDatabase classmethod from_databricks(catalog: str, schema: str, host: Optional[str] = None, api_token: Optional[str] = None, warehouse_id: Optional[str] = None, cluster_id: Optional[str] = None, engine_args: Optional[dict] = None, **kwargs: Any) → SQLDatabase[source]¶ Class method to create an SQLDatabase instance from a Databricks connection. This method requires the ‘databricks-sql-connector’ package. If not installed, it can be added using pip install databricks-sql-connector. Parameters catalog (str) – The catalog name in the Databricks database. schema (str) – The schema name in the catalog. host (Optional[str]) – The Databricks workspace hostname, excluding ‘https://’ part. If not provided, it attempts to fetch from the environment variable ‘DATABRICKS_HOST’. If still unavailable and if running in a Databricks notebook, it defaults to the current workspace hostname. Defaults to None. api_token (Optional[str]) – The Databricks personal access token for accessing the Databricks SQL warehouse or the cluster. If not provided, it attempts to fetch from ‘DATABRICKS_TOKEN’. If still unavailable and running in a Databricks notebook, a temporary token for the current user is generated. Defaults to None. warehouse_id (Optional[str]) – The warehouse ID in the Databricks SQL. If provided, the method configures the connection to use this warehouse. Cannot be used with ‘cluster_id’. Defaults to None. cluster_id (Optional[str]) – The cluster ID in the Databricks Runtime. If provided, the method configures the connection to use this cluster.
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.sql_database.SQLDatabase.html
f9195d6fa8d0-3
provided, the method configures the connection to use this cluster. Cannot be used with ‘warehouse_id’. If running in a Databricks notebook and both ‘warehouse_id’ and ‘cluster_id’ are None, it uses the ID of the cluster the notebook is attached to. Defaults to None. engine_args (Optional[dict]) – The arguments to be used when connecting Databricks. Defaults to None. **kwargs (Any) – Additional keyword arguments for the from_uri method. Returns An instance of SQLDatabase configured with the providedDatabricks connection details. Return type SQLDatabase Raises ValueError – If ‘databricks-sql-connector’ is not found, or if both ‘warehouse_id’ and ‘cluster_id’ are provided, or if neither ‘warehouse_id’ nor ‘cluster_id’ are provided and it’s not executing inside a Databricks notebook. classmethod from_uri(database_uri: str, engine_args: Optional[dict] = None, **kwargs: Any) → SQLDatabase[source]¶ Construct a SQLAlchemy engine from URI. get_table_info(table_names: Optional[List[str]] = None) → str[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. get_table_info_no_throw(table_names: Optional[List[str]] = None) → str[source]¶ Get information about specified tables. Follows best practices as specified in: Rajkumar et al, 2022 (https://arxiv.org/abs/2204.00498)
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.sql_database.SQLDatabase.html
f9195d6fa8d0-4
(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. get_table_names() → Iterable[str][source]¶ Get names of tables available. get_usable_table_names() → Iterable[str][source]¶ Get names of tables available. run(command: str, fetch: str = 'all') → str[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. run_no_throw(command: str, fetch: str = 'all') → str[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. Examples using SQLDatabase¶ Rebuff SQL Database Agent SQL Query
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.sql_database.SQLDatabase.html
c507d2bd769b-0
langchain.utilities.serpapi.SerpAPIWrapper¶ class langchain.utilities.serpapi.SerpAPIWrapper[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. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.serpapi.SerpAPIWrapper.html
c507d2bd769b-1
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶ get_params(query: str) → Dict[str, str][source]¶ Get parameters for SerpAPI.
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.serpapi.SerpAPIWrapper.html
c507d2bd769b-2
Get parameters for SerpAPI. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ 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. classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns.
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.serpapi.SerpAPIWrapper.html
c507d2bd769b-3
Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using SerpAPIWrapper¶ SerpAPI AutoGPT
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.serpapi.SerpAPIWrapper.html
c4687e02880d-0
langchain.utilities.google_serper.GoogleSerperAPIWrapper¶ class langchain.utilities.google_serper.GoogleSerperAPIWrapper[source]¶ Bases: 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() 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 gl: str = 'us'¶ param hl: str = 'en'¶ param k: int = 10¶ param serper_api_key: Optional[str] = None¶ param tbs: Optional[str] = None¶ param type: Literal['news', 'search', 'places', 'images'] = 'search'¶ async aresults(query: str, **kwargs: Any) → Dict[source]¶ Run query through GoogleSearch. async arun(query: str, **kwargs: Any) → str[source]¶ Run query through GoogleSearch and parse result async. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.google_serper.GoogleSerperAPIWrapper.html
c4687e02880d-1
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.google_serper.GoogleSerperAPIWrapper.html
c4687e02880d-2
classmethod from_orm(obj: Any) → Model¶ json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ results(query: str, **kwargs: Any) → Dict[source]¶ Run query through GoogleSearch. run(query: str, **kwargs: Any) → str[source]¶ Run query through GoogleSearch and parse result. classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns.
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.google_serper.GoogleSerperAPIWrapper.html
c4687e02880d-3
Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using GoogleSerperAPIWrapper¶ Google Serper API Google Serper Retrieve as you generate with FLARE FLARE
https://api.python.langchain.com/en/latest/utilities/langchain.utilities.google_serper.GoogleSerperAPIWrapper.html
efe5e61e4f5f-0
langchain.cache.SQLAlchemyCache¶ class langchain.cache.SQLAlchemyCache(engine: ~sqlalchemy.engine.base.Engine, cache_schema: ~typing.Type[~langchain.cache.FullLLMCache] = <class 'langchain.cache.FullLLMCache'>)[source]¶ Cache that uses SQAlchemy as a backend. Initialize by creating all tables. Methods __init__(engine[, cache_schema]) Initialize by creating all tables. clear(**kwargs) Clear cache. lookup(prompt, llm_string) Look up based on prompt and llm_string. update(prompt, llm_string, return_val) Update based on prompt and llm_string. __init__(engine: ~sqlalchemy.engine.base.Engine, cache_schema: ~typing.Type[~langchain.cache.FullLLMCache] = <class 'langchain.cache.FullLLMCache'>)[source]¶ Initialize by creating all tables. clear(**kwargs: Any) → None[source]¶ Clear cache. lookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]][source]¶ Look up based on prompt and llm_string. update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None[source]¶ Update based on prompt and llm_string. Examples using SQLAlchemyCache¶ Caching integrations
https://api.python.langchain.com/en/latest/cache/langchain.cache.SQLAlchemyCache.html
22657d706a8c-0
langchain.cache.InMemoryCache¶ class langchain.cache.InMemoryCache[source]¶ Cache that stores things in memory. Initialize with empty cache. Methods __init__() Initialize with empty cache. clear(**kwargs) Clear cache. lookup(prompt, llm_string) Look up based on prompt and llm_string. update(prompt, llm_string, return_val) Update cache based on prompt and llm_string. __init__() → None[source]¶ Initialize with empty cache. clear(**kwargs: Any) → None[source]¶ Clear cache. lookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]][source]¶ Look up based on prompt and llm_string. update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None[source]¶ Update cache based on prompt and llm_string. Examples using InMemoryCache¶ Caching integrations
https://api.python.langchain.com/en/latest/cache/langchain.cache.InMemoryCache.html
b2999fb75fb7-0
langchain.cache.FullLLMCache¶ class langchain.cache.FullLLMCache(**kwargs)[source]¶ SQLite table for full LLM Cache (all generations). A simple constructor that allows initialization from kwargs. Sets attributes on the constructed instance using the names and values in kwargs. Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships. Attributes idx llm metadata prompt registry response Methods __init__(**kwargs) A simple constructor that allows initialization from kwargs. __init__(**kwargs)¶ A simple constructor that allows initialization from kwargs. Sets attributes on the constructed instance using the names and values in kwargs. Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
https://api.python.langchain.com/en/latest/cache/langchain.cache.FullLLMCache.html
d4afd764474c-0
langchain.cache.MomentoCache¶ class langchain.cache.MomentoCache(cache_client: momento.CacheClient, cache_name: str, *, ttl: Optional[timedelta] = None, ensure_cache_exists: bool = True)[source]¶ Cache that uses Momento as a backend. See https://gomomento.com/ Instantiate a prompt cache using Momento as a backend. Note: to instantiate the cache client passed to MomentoCache, you must have a Momento account. See https://gomomento.com/. Parameters cache_client (CacheClient) – The Momento cache client. cache_name (str) – The name of the cache to use to store the data. ttl (Optional[timedelta], optional) – The time to live for the cache items. Defaults to None, ie use the client default TTL. ensure_cache_exists (bool, optional) – Create the cache if it doesn’t exist. Defaults to True. Raises ImportError – Momento python package is not installed. TypeError – cache_client is not of type momento.CacheClientObject ValueError – ttl is non-null and non-negative Methods __init__(cache_client, cache_name, *[, ttl, ...]) Instantiate a prompt cache using Momento as a backend. clear(**kwargs) Clear the cache. from_client_params(cache_name, ttl, *[, ...]) Construct cache from CacheClient parameters. lookup(prompt, llm_string) Lookup llm generations in cache by prompt and associated model and settings. update(prompt, llm_string, return_val) Store llm generations in cache. __init__(cache_client: momento.CacheClient, cache_name: str, *, ttl: Optional[timedelta] = None, ensure_cache_exists: bool = True)[source]¶
https://api.python.langchain.com/en/latest/cache/langchain.cache.MomentoCache.html
d4afd764474c-1
Instantiate a prompt cache using Momento as a backend. Note: to instantiate the cache client passed to MomentoCache, you must have a Momento account. See https://gomomento.com/. Parameters cache_client (CacheClient) – The Momento cache client. cache_name (str) – The name of the cache to use to store the data. ttl (Optional[timedelta], optional) – The time to live for the cache items. Defaults to None, ie use the client default TTL. ensure_cache_exists (bool, optional) – Create the cache if it doesn’t exist. Defaults to True. Raises ImportError – Momento python package is not installed. TypeError – cache_client is not of type momento.CacheClientObject ValueError – ttl is non-null and non-negative clear(**kwargs: Any) → None[source]¶ Clear the cache. Raises SdkException – Momento service or network error classmethod from_client_params(cache_name: str, ttl: timedelta, *, configuration: Optional[momento.config.Configuration] = None, auth_token: Optional[str] = None, **kwargs: Any) → MomentoCache[source]¶ Construct cache from CacheClient parameters. lookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]][source]¶ Lookup llm generations in cache by prompt and associated model and settings. Parameters prompt (str) – The prompt run through the language model. llm_string (str) – The language model version and settings. Raises SdkException – Momento service or network error Returns A list of language model generations. Return type Optional[RETURN_VAL_TYPE] update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None[source]¶ Store llm generations in cache. Parameters
https://api.python.langchain.com/en/latest/cache/langchain.cache.MomentoCache.html
d4afd764474c-2
Store llm generations in cache. Parameters prompt (str) – The prompt run through the language model. llm_string (str) – The language model string. return_val (RETURN_VAL_TYPE) – A list of language model generations. Raises SdkException – Momento service or network error Exception – Unexpected response Examples using MomentoCache¶ Momento Caching integrations
https://api.python.langchain.com/en/latest/cache/langchain.cache.MomentoCache.html
a43d1ff54d8c-0
langchain.cache.BaseCache¶ class langchain.cache.BaseCache[source]¶ Base interface for cache. Methods __init__() clear(**kwargs) Clear cache that can take additional keyword arguments. lookup(prompt, llm_string) Look up based on prompt and llm_string. update(prompt, llm_string, return_val) Update cache based on prompt and llm_string. __init__()¶ abstract clear(**kwargs: Any) → None[source]¶ Clear cache that can take additional keyword arguments. abstract lookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]][source]¶ Look up based on prompt and llm_string. abstract update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None[source]¶ Update cache based on prompt and llm_string.
https://api.python.langchain.com/en/latest/cache/langchain.cache.BaseCache.html
757289e3eae2-0
langchain.cache.SQLiteCache¶ class langchain.cache.SQLiteCache(database_path: str = '.langchain.db')[source]¶ Cache that uses SQLite as a backend. Initialize by creating the engine and all tables. Methods __init__([database_path]) Initialize by creating the engine and all tables. clear(**kwargs) Clear cache. lookup(prompt, llm_string) Look up based on prompt and llm_string. update(prompt, llm_string, return_val) Update based on prompt and llm_string. __init__(database_path: str = '.langchain.db')[source]¶ Initialize by creating the engine and all tables. clear(**kwargs: Any) → None¶ Clear cache. lookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]]¶ Look up based on prompt and llm_string. update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None¶ Update based on prompt and llm_string. Examples using SQLiteCache¶ Caching integrations
https://api.python.langchain.com/en/latest/cache/langchain.cache.SQLiteCache.html
fe44da6a2d2f-0
langchain.cache.GPTCache¶ class langchain.cache.GPTCache(init_func: Optional[Union[Callable[[Any, str], None], Callable[[Any], None]]] = None)[source]¶ Cache that uses GPTCache as a backend. Initialize by passing in init function (default: None). Parameters init_func (Optional[Callable[[Any], None]]) – init GPTCache function (default – None) Example: .. code-block:: python # Initialize GPTCache with a custom init function import gptcache from gptcache.processor.pre import get_prompt from gptcache.manager.factory import get_data_manager # Avoid multiple caches using the same file, causing different llm model caches to affect each other def init_gptcache(cache_obj: gptcache.Cache, llm str): cache_obj.init(pre_embedding_func=get_prompt, data_manager=manager_factory( manager=”map”, data_dir=f”map_cache_{llm}” ), ) langchain.llm_cache = GPTCache(init_gptcache) Methods __init__([init_func]) Initialize by passing in init function (default: None). clear(**kwargs) Clear cache. lookup(prompt, llm_string) Look up the cache data. update(prompt, llm_string, return_val) Update cache. __init__(init_func: Optional[Union[Callable[[Any, str], None], Callable[[Any], None]]] = None)[source]¶ Initialize by passing in init function (default: None). Parameters init_func (Optional[Callable[[Any], None]]) – init GPTCache function (default – None) Example: .. code-block:: python # Initialize GPTCache with a custom init function import gptcache from gptcache.processor.pre import get_prompt
https://api.python.langchain.com/en/latest/cache/langchain.cache.GPTCache.html
fe44da6a2d2f-1
import gptcache from gptcache.processor.pre import get_prompt from gptcache.manager.factory import get_data_manager # Avoid multiple caches using the same file, causing different llm model caches to affect each other def init_gptcache(cache_obj: gptcache.Cache, llm str): cache_obj.init(pre_embedding_func=get_prompt, data_manager=manager_factory( manager=”map”, data_dir=f”map_cache_{llm}” ), ) langchain.llm_cache = GPTCache(init_gptcache) clear(**kwargs: Any) → None[source]¶ Clear cache. lookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]][source]¶ Look up the cache data. First, retrieve the corresponding cache object using the llm_string parameter, and then retrieve the data from the cache based on the prompt. update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None[source]¶ Update cache. First, retrieve the corresponding cache object using the llm_string parameter, and then store the prompt and return_val in the cache object. Examples using GPTCache¶ Caching integrations
https://api.python.langchain.com/en/latest/cache/langchain.cache.GPTCache.html
077f2ccfcf61-0
langchain.cache.RedisSemanticCache¶ class langchain.cache.RedisSemanticCache(redis_url: str, embedding: Embeddings, score_threshold: float = 0.2)[source]¶ Cache that uses Redis as a vector-store backend. Initialize by passing in the init GPTCache func Parameters redis_url (str) – URL to connect to Redis. embedding (Embedding) – Embedding provider for semantic encoding and search. score_threshold (float, 0.2) – Example: import langchain from langchain.cache import RedisSemanticCache from langchain.embeddings import OpenAIEmbeddings langchain.llm_cache = RedisSemanticCache( redis_url="redis://localhost:6379", embedding=OpenAIEmbeddings() ) Methods __init__(redis_url, embedding[, score_threshold]) Initialize by passing in the init GPTCache func clear(**kwargs) Clear semantic cache for a given llm_string. lookup(prompt, llm_string) Look up based on prompt and llm_string. update(prompt, llm_string, return_val) Update cache based on prompt and llm_string. __init__(redis_url: str, embedding: Embeddings, score_threshold: float = 0.2)[source]¶ Initialize by passing in the init GPTCache func Parameters redis_url (str) – URL to connect to Redis. embedding (Embedding) – Embedding provider for semantic encoding and search. score_threshold (float, 0.2) – Example: import langchain from langchain.cache import RedisSemanticCache from langchain.embeddings import OpenAIEmbeddings langchain.llm_cache = RedisSemanticCache( redis_url="redis://localhost:6379", embedding=OpenAIEmbeddings() )
https://api.python.langchain.com/en/latest/cache/langchain.cache.RedisSemanticCache.html
077f2ccfcf61-1
embedding=OpenAIEmbeddings() ) clear(**kwargs: Any) → None[source]¶ Clear semantic cache for a given llm_string. lookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]][source]¶ Look up based on prompt and llm_string. update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None[source]¶ Update cache based on prompt and llm_string. Examples using RedisSemanticCache¶ Redis Caching integrations
https://api.python.langchain.com/en/latest/cache/langchain.cache.RedisSemanticCache.html
755fec6b6cd5-0
langchain.cache.RedisCache¶ class langchain.cache.RedisCache(redis_: Any)[source]¶ Cache that uses Redis as a backend. Initialize by passing in Redis instance. Methods __init__(redis_) Initialize by passing in Redis instance. clear(**kwargs) Clear cache. lookup(prompt, llm_string) Look up based on prompt and llm_string. update(prompt, llm_string, return_val) Update cache based on prompt and llm_string. __init__(redis_: Any)[source]¶ Initialize by passing in Redis instance. clear(**kwargs: Any) → None[source]¶ Clear cache. If asynchronous is True, flush asynchronously. lookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]][source]¶ Look up based on prompt and llm_string. update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None[source]¶ Update cache based on prompt and llm_string. Examples using RedisCache¶ Redis Caching integrations
https://api.python.langchain.com/en/latest/cache/langchain.cache.RedisCache.html
3383f7b428bf-0
langchain.docstore.in_memory.InMemoryDocstore¶ class langchain.docstore.in_memory.InMemoryDocstore(_dict: Optional[Dict[str, Document]] = None)[source]¶ Simple in memory docstore in the form of a dict. Initialize with dict. Methods __init__([_dict]) Initialize with dict. add(texts) Add texts to in memory dictionary. delete(ids) Deleting IDs from in memory dictionary. search(search) Search via direct lookup. __init__(_dict: Optional[Dict[str, Document]] = None)[source]¶ Initialize with dict. add(texts: Dict[str, Document]) → None[source]¶ Add texts to in memory dictionary. Parameters texts – dictionary of id -> document. Returns None delete(ids: List) → None[source]¶ Deleting IDs from in memory dictionary. search(search: str) → Union[str, Document][source]¶ Search via direct lookup. Parameters search – id of a document to search for. Returns Document if found, else error message. Examples using InMemoryDocstore¶ Annoy AutoGPT BabyAGI User Guide BabyAGI with Tools !pip install bs4 Generative Agents in LangChain
https://api.python.langchain.com/en/latest/docstore/langchain.docstore.in_memory.InMemoryDocstore.html
0830de398c88-0
langchain.docstore.arbitrary_fn.DocstoreFn¶ class langchain.docstore.arbitrary_fn.DocstoreFn(lookup_fn: Callable[[str], Union[Document, str]])[source]¶ Langchain Docstore via arbitrary lookup function. This is useful when: it’s expensive to construct an InMemoryDocstore/dict you retrieve documents from remote sources you just want to reuse existing objects Methods __init__(lookup_fn) delete(ids) Deleting IDs from in memory dictionary. search(search) Search for a document. __init__(lookup_fn: Callable[[str], Union[Document, str]])[source]¶ delete(ids: List) → None¶ Deleting IDs from in memory dictionary. search(search: str) → Document[source]¶ Search for a document. Parameters search – search string Returns Document if found, else error message.
https://api.python.langchain.com/en/latest/docstore/langchain.docstore.arbitrary_fn.DocstoreFn.html
d9e21a25bf91-0
langchain.docstore.base.AddableMixin¶ class langchain.docstore.base.AddableMixin[source]¶ Mixin class that supports adding texts. Methods __init__() add(texts) Add more documents. __init__()¶ abstract add(texts: Dict[str, Document]) → None[source]¶ Add more documents.
https://api.python.langchain.com/en/latest/docstore/langchain.docstore.base.AddableMixin.html
7d21293d26d2-0
langchain.docstore.base.Docstore¶ class langchain.docstore.base.Docstore[source]¶ Interface to access to place that stores documents. Methods __init__() delete(ids) Deleting IDs from in memory dictionary. search(search) Search for document. __init__()¶ delete(ids: List) → None[source]¶ Deleting IDs from in memory dictionary. abstract search(search: str) → Union[str, Document][source]¶ Search for document. If page exists, return the page summary, and a Document object. If page does not exist, return similar entries.
https://api.python.langchain.com/en/latest/docstore/langchain.docstore.base.Docstore.html
90f2e8f3d637-0
langchain.docstore.wikipedia.Wikipedia¶ class langchain.docstore.wikipedia.Wikipedia[source]¶ Wrapper around wikipedia API. Check that wikipedia package is installed. Methods __init__() Check that wikipedia package is installed. delete(ids) Deleting IDs from in memory dictionary. search(search) Try to search for wiki page. __init__() → None[source]¶ Check that wikipedia package is installed. delete(ids: List) → None¶ Deleting IDs from in memory dictionary. search(search: str) → Union[str, Document][source]¶ Try to search for wiki page. If page exists, return the page summary, and a PageWithLookups object. If page does not exist, return similar entries. Parameters search – search string. Returns: a Document object or error message.
https://api.python.langchain.com/en/latest/docstore/langchain.docstore.wikipedia.Wikipedia.html
e47904fddb9f-0
langchain.agents.mrkl.base.ZeroShotAgent¶ class langchain.agents.mrkl.base.ZeroShotAgent[source]¶ Bases: Agent Agent for the MRKL chain. 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 allowed_tools: Optional[List[str]] = None¶ param llm_chain: langchain.chains.llm.LLMChain [Required]¶ param output_parser: langchain.agents.agent.AgentOutputParser [Optional]¶ async aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → Union[AgentAction, AgentFinish]¶ Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations callbacks – Callbacks to run. **kwargs – User inputs. Returns Action specifying what tool to use. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model
https://api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ZeroShotAgent.html
e47904fddb9f-1
Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance classmethod create_prompt(tools: Sequence[BaseTool], prefix: str = 'Answer the following questions as best you can. You have access to the following tools:', suffix: str = 'Begin!\n\nQuestion: {input}\nThought:{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables: Optional[List[str]] = None) → PromptTemplate[source]¶ Create prompt in the style of the zero shot agent. Parameters tools – List of tools the agent will have access to, used to format the prompt. prefix – String to put before the list of tools. suffix – String to put after the list of tools. input_variables – List of input variables the final prompt will expect. Returns A PromptTemplate with the template assembled from the pieces here. dict(**kwargs: Any) → Dict¶ Return dictionary representation of agent.
https://api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ZeroShotAgent.html
e47904fddb9f-2
dict(**kwargs: Any) → Dict¶ Return dictionary representation of agent. classmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: str = 'Answer the following questions as best you can. You have access to the following tools:', suffix: str = 'Begin!\n\nQuestion: {input}\nThought:{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables: Optional[List[str]] = None, **kwargs: Any) → Agent[source]¶ Construct an agent from an LLM and tools. classmethod from_orm(obj: Any) → Model¶ get_allowed_tools() → Optional[List[str]]¶ get_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) → Dict[str, Any]¶ Create the full inputs for the LLMChain from intermediate steps.
https://api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ZeroShotAgent.html
e47904fddb9f-3
Create the full inputs for the LLMChain from intermediate steps. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ plan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → Union[AgentAction, AgentFinish]¶ Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations callbacks – Callbacks to run. **kwargs – User inputs. Returns Action specifying what tool to use. return_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) → AgentFinish¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ZeroShotAgent.html
e47904fddb9f-4
Return response when agent has been stopped due to max iterations. save(file_path: Union[Path, str]) → None¶ Save the agent. Parameters file_path – Path to file to save the agent to. Example: .. code-block:: python # If working with agent executor agent.agent.save(file_path=”path/agent.yaml”) classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ tool_run_logging_kwargs() → Dict¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ property llm_prefix: str¶ Prefix to append the llm call with. property observation_prefix: str¶ Prefix to append the observation with. property return_values: List[str]¶ Return values of the agent. Examples using ZeroShotAgent¶ Jina BabyAGI with Tools Adding Message Memory backed by a database to an Agent How to add Memory to an Agent Custom MRKL agent Shared memory across agents and tools
https://api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ZeroShotAgent.html
e741a9c4e676-0
langchain.agents.mrkl.base.ChainConfig¶ class langchain.agents.mrkl.base.ChainConfig(action_name: str, action: Callable, action_description: str)[source]¶ Configuration for chain to use in MRKL system. Parameters action_name – Name of the action. action – Action function to call. action_description – Description of the action. Create new instance of ChainConfig(action_name, action, action_description) Attributes action Alias for field number 1 action_description Alias for field number 2 action_name Alias for field number 0 Methods __init__() count(value, /) Return number of occurrences of value. index(value[, start, stop]) Return first index of value. __init__()¶ count(value, /)¶ Return number of occurrences of value. index(value, start=0, stop=9223372036854775807, /)¶ Return first index of value. Raises ValueError if the value is not present.
https://api.python.langchain.com/en/latest/agents/langchain.agents.mrkl.base.ChainConfig.html
d54094ed3b08-0
langchain.agents.react.base.DocstoreExplorer¶ class langchain.agents.react.base.DocstoreExplorer(docstore: Docstore)[source]¶ Class to assist with exploration of a document store. Initialize with a docstore, and set initial document to None. Methods __init__(docstore) Initialize with a docstore, and set initial document to None. lookup(term) Lookup a term in document (if saved). search(term) Search for a term in the docstore, and if found save. __init__(docstore: Docstore)[source]¶ Initialize with a docstore, and set initial document to None. lookup(term: str) → str[source]¶ Lookup a term in document (if saved). search(term: str) → str[source]¶ Search for a term in the docstore, and if found save. Examples using DocstoreExplorer¶ ReAct document store
https://api.python.langchain.com/en/latest/agents/langchain.agents.react.base.DocstoreExplorer.html
a77bface1779-0
langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent.html
a77bface1779-1
langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent(llm: BaseLanguageModel, toolkit: Optional[PowerBIToolkit] = None, powerbi: Optional[PowerBIDataset] = None, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = 'You are an agent designed to help users interact with a PowerBI Dataset.\n\nAgent has access to a tool that can write a query based on the question and then run those against PowerBI, Microsofts business intelligence tool. The questions from the users should be interpreted as related to the dataset that is available and not general questions about the world. If the question does not seem related to the dataset, return "This does not appear to be part of this dataset." as the answer.\n\nGiven an input question, ask to run the questions against the dataset, then look at the results and return the answer, the answer should be a complete sentence that answers the question, if multiple rows are asked find a way to write that in a easily readable format for a human, also make sure to represent numbers in readable ways, like 1M instead of 1000000. Unless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\n', suffix: str = 'Begin!\n\nQuestion: {input}\nThought: I can first ask which tables I have, then how each table is defined and then ask the query tool the question I need, and finally create a nice sentence that answers the question.\n{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n...
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent.html
a77bface1779-2
Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', examples: Optional[str] = None, input_variables: Optional[List[str]] = None, top_k: int = 10, verbose: bool = False, agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Dict[str, Any]) → AgentExecutor[source]¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent.html
a77bface1779-3
Construct a Power BI agent from an LLM and tools. Examples using create_pbi_agent¶ PowerBI Dataset Agent
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.base.create_pbi_agent.html
2a680e37ce46-0
langchain.agents.react.base.ReActChain¶ class langchain.agents.react.base.ReActChain[source]¶ Bases: AgentExecutor Chain that implements the ReAct paper. Example from langchain import ReActChain, OpenAI react = ReAct(llm=OpenAI()) Initialize with the LLM and a docstore. param agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] [Required]¶ The agent to run for creating a plan and determining actions to take at each step of the execution loop. 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 early_stopping_method: str = 'force'¶ The method to use for early stopping if the agent never returns AgentFinish. Either ‘force’ or ‘generate’. “force” returns a string saying that it stopped because it met atime or iteration limit. “generate” calls the agent’s LLM Chain one final time to generatea final answer based on the previous steps. param handle_parsing_errors: Union[bool, str, Callable[[OutputParserException], str]] = False¶ How to handle errors raised by the agent’s output parser.Defaults to False, which raises the error. sIf true, the error will be sent back to the LLM as an observation. If a string, the string itself will be sent to the LLM as an observation. If a callable function, the function will be called with the exception
https://api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html
2a680e37ce46-1
If a callable function, the function will be called with the exception as an argument, and the result of that function will be passed to the agentas an observation. param max_execution_time: Optional[float] = None¶ The maximum amount of wall clock time to spend in the execution loop. param max_iterations: Optional[int] = 15¶ The maximum number of steps to take before ending the execution loop. Setting to ‘None’ could lead to an infinite loop. 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 return_intermediate_steps: bool = False¶ Whether to return the agent’s trajectory of intermediate steps at the end in addition to the final output. 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 tools: Sequence[BaseTool] [Required]¶ The valid tools the agent can call.
https://api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html
2a680e37ce46-2
The valid tools the agent can call. param trim_intermediate_steps: Union[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]] = -1¶ 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. 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
https://api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html
2a680e37ce46-3
to False. Returns A dict of named outputs. Should contain all outputs specified inChain.output_keys. async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, max_concurrency: Optional[int] = None) → List[Output]¶ 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/agents/langchain.agents.react.base.ReActChain.html
2a680e37ce46-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/agents/langchain.agents.react.base.ReActChain.html
2a680e37ce46-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..." async astream(input: Input, config: Optional[RunnableConfig] = None) → AsyncIterator[Output]¶ batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, max_concurrency: Optional[int] = None) → List[Output]¶ bind(**kwargs: Any) → Runnable[Input, Output]¶ Bind arguments to a Runnable, returning a new Runnable. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data
https://api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html
2a680e37ce46-6
the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance 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_agent_and_tools(agent: Union[BaseSingleActionAgent, BaseMultiActionAgent], tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, **kwargs: Any) → AgentExecutor¶ Create from agent and tools. classmethod from_orm(obj: Any) → Model¶ invoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None) → Dict[str, Any]¶ iter(inputs: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, include_run_info: bool = False, async_: bool = False) → AgentExecutorIterator¶ Enables iteration over steps taken to reach final output. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html
2a680e37ce46-7
Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). lookup_tool(name: str) → BaseTool¶ Lookup tool by name. classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ 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.
https://api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html
2a680e37ce46-8
Returns A dict of the final chain outputs. 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: 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¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html
2a680e37ce46-9
save(file_path: Union[Path, str]) → None¶ Raise error - saving not supported for Agent Executors. save_agent(file_path: Union[Path, str]) → None¶ Save the underlying agent. classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ stream(input: Input, config: Optional[RunnableConfig] = None) → Iterator[Output]¶ to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶ to_json_not_implemented() → SerializedNotImplemented¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ with_fallbacks(fallbacks: ~typing.Sequence[~langchain.schema.runnable.Runnable[~langchain.schema.runnable.Input, ~langchain.schema.runnable.Output]], *, exceptions_to_handle: ~typing.Tuple[~typing.Type[BaseException]] = (<class 'Exception'>,)) → RunnableWithFallbacks[Input, Output]¶ 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¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html
2a680e37ce46-10
property lc_serializable: bool¶ Return whether or not the class is serializable.
https://api.python.langchain.com/en/latest/agents/langchain.agents.react.base.ReActChain.html
cd25fe159184-0
langchain.agents.agent_toolkits.pandas.base.create_pandas_dataframe_agent¶ langchain.agents.agent_toolkits.pandas.base.create_pandas_dataframe_agent(llm: BaseLanguageModel, df: Any, agent_type: AgentType = AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager: Optional[BaseCallbackManager] = None, prefix: Optional[str] = None, suffix: Optional[str] = None, input_variables: Optional[List[str]] = None, verbose: bool = False, return_intermediate_steps: bool = False, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = 'force', agent_executor_kwargs: Optional[Dict[str, Any]] = None, include_df_in_prompt: Optional[bool] = True, number_of_head_rows: int = 5, **kwargs: Dict[str, Any]) → AgentExecutor[source]¶ Construct a pandas agent from an LLM and dataframe. Examples using create_pandas_dataframe_agent¶ Pandas Dataframe Agent !pip install bs4
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.pandas.base.create_pandas_dataframe_agent.html
6b8332e283ce-0
langchain.agents.agent_toolkits.amadeus.toolkit.AmadeusToolkit¶ class langchain.agents.agent_toolkits.amadeus.toolkit.AmadeusToolkit[source]¶ Bases: BaseToolkit Toolkit for interacting with Office365. 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: Client [Optional]¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.amadeus.toolkit.AmadeusToolkit.html
6b8332e283ce-1
deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶ get_tools() → List[BaseTool][source]¶ Get the tools in the toolkit. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.amadeus.toolkit.AmadeusToolkit.html
6b8332e283ce-2
classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using AmadeusToolkit¶ Amadeus Toolkit
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.amadeus.toolkit.AmadeusToolkit.html
07fc1444d4a2-0
langchain.agents.agent_toolkits.openapi.spec.reduce_openapi_spec¶ langchain.agents.agent_toolkits.openapi.spec.reduce_openapi_spec(spec: dict, dereference: bool = True) → ReducedOpenAPISpec[source]¶ Simplify/distill/minify a spec somehow. I want a smaller target for retrieval and (more importantly) I want smaller results from retrieval. I was hoping https://openapi.tools/ would have some useful bits to this end, but doesn’t seem so. Examples using reduce_openapi_spec¶ OpenAPI agents
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.spec.reduce_openapi_spec.html
659d76cd258e-0
langchain.agents.structured_chat.output_parser.StructuredChatOutputParser¶ class langchain.agents.structured_chat.output_parser.StructuredChatOutputParser[source]¶ Bases: AgentOutputParser Output parser for the structured chat agent. 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. async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, max_concurrency: Optional[int] = None) → List[Output]¶ async ainvoke(input: str | langchain.schema.messages.BaseMessage, config: langchain.schema.runnable.RunnableConfig | None = None) → T¶ async aparse(text: str) → T¶ Parse a single string model output into some structure. Parameters text – String output of a language model. Returns Structured output. async aparse_result(result: List[Generation]) → T¶ Parse a list of candidate model Generations into a specific format. The return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation. Parameters result – A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. Returns Structured output. async astream(input: Input, config: Optional[RunnableConfig] = None) → AsyncIterator[Output]¶ batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, max_concurrency: Optional[int] = None) → List[Output]¶ bind(**kwargs: Any) → Runnable[Input, Output]¶ Bind arguments to a Runnable, returning a new Runnable.
https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html
659d76cd258e-1
Bind arguments to a Runnable, returning a new Runnable. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) → Dict¶ Return dictionary representation of output parser. classmethod from_orm(obj: Any) → Model¶ get_format_instructions() → str[source]¶ Instructions on how the LLM output should be formatted. invoke(input: str | langchain.schema.messages.BaseMessage, config: langchain.schema.runnable.RunnableConfig | None = None) → T¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html
659d76cd258e-2
json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). parse(text: str) → Union[AgentAction, AgentFinish][source]¶ Parse text into agent action/finish. classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ parse_result(result: List[Generation]) → T¶ Parse a list of candidate model Generations into a specific format. The return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation. Parameters result – A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. Returns Structured output. parse_with_prompt(completion: str, prompt: PromptValue) → Any¶ Parse the output of an LLM call with the input prompt for context.
https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html
659d76cd258e-3
Parse the output of an LLM call with the input prompt for context. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so. Parameters completion – String output of a language model. prompt – Input PromptValue. Returns Structured output classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ stream(input: Input, config: Optional[RunnableConfig] = None) → Iterator[Output]¶ to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶ to_json_not_implemented() → SerializedNotImplemented¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ with_fallbacks(fallbacks: ~typing.Sequence[~langchain.schema.runnable.Runnable[~langchain.schema.runnable.Input, ~langchain.schema.runnable.Output]], *, exceptions_to_handle: ~typing.Tuple[~typing.Type[BaseException]] = (<class 'Exception'>,)) → RunnableWithFallbacks[Input, Output]¶ 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.
https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html
659d76cd258e-4
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.
https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.output_parser.StructuredChatOutputParser.html
4ca163c3af9b-0
langchain.agents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit¶ class langchain.agents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit[source]¶ Bases: BaseToolkit Toolkit for Azure Cognitive Services. 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. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit.html
4ca163c3af9b-1
deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶ get_tools() → List[BaseTool][source]¶ Get the tools in the toolkit. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit.html
4ca163c3af9b-2
classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using AzureCognitiveServicesToolkit¶ Azure Cognitive Services Toolkit
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.azure_cognitive_services.AzureCognitiveServicesToolkit.html
322c186e5fd3-0
langchain.agents.structured_chat.base.StructuredChatAgent¶ class langchain.agents.structured_chat.base.StructuredChatAgent[source]¶ Bases: Agent Structured Chat Agent. 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 allowed_tools: Optional[List[str]] = None¶ param llm_chain: langchain.chains.llm.LLMChain [Required]¶ param output_parser: langchain.agents.agent.AgentOutputParser [Optional]¶ Output parser for the agent. async aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → Union[AgentAction, AgentFinish]¶ Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations callbacks – Callbacks to run. **kwargs – User inputs. Returns Action specifying what tool to use. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model
https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html
322c186e5fd3-1
Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance
https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html
322c186e5fd3-2
deep – set to True to make a deep copy of the model Returns new model instance classmethod create_prompt(tools: Sequence[BaseTool], prefix: str = 'Respond to the human as helpfully and accurately as possible. You have access to the following tools:', suffix: str = 'Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation:.\nThought:', human_message_template: str = '{input}\n\n{agent_scratchpad}', format_instructions: str = 'Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).\n\nValid "action" values: "Final Answer" or {tool_names}\n\nProvide only ONE action per $JSON_BLOB, as shown:\n\n```\n{{{{\n  "action": $TOOL_NAME,\n  "action_input": $INPUT\n}}}}\n```\n\nFollow this format:\n\nQuestion: input question to answer\nThought: consider previous and subsequent steps\nAction:\n```\n$JSON_BLOB\n```\nObservation: action result\n... (repeat Thought/Action/Observation N times)\nThought: I know what to respond\nAction:\n```\n{{{{\n  "action": "Final Answer",\n  "action_input": "Final response to human"\n}}}}\n```', input_variables: Optional[List[str]] = None, memory_prompts: Optional[List[BasePromptTemplate]] = None) → BasePromptTemplate[source]¶ Create a prompt for this class. dict(**kwargs: Any) → Dict¶ Return dictionary representation of agent.
https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html
322c186e5fd3-3
dict(**kwargs: Any) → Dict¶ Return dictionary representation of agent. classmethod from_llm_and_tools(llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: str = 'Respond to the human as helpfully and accurately as possible. You have access to the following tools:', suffix: str = 'Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation:.\nThought:', human_message_template: str = '{input}\n\n{agent_scratchpad}', format_instructions: str = 'Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).\n\nValid "action" values: "Final Answer" or {tool_names}\n\nProvide only ONE action per $JSON_BLOB, as shown:\n\n```\n{{{{\n  "action": $TOOL_NAME,\n  "action_input": $INPUT\n}}}}\n```\n\nFollow this format:\n\nQuestion: input question to answer\nThought: consider previous and subsequent steps\nAction:\n```\n$JSON_BLOB\n```\nObservation: action result\n... (repeat Thought/Action/Observation N times)\nThought: I know what to respond\nAction:\n```\n{{{{\n  "action": "Final Answer",\n  "action_input": "Final response to human"\n}}}}\n```', input_variables: Optional[List[str]] = None, memory_prompts: Optional[List[BasePromptTemplate]] = None, **kwargs: Any) → Agent[source]¶ Construct an agent from an LLM and tools.
https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html
322c186e5fd3-4
Construct an agent from an LLM and tools. classmethod from_orm(obj: Any) → Model¶ get_allowed_tools() → Optional[List[str]]¶ get_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) → Dict[str, Any]¶ Create the full inputs for the LLMChain from intermediate steps. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ plan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → Union[AgentAction, AgentFinish]¶ Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations
https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html
322c186e5fd3-5
Parameters intermediate_steps – Steps the LLM has taken to date, along with observations callbacks – Callbacks to run. **kwargs – User inputs. Returns Action specifying what tool to use. return_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) → AgentFinish¶ Return response when agent has been stopped due to max iterations. save(file_path: Union[Path, str]) → None¶ Save the agent. Parameters file_path – Path to file to save the agent to. Example: .. code-block:: python # If working with agent executor agent.agent.save(file_path=”path/agent.yaml”) classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ tool_run_logging_kwargs() → Dict¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ property llm_prefix: str¶ Prefix to append the llm call with. property observation_prefix: str¶ Prefix to append the observation with. property return_values: List[str]¶ Return values of the agent.
https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.StructuredChatAgent.html
d93ac2a03bed-0
langchain.agents.agent_toolkits.openapi.toolkit.RequestsToolkit¶ class langchain.agents.agent_toolkits.openapi.toolkit.RequestsToolkit[source]¶ Bases: BaseToolkit Toolkit for making REST requests. 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 requests_wrapper: langchain.utilities.requests.TextRequestsWrapper [Required]¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.toolkit.RequestsToolkit.html
d93ac2a03bed-1
deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶ get_tools() → List[BaseTool][source]¶ Return a list of tools. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.toolkit.RequestsToolkit.html
d93ac2a03bed-2
classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.toolkit.RequestsToolkit.html
829a9395afeb-0
langchain.agents.agent_toolkits.office365.toolkit.O365Toolkit¶ class langchain.agents.agent_toolkits.office365.toolkit.O365Toolkit[source]¶ Bases: BaseToolkit Toolkit for interacting with Office 365. 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 account: Account [Optional]¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.office365.toolkit.O365Toolkit.html
829a9395afeb-1
deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶ get_tools() → List[BaseTool][source]¶ Get the tools in the toolkit. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.office365.toolkit.O365Toolkit.html
829a9395afeb-2
classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using O365Toolkit¶ Office365 Toolkit
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.office365.toolkit.O365Toolkit.html
d66879408270-0
langchain.agents.agent_toolkits.openapi.spec.ReducedOpenAPISpec¶ class langchain.agents.agent_toolkits.openapi.spec.ReducedOpenAPISpec(servers: List[dict], description: str, endpoints: List[Tuple[str, str, dict]])[source]¶ Attributes servers description endpoints Methods __init__(servers, description, endpoints) __init__(servers: List[dict], description: str, endpoints: List[Tuple[str, str, dict]]) → None¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.openapi.spec.ReducedOpenAPISpec.html
0d9d7aa76b3f-0
langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit¶ class langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit[source]¶ Bases: BaseToolkit Toolkit for interacting with Power BI dataset. 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[langchain.callbacks.base.BaseCallbackManager] = None¶ param examples: Optional[str] = None¶ param llm: Union[langchain.schema.language_model.BaseLanguageModel, langchain.chat_models.base.BaseChatModel] [Required]¶ param max_iterations: int = 5¶ param output_token_limit: Optional[int] = None¶ param powerbi: langchain.utilities.powerbi.PowerBIDataset [Required]¶ param tiktoken_model_name: Optional[str] = None¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit.html
0d9d7aa76b3f-1
the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶ get_tools() → List[BaseTool][source]¶ Get the tools in the toolkit. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit.html
0d9d7aa76b3f-2
classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using PowerBIToolkit¶ PowerBI Dataset Agent
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit.html
ee999c9e9ca9-0
langchain.agents.agent.AgentOutputParser¶ class langchain.agents.agent.AgentOutputParser[source]¶ Bases: BaseOutputParser Base class for parsing agent output into agent action/finish. 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. async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, max_concurrency: Optional[int] = None) → List[Output]¶ async ainvoke(input: str | langchain.schema.messages.BaseMessage, config: langchain.schema.runnable.RunnableConfig | None = None) → T¶ async aparse(text: str) → T¶ Parse a single string model output into some structure. Parameters text – String output of a language model. Returns Structured output. async aparse_result(result: List[Generation]) → T¶ Parse a list of candidate model Generations into a specific format. The return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation. Parameters result – A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. Returns Structured output. async astream(input: Input, config: Optional[RunnableConfig] = None) → AsyncIterator[Output]¶ batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, max_concurrency: Optional[int] = None) → List[Output]¶ bind(**kwargs: Any) → Runnable[Input, Output]¶ Bind arguments to a Runnable, returning a new Runnable. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
https://api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentOutputParser.html