Tony20100/langchain_full huggingface dataset:
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]¶
Class to handle prompt safety moderation.
Methods
__init__(client[, callback, unique_id, chain_id])
validate(prompt_value[, config])
Check and validate the safety of the given prompt text.
Parameters
client (Any) – 
callback (Optional[Any]) – 
unique_id (Optional[str]) – 
chain_id (Optional[str]) – 
__init__(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None) → None[source]¶
Parameters
client (Any) – 
callback (Optional[Any]) – 
unique_id (Optional[str]) – 
chain_id (Optional[str]) – 
Return type
None
validate(prompt_value: str, config: Optional[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’)
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]¶
Class to handle Personally Identifiable Information (PII) moderation.
Methods
__init__(client[, callback, unique_id, chain_id])
validate(prompt_value[, config])
Parameters
client (Any) – 
callback (Optional[Any]) – 
unique_id (Optional[str]) – 
chain_id (Optional[str]) – 
__init__(client: Any, callback: Optional[Any] = None, unique_id: Optional[str] = None, chain_id: Optional[str] = None) → None[source]¶
Parameters
client (Any) – 
callback (Optional[Any]) – 
unique_id (Optional[str]) – 
chain_id (Optional[str]) – 
Return type
None
validate(prompt_value: str, config: Optional[Any] = None) → str[source]¶
Parameters
prompt_value (str) – 
config (Optional[Any]) – 
Return type
str
langchain_experimental.pal_chain.base.PALChain¶
class langchain_experimental.pal_chain.base.PALChain[source]¶
Bases: Chain
Chain that implements Program-Aided Language Models (PAL).
This class implements the Program-Aided Language Models (PAL) for generating code
solutions. PAL is a technique described in the paper “Program-Aided Language Models”
(https://arxiv.org/pdf/2211.10435.pdf).
Security note: This class implements an AI technique that generates and evaluatesPython code, which can be dangerous and requires a specially sandboxed
environment to be safely used. While this class implements some basic guardrails
by limiting available locals/globals and by parsing and inspecting
the generated Python AST using PALValidation, those guardrails will not
deter sophisticated attackers and are not a replacement for a proper sandbox.
Do not use this class on untrusted inputs, with elevated permissions,
or without consulting your security team about proper sandboxing!
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 code_validations: PALValidation [Optional]¶
Validations to perform on the generated code.
param get_answer_expr: str = 'print(solution())'¶
Expression to use to get the answer from the generated code.
param llm_chain: LLMChain [Required]¶
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]¶
[Deprecated] Execute the chain.
Parameters
inputs (Union[Dict[str, Any], Any]) – 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 (bool) – 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 (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 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 (Optional[List[str]]) – 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[Dict[str, Any]]) – Optional metadata associated with the chain. Defaults to None
include_run_info (bool) – Whether to include run info in the response. Defaults
to False.
run_name (Optional[str]) – 
Returns
to False.
run_name (Optional[str]) – 
Returns
A dict of named outputs. Should contain all outputs specified inChain.output_keys.
Return type
Dict[str, Any]
Notes
Deprecated since version langchain==0.1.0: Use invoke instead.
async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶
Default implementation runs ainvoke in parallel using asyncio.gather.
The default implementation of batch works well for IO bound runnables.
Subclasses should override this method if they can batch more efficiently;
e.g., if the underlying runnable uses an API which supports a batch mode.
Parameters
inputs (List[Input]) – 
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
List[Output]
async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → AsyncIterator[Tuple[int, Union[Output, Exception]]]¶
Run ainvoke in parallel on a list of inputs,
yielding results as they complete.
Parameters
inputs (Sequence[Input]) – 
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
AsyncIterator[Tuple[int, Union[Output, Exception]]]
update (Optional[DictStrAny]) – 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 (bool) – set to True to make a deep copy of the model
self (Model) – 
Returns
new model instance
Return type
Model
dict(**kwargs: Any) → Dict¶
Dictionary representation of chain.
Expects Chain._chain_type property to be implemented and for memory to benull.
Parameters
**kwargs (Any) – Keyword arguments passed to default pydantic.BaseModel.dict
method.
Returns
A dictionary representation of the chain.
Return type
Dict
Example
chain.dict(exclude_unset=True)
# -> {"_type": "foo", "verbose": False, ...}
classmethod from_colored_object_prompt(llm: BaseLanguageModel, **kwargs: Any) → PALChain[source]¶
Load PAL from colored object prompt.
Parameters
llm (BaseLanguageModel) – The language model to use for generating code.
kwargs (Any) – 
Returns
An instance of PALChain.
Return type
PALChain
classmethod from_math_prompt(llm: BaseLanguageModel, **kwargs: Any) → PALChain[source]¶
Load PAL from math prompt.
Parameters
llm (BaseLanguageModel) – The language model to use for generating code.
kwargs (Any) – 
Returns
An instance of PALChain.
Return type
PALChain
classmethod from_orm(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
get_graph(config: Optional[RunnableConfig] = None) → Graph¶
Return a graph representation of this runnable.
Parameters
config (Optional[RunnableConfig]) – 
Return type
Graph
Parameters
config (Optional[RunnableConfig]) – 
Return type
Graph
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 (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate input.
Return type
Type[BaseModel]
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”]
Return type
List[str]
get_name(suffix: Optional[str] = None, *, name: Optional[str] = None) → str¶
Get the name of the runnable.
Parameters
suffix (Optional[str]) – 
name (Optional[str]) – 
Return type
str
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 (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate output.
Return type
Type[BaseModel]
Return type
Type[BaseModel]
get_prompts(config: Optional[RunnableConfig] = None) → List[BasePromptTemplate]¶
Parameters
config (Optional[RunnableConfig]) – 
Return type
List[BasePromptTemplate]
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 (Dict[str, Any]) – The input to the runnable.
config (Optional[RunnableConfig]) – 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.
kwargs (Any) – 
Returns
The output of the runnable.
Return type
Dict[str, Any]
classmethod is_lc_serializable() → bool¶
Is this class serializable?
Return type
bool
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().
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) –
Expects Chain._chain_type property to be implemented and for memory to benull.
Parameters
file_path (Union[Path, str]) – Path to file to save the chain to.
Return type
None
Example
chain.save(file_path="path/chain.yaml")
classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
Return type
DictStrAny
classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
dumps_kwargs (Any) – 
Return type
unicode
stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶
Default implementation of stream, which calls invoke.
Subclasses should override this method if they support streaming output.
Parameters
input (Input) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
Iterator[Output]
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
Serialize the runnable to JSON.
Return type
Union[SerializedConstructor, SerializedNotImplemented]
to_json_not_implemented() → SerializedNotImplemented¶
Return type
SerializedNotImplemented
transform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶
Default implementation of transform, which buffers input and then calls stream.
Subclasses should override this method if they can start producing output while
input is still being generated.
Parameters
input (Iterator[Input]) –
input is still being generated.
Parameters
input (Iterator[Input]) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
Iterator[Output]
classmethod update_forward_refs(**localns: Any) → None¶
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) – 
Return type
None
classmethod validate(value: Any) → Model¶
Parameters
value (Any) – 
Return type
Model
classmethod validate_code(code: str, code_validations: PALValidation) → None[source]¶
Parameters
code (str) – 
code_validations (PALValidation) – 
Return type
None
with_alisteners(*, on_start: Optional[AsyncListener] = None, on_end: Optional[AsyncListener] = None, on_error: Optional[AsyncListener] = None) → Runnable[Input, Output]¶
Bind asynchronous lifecycle listeners to a Runnable, returning a new Runnable.
on_start: Asynchronously called before the runnable starts running.
on_end: Asynchronously called after the runnable finishes running.
on_error: Asynchronously called if the runnable throws an error.
The Run object contains information about the run, including its id,
type, input, output, error, start_time, end_time, and any tags or metadata
added to the run.
Example:
Parameters
on_start (Optional[AsyncListener]) – 
on_end (Optional[AsyncListener]) – 
on_error (Optional[AsyncListener]) – 
Return type
Runnable[Input, Output]
with_config(config: Optional[RunnableConfig] = None, **kwargs: Any) → Runnable[Input, Output]¶
Bind config to a Runnable, returning a new Runnable.
Parameters
config (Optional[RunnableConfig]) –
Parameters
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
Runnable[Input, Output]
with_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,), exception_key: Optional[str] = None) → RunnableWithFallbacksT[Input, Output]¶
Add fallbacks to a runnable, returning a new Runnable.
Example
from typing import Iterator
from langchain_core.runnables import RunnableGenerator
def _generate_immediate_error(input: Iterator) -> Iterator[str]:
    raise ValueError()
    yield ""
