viruPVS/langchain-docs huggingface dataset:
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a chain with its use case.
param verbose: bool [Optional]¶
Whether or not run in verbose mode. In verbose mode, some intermediate logs
will be printed to the console. Defaults to the global verbose value,
accessible via langchain.globals.get_verbose().
pydantic_model¶
alias of NarrativeModel
__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, run_name: Optional[str] = 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.
candy, then how many pounds of candy will andy have?\n\n\n\n\n\n# JSON\n\n\n\n\n{{\n    "story_outcome_question": "how many pounds of candy will andy have?",\n    "story_hypothetical": "If boris has 100 pounds of candy and marcia has 200 pounds of candy"\n    "story_plot": "boris gives ten percent of his candy to marcia. marcia gives ten percent of her candy to andy."\n}}\n\n\n\n\n\nQ: {narrative_input}\n\n\n\n# JSON\n\n\n'¶
langchain_experimental.comprehend_moderation.base_moderation_config.BaseModerationConfig¶
class langchain_experimental.comprehend_moderation.base_moderation_config.BaseModerationConfig[source]¶
Bases: BaseModel
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 filters: List[Union[langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPiiConfig, langchain_experimental.comprehend_moderation.base_moderation_config.ModerationToxicityConfig, langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPromptSafetyConfig]] = [ModerationPiiConfig(threshold=0.5, labels=[], redact=False, mask_character='*'), ModerationToxicityConfig(threshold=0.5, labels=[]), ModerationPromptSafetyConfig(threshold=0.5)]¶
Filters applied to the moderation chain, defaults to
[ModerationPiiConfig(), ModerationToxicityConfig(),
ModerationPromptSafetyConfig()]
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
langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPromptSafetyConfig¶
class langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPromptSafetyConfig[source]¶
Bases: BaseModel
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 threshold: float = 0.5¶
Threshold for Prompt Safety classification
confidence score, defaults to 0.5 i.e. 50%
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
langchain_experimental.comprehend_moderation.prompt_safety.ComprehendPromptSafety¶
class langchain_experimental.comprehend_moderation.prompt_safety.ComprehendPromptSafety(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None)[source]¶
Methods
__init__(client[, callback, unique_id, chain_id])
validate(prompt_value[, config])
Check and validate the safety of the given prompt text.
__init__(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None) → None[source]¶
validate(prompt_value: str, config: Any = None) → str[source]¶
Check and validate the safety of the given prompt text.
Parameters
prompt_value (str) – The input text to be checked for unsafe text.
config (Dict[str, Any]) – Configuration settings for prompt safety checks.
Raises
ValueError – If unsafe prompt is found in the prompt text based
on the specified threshold. – 
Returns
The input prompt_value.
Return type
str
Note
This function checks the safety of the provided prompt text using
Comprehend’s classify_document API and raises an error if unsafe
text is detected with a score above the specified threshold.
Example
comprehend_client = boto3.client(‘comprehend’)
prompt_text = “Please tell me your credit card information.”
config = {“threshold”: 0.7}
checked_prompt = check_prompt_safety(comprehend_client, prompt_text, config)
langchain_experimental.comprehend_moderation.base_moderation.BaseModeration¶
class langchain_experimental.comprehend_moderation.base_moderation.BaseModeration(client: Any, config: Optional[Any] = None, moderation_callback: Optional[Any] = None, unique_id: Optional[str] = None, run_manager: Optional[CallbackManagerForChainRun] = None)[source]¶
Methods
__init__(client[, config, ...])
moderate(prompt)
__init__(client: Any, config: Optional[Any] = None, moderation_callback: Optional[Any] = None, unique_id: Optional[str] = None, run_manager: Optional[CallbackManagerForChainRun] = None)[source]¶
moderate(prompt: Any) → str[source]¶
langchain_experimental.comprehend_moderation.pii.ComprehendPII¶
class langchain_experimental.comprehend_moderation.pii.ComprehendPII(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None)[source]¶
Methods
__init__(client[, callback, unique_id, chain_id])
validate(prompt_value[, config])
__init__(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None) → None[source]¶
validate(prompt_value: str, config: Any = None) → str[source]¶
langchain_experimental.comprehend_moderation.base_moderation_callbacks.BaseModerationCallbackHandler¶
class langchain_experimental.comprehend_moderation.base_moderation_callbacks.BaseModerationCallbackHandler[source]¶
Attributes
pii_callback
prompt_safety_callback
toxicity_callback
Methods
__init__()
on_after_pii(moderation_beacon, unique_id, ...)
Run after PII validation is complete.
on_after_prompt_safety(moderation_beacon, ...)
Run after Prompt Safety validation is complete.
on_after_toxicity(moderation_beacon, ...)
Run after Toxicity validation is complete.
__init__() → None[source]¶
async on_after_pii(moderation_beacon: Dict[str, Any], unique_id: str, **kwargs: Any) → None[source]¶
Run after PII validation is complete.
async on_after_prompt_safety(moderation_beacon: Dict[str, Any], unique_id: str, **kwargs: Any) → None[source]¶
Run after Prompt Safety validation is complete.
async on_after_toxicity(moderation_beacon: Dict[str, Any], unique_id: str, **kwargs: Any) → None[source]¶
Run after Toxicity validation is complete.
langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPiiConfig¶
class langchain_experimental.comprehend_moderation.base_moderation_config.ModerationPiiConfig[source]¶
Bases: BaseModel
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 labels: List[str] = []¶
List of PII Universal Labels.
Defaults to list[]
param mask_character: str = '*'¶
Redaction mask character in case redact=True, defaults to asterisk (*)
param redact: bool = False¶
Whether to perform redaction of detected PII entities
param threshold: float = 0.5¶
Threshold for PII confidence score, defaults to 0.5 i.e. 50%
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
langchain_experimental.comprehend_moderation.base_moderation_config.ModerationToxicityConfig¶
class langchain_experimental.comprehend_moderation.base_moderation_config.ModerationToxicityConfig[source]¶
Bases: BaseModel
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 labels: List[str] = []¶
List of toxic labels, defaults to list[]
param threshold: float = 0.5¶
Threshold for Toxic label confidence score, defaults to 0.5 i.e. 50%
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
langchain_experimental.comprehend_moderation.toxicity.ComprehendToxicity¶
class langchain_experimental.comprehend_moderation.toxicity.ComprehendToxicity(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None)[source]¶
Methods
__init__(client[, callback, unique_id, chain_id])
validate(prompt_value[, config])
Check the toxicity of a given text prompt using AWS Comprehend service and apply actions based on configuration.
__init__(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None) → None[source]¶
validate(prompt_value: str, config: Any = None) → str[source]¶
Check the toxicity of a given text prompt using AWS
Comprehend service and apply actions based on configuration.
:param prompt_value: The text content to be checked for toxicity.
:type prompt_value: str
:param config: Configuration for toxicity checks and actions.
:type config: Dict[str, Any]
Returns
The original prompt_value if allowed or no toxicity found.
Return type
str
Raises
ValueError – If the prompt contains toxic labels and cannot be
processed based on the configuration. –
langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain¶
class langchain_experimental.comprehend_moderation.amazon_comprehend_moderation.AmazonComprehendModerationChain[source]¶
Bases: Chain
A subclass of Chain, designed to apply moderation to LLMs.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param callback_manager: Optional[BaseCallbackManager] = None¶
Deprecated, use callbacks instead.
param callbacks: Callbacks = None¶
Optional list of callback handlers (or callback manager). Defaults to None.
Callback handlers are called throughout the lifecycle of a call to a chain,
starting with on_chain_start, ending with on_chain_end or on_chain_error.
Each custom chain can optionally call additional callback methods, see Callback docs
for full details.
param client: Optional[Any] = None¶
boto3 client object for connection to Amazon Comprehend
param credentials_profile_name: Optional[str] = None¶
The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which
has either access keys or role information specified.
If not specified, the default credential profile or, if on an EC2 instance,
credentials from IMDS will be used.
See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
param input_key: str = 'input'¶
Key used to fetch/store the input in data containers. Defaults to input
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
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 moderation_callback: Optional[langchain_experimental.comprehend_moderation.base_moderation_callbacks.BaseModerationCallbackHandler] = None¶
Callback handler for moderation, this is different
from regular callbacks which can be used in addition to this.
param moderation_config: langchain_experimental.comprehend_moderation.base_moderation_config.BaseModerationConfig = BaseModerationConfig(filters=[ModerationPiiConfig(threshold=0.5, labels=[], redact=False, mask_character='*'), ModerationToxicityConfig(threshold=0.5, labels=[]), ModerationPromptSafetyConfig(threshold=0.5)])¶
Configuration settings for moderation,
defaults to BaseModerationConfig with default values
param output_key: str = 'output'¶
Key used to fetch/store the output in data containers. Defaults to output
param region_name: Optional[str] = None¶
The aws region e.g., us-west-2. Fallsback to AWS_DEFAULT_REGION env variable
or region specified in ~/.aws/config in case it is not provided here.
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.
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 unique_id: Optional[str] = None¶
A unique id that can be used to identify or group a user or session
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 the global verbose value,
accessible via langchain.globals.get_verbose().
__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, run_name: Optional[str] = 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
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¶
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
chain.dict(exclude_unset=True)
# -> {"_type": "foo", "verbose": False, ...}
classmethod from_orm(obj: Any) → Model¶
get_input_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶
Get a pydantic model that can be used to validate input to the runnable.
Runnables that leverage the configurable_fields and configurable_alternatives
methods will have a dynamic input schema that depends on which
configuration the runnable is invoked with.
This method allows to get an input schema for a specific configuration.
Parameters
config – A config to use when generating the schema.
Returns
Parameters
config – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate input.
classmethod get_lc_namespace() → List[str]¶
Get the namespace of the langchain object.
For example, if the class is langchain.llms.openai.OpenAI, then the
namespace is [“langchain”, “llms”, “openai”]
get_output_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶
Get a pydantic model that can be used to validate output to the runnable.
Runnables that leverage the configurable_fields and configurable_alternatives
methods will have a dynamic output schema that depends on which
configuration the runnable is invoked with.
This method allows to get an output schema for a specific configuration.
Parameters
config – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate output.
invoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → Dict[str, Any]¶
Transform a single input into an output. Override to implement.
Parameters
input – The input to the runnable.
config – A config to use when invoking the runnable.
The config supports standard keys like ‘tags’, ‘metadata’ for tracing
purposes, ‘max_concurrency’ for controlling how much work to do
in parallel, and other keys. Please refer to the RunnableConfig
for more details.
Returns
The output of the runnable.
classmethod is_lc_serializable() → bool¶
Is this class serializable?
added to the run.
with_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) → Runnable[Input, Output]¶
Create a new Runnable that retries the original runnable on exceptions.
Parameters
retry_if_exception_type – A tuple of exception types to retry on
wait_exponential_jitter – Whether to add jitter to the wait time
between retries
stop_after_attempt – The maximum number of attempts to make before giving up
Returns
A new Runnable that retries the original runnable on exceptions.
with_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) → Runnable[Input, Output]¶
Bind input and output types to a Runnable, returning a new Runnable.
property InputType: Type[langchain_core.runnables.utils.Input]¶
The type of input this runnable accepts specified as a type annotation.
property OutputType: Type[langchain_core.runnables.utils.Output]¶
The type of output this runnable produces specified as a type annotation.
property config_specs: List[langchain_core.runnables.utils.ConfigurableFieldSpec]¶
List configurable fields for this runnable.
property input_keys: List[str]¶
Returns a list of input keys expected by the prompt.
This method defines the input keys that the prompt expects in order to perform
its processing. It ensures that the specified keys are available for providing
input to the prompt.
Returns
A list of input keys.
Return type
List[str]
Note
This method is considered private and may not be intended for direct
external use.
property input_schema: Type[pydantic.main.BaseModel]¶
external use.
property input_schema: Type[pydantic.main.BaseModel]¶
The type of input this runnable accepts specified as a pydantic model.
property lc_attributes: Dict¶
List of attribute names that should be included in the serialized kwargs.
These attributes must be accepted by the constructor.
property lc_secrets: Dict[str, str]¶
A map of constructor argument names to secret ids.
For example,{“openai_api_key”: “OPENAI_API_KEY”}
property output_keys: List[str]¶
Returns a list of output keys.
This method defines the output keys that will be used to access the output
values produced by the chain or function. It ensures that the specified keys
are available to access the outputs.
Returns
A list of output keys.
Return type
List[str]
Note
This method is considered private and may not be intended for direct
external use.
property output_schema: Type[pydantic.main.BaseModel]¶
The type of output this runnable produces specified as a pydantic model.