def _generate(input: Iterator) -> Iterator[str]:
    yield from "foo bar"
runnable = RunnableGenerator(_generate_immediate_error).with_fallbacks(
    [RunnableGenerator(_generate)]
    )
print(''.join(runnable.stream({}))) #foo bar
Parameters
fallbacks (Sequence[Runnable[Input, Output]]) – A sequence of runnables to try if the original runnable fails.
exceptions_to_handle (Tuple[Type[BaseException], ...]) – A tuple of exception types to handle.
exception_key (Optional[str]) – If string is specified then handled exceptions will be passed
to fallbacks as part of the input under the specified key. If None,
exceptions will not be passed to fallbacks. If used, the base runnable
and its fallbacks must accept a dictionary as input.
Returns
A new Runnable that will try the original runnable, and then each
fallback in order, upon failures.
Return type
RunnableWithFallbacksT[Input, Output]
output_type (Optional[Type[Output]]) – 
Return type
Runnable[Input, Output]
property InputType: Type[Input]¶
The type of input this runnable accepts specified as a type annotation.
property OutputType: Type[Output]¶
The type of output this runnable produces specified as a type annotation.
property config_specs: List[ConfigurableFieldSpec]¶
List configurable fields for this runnable.
property input_schema: Type[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”}
name: Optional[str] = None¶
The name of the runnable. Used for debugging and tracing.
property output_schema: Type[BaseModel]¶
The type of output this runnable produces specified as a pydantic model.
langchain_experimental.pal_chain.base.PALValidation¶
class langchain_experimental.pal_chain.base.PALValidation(solution_expression_name: Optional[str] = None, solution_expression_type: Optional[type] = None, allow_imports: bool = False, allow_command_exec: bool = False)[source]¶
Validation for PAL generated code.
Initialize a PALValidation instance.
Parameters
solution_expression_name (str) – Name of the expected solution expression.
If passed, solution_expression_type must be passed as well.
solution_expression_type (str) – AST type of the expected solution
expression. If passed, solution_expression_name must be passed as well.
Must be one of PALValidation.SOLUTION_EXPRESSION_TYPE_FUNCTION,
PALValidation.SOLUTION_EXPRESSION_TYPE_VARIABLE.
allow_imports (bool) – Allow import statements.
allow_command_exec (bool) – Allow using known command execution functions.
Methods
__init__([solution_expression_name, ...])
Initialize a PALValidation instance.
__init__(solution_expression_name: Optional[str] = None, solution_expression_type: Optional[type] = None, allow_imports: bool = False, allow_command_exec: bool = False)[source]¶
Initialize a PALValidation instance.
Parameters
solution_expression_name (str) – Name of the expected solution expression.
If passed, solution_expression_type must be passed as well.
solution_expression_type (str) – AST type of the expected solution
expression. If passed, solution_expression_name must be passed as well.
Must be one of PALValidation.SOLUTION_EXPRESSION_TYPE_FUNCTION,
PALValidation.SOLUTION_EXPRESSION_TYPE_VARIABLE.
allow_imports (bool) – Allow import statements.
allow_command_exec (bool) – Allow using known command execution functions.
langchain_core.tracers.log_stream.RunState¶
class langchain_core.tracers.log_stream.RunState[source]¶
State of the run.
Attributes
id
ID of the run.
streamed_output
List of output chunks streamed by Runnable.stream()
final_output
Final output of the run, usually the result of aggregating (+) streamed_output.
name
Name of the object being run.
type
Type of the object being run, eg.
logs
Map of run names to sub-runs.
Methods
__init__(*args, **kwargs)
clear()
copy()
fromkeys([value])
Create a new dictionary with keys from iterable and values set to value.
get(key[, default])
Return the value for key if key is in the dictionary, else default.
items()
keys()
pop(k[,d])
If the key is not found, return the default if given; otherwise, raise a KeyError.
popitem()
Remove and return a (key, value) pair as a 2-tuple.
setdefault(key[, default])
Insert key with a value of default if key is not in the dictionary.
update([E, ]**F)
If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]
values()
__init__(*args, **kwargs)¶
clear() → None.  Remove all items from D.¶
copy() → a shallow copy of D¶
fromkeys(value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
Create a new dictionary with keys from iterable and values set to value.
get(key, default=None, /)¶
Return the value for key if key is in the dictionary, else default.
items() → a set-like object providing a view on D's items¶
keys() → a set-like object providing a view on D's keys¶
pop(k[, d]) → v, remove specified key and return the corresponding value.¶
If the key is not found, return the default if given; otherwise,
raise a KeyError.
popitem()¶
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order.
Raises KeyError if the dict is empty.
setdefault(key, default=None, /)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
update([E, ]**F) → None.  Update D from dict/iterable E and F.¶
If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
In either case, this is followed by: for k in F:  D[k] = F[k]
values() → an object providing a view on D's values¶
langchain_core.tracers.context.register_configure_hook¶
langchain_core.tracers.context.register_configure_hook(context_var: ContextVar[Optional[Any]], inheritable: bool, handle_class: Optional[Type[BaseCallbackHandler]] = None, env_var: Optional[str] = None) → None[source]¶
Register a configure hook.
Parameters
context_var (ContextVar[Optional[Any]]) – The context variable.
inheritable (bool) – Whether the context variable is inheritable.
handle_class (Optional[Type[BaseCallbackHandler]], optional) – The callback handler class. Defaults to None.
env_var (Optional[str], optional) – The environment variable. Defaults to None.
Raises
ValueError – If env_var is set, handle_class must also be set
    to a non-None value.
Return type
None
langchain_core.tracers.base.BaseTracer¶
class langchain_core.tracers.base.BaseTracer(*, _schema_format: Literal['original', 'streaming_events', 'original+chat'] = 'original', **kwargs: Any)[source]¶
Base interface for tracers.
Initialize the tracer.
Parameters
_schema_format (Literal['original', 'streaming_events', 'original+chat']) – Primarily changes how the inputs and outputs are
handled. For internal use only. This API will change.
- ‘original’ is the format used by all current tracers.
This format is slightly inconsistent with respect to inputs
and outputs.
’streaming_events’ is used for supporting streaming events,for internal usage. It will likely change in the future, or
be deprecated entirely in favor of a dedicated async tracer
for streaming events.
’original+chat’ is a format that is the same as ‘original’except it does NOT raise an attribute error on_chat_model_start
kwargs (Any) – Additional keyword arguments that will be passed to
the super class.
Attributes
ignore_agent
Whether to ignore agent callbacks.
ignore_chain
Whether to ignore chain callbacks.
ignore_chat_model
Whether to ignore chat model callbacks.
ignore_llm
Whether to ignore LLM callbacks.
ignore_retriever
Whether to ignore retriever callbacks.
ignore_retry
Whether to ignore retry callbacks.
raise_error
run_inline
Methods
__init__(*[, _schema_format])
Initialize the tracer.
on_agent_action(action, *, run_id[, ...])
Run on agent action.
on_agent_finish(finish, *, run_id[, ...])
Run on agent end.
on_chain_end(outputs, *, run_id[, inputs])
End a trace for a chain run.
on_chain_error(error, *[, inputs])