Tony20100/langchain_full huggingface dataset:
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 (Any) – If the chain expects a single input, it can be passed in as the
sole positional argument.
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.
**kwargs (Any) – If the chain expects multiple inputs, they can be passed in
directly as keyword arguments.
metadata (Optional[Dict[str, Any]]) – 
**kwargs – 
Returns
The chain output.
Return type
Any
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..."
Notes
Deprecated since version langchain==0.1.0: Use invoke instead.
save(file_path: Union[Path, str]) → None¶
Save the chain.
Expects Chain._chain_type property to be implemented and for memory to benull.
Parameters
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")
save_progress() → None¶
This function should be called to save the state of the learned policy model.
Return type
None
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.
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]) – 
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
update_with_delayed_score(score: float, chain_response: Dict[str, Any], force_score: bool = False) → None¶
Updates the learned policy with the score provided.
Will raise an error if selection_scorer is set, and force_score=True was not provided during the method call
Parameters
score (float) – 
chain_response (Dict[str, Any]) – 
force_score (bool) – 
Return type
None
classmethod validate(value: Any) → Model¶
Parameters
value (Any) – 
Return type
Model
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]) –
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]) – 
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
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]
with_listeners(*, on_start: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]] = None, on_end: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]] = None, on_error: Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]] = None) → Runnable[Input, Output]¶
Bind lifecycle listeners to a Runnable, returning a new Runnable.
on_start: Called before the runnable starts running, with the Run object.
on_end: Called after the runnable finishes running, with the Run object.
on_error: Called if the runnable throws an error, with the Run object.
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:
from langchain_core.runnables import RunnableLambda
from langchain_core.tracers.schemas import Run
import time
def test_runnable(time_to_sleep : int):
    time.sleep(time_to_sleep)
def fn_start(run_obj: Run):
    print("start_time:", run_obj.start_time)
def fn_end(run_obj: Run):
    print("end_time:", run_obj.end_time)
chain = RunnableLambda(test_runnable).with_listeners(
    on_start=fn_start,
    on_end=fn_end
)
chain.invoke(2)
Parameters
on_end=fn_end
)
chain.invoke(2)
Parameters
on_start (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) – 
on_end (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) – 
on_error (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) – 
Return type
Runnable[Input, Output]
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.
Example:
from langchain_core.runnables import RunnableLambda
count = 0
def _lambda(x: int) -> None:
    global count
    count = count + 1
    if x == 1:
        raise ValueError("x is 1")
    else:
         pass
runnable = RunnableLambda(_lambda)
try:
    runnable.with_retry(
        stop_after_attempt=2,
        retry_if_exception_type=(ValueError,),
    ).invoke(1)
except ValueError:
    pass
assert (count == 2)
Parameters
retry_if_exception_type (Tuple[Type[BaseException], ...]) – A tuple of exception types to retry on
wait_exponential_jitter (bool) – Whether to add jitter to the wait time
between retries
stop_after_attempt (int) – The maximum number of attempts to make before giving up
Returns
A new Runnable that retries the original runnable on exceptions.
Return type
Runnable[Input, Output]
Return type
Runnable[Input, Output]
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.
Parameters
input_type (Optional[Type[Input]]) – 
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_keys: List[str]¶
Expect input key.
:meta private:
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.rl_chain.base.embed_string_type¶
langchain_experimental.rl_chain.base.embed_string_type(item: Union[str, _Embed], model: Any, namespace: Optional[str] = None) → Dict[str, Union[str, List[str]]][source]¶
Embed a string or an _Embed object.
Parameters
item (Union[str, _Embed]) – 
model (Any) – 
namespace (Optional[str]) – 
Return type
Dict[str, Union[str, List[str]]]
langchain_experimental.rl_chain.metrics.MetricsTrackerAverage¶
class langchain_experimental.rl_chain.metrics.MetricsTrackerAverage(step: int)[source]¶
Metrics Tracker Average.
Attributes
score
Methods
__init__(step)
on_decision()
on_feedback(score)
to_pandas()
Parameters
step (int) – 
__init__(step: int)[source]¶
Parameters
step (int) – 
on_decision() → None[source]¶
Return type
None
on_feedback(score: float) → None[source]¶
Parameters
score (float) – 
Return type
None
to_pandas() → pd.DataFrame[source]¶
Return type
pd.DataFrame
langchain_experimental.rl_chain.base.SelectionScorer¶
class langchain_experimental.rl_chain.base.SelectionScorer[source]¶
Bases: Generic[TEvent], ABC, BaseModel
Abstract class to grade the chosen selection or the response of the llm.
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
Parameters
_fields_set (Optional[SetStr]) – 
values (Any) – 
Return type
Model
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 (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
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
self (Model) – 
Returns
new model instance
Return type
Model
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.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
Return type
DictStrAny
classmethod from_orm(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
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().
Parameters
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
encoder (Optional[Callable[[Any], Any]]) – 
models_as_dict (bool) – 
dumps_kwargs (Any) – 
Return type
unicode
classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
Parameters
path (Union[str, Path]) – 
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
classmethod parse_obj(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
Parameters
b (Union[str, bytes]) – 
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
Return type
DictStrAny
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
abstract score_response(inputs: Dict[str, Any], llm_response: str, event: TEvent) → float[source]¶
Parameters
inputs (Dict[str, Any]) – 
llm_response (str) – 
event (TEvent) – 
Return type
float
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
langchain_experimental.rl_chain.metrics.MetricsTrackerRollingWindow¶
class langchain_experimental.rl_chain.metrics.MetricsTrackerRollingWindow(window_size: int, step: int)[source]¶
Metrics Tracker Rolling Window.
Attributes
score
Methods
__init__(window_size, step)
on_decision()
on_feedback(value)
to_pandas()
Parameters
window_size (int) – 
step (int) – 
__init__(window_size: int, step: int)[source]¶
Parameters
window_size (int) – 
step (int) – 
on_decision() → None[source]¶
Return type
None
on_feedback(value: float) → None[source]¶
Parameters
value (float) – 
Return type
None
to_pandas() → pd.DataFrame[source]¶
Return type
pd.DataFrame
langchain_experimental.rl_chain.base.Event¶
class langchain_experimental.rl_chain.base.Event(inputs: Dict[str, Any], selected: Optional[TSelected] = None)[source]¶
Abstract class to represent an event.
Attributes
inputs
selected
Methods
__init__(inputs[, selected])
Parameters
inputs (Dict[str, Any]) – 
selected (Optional[TSelected]) – 
__init__(inputs: Dict[str, Any], selected: Optional[TSelected] = None)[source]¶
Parameters
inputs (Dict[str, Any]) – 
selected (Optional[TSelected]) –
langchain_experimental.rl_chain.pick_best_chain.PickBestSelected¶
class langchain_experimental.rl_chain.pick_best_chain.PickBestSelected(index: Optional[int] = None, probability: Optional[float] = None, score: Optional[float] = None)[source]¶
Selected class for PickBest chain.
Attributes
index
probability
score
Methods
__init__([index, probability, score])
Parameters
index (Optional[int]) – 
probability (Optional[float]) – 
score (Optional[float]) – 
__init__(index: Optional[int] = None, probability: Optional[float] = None, score: Optional[float] = None)[source]¶
Parameters
index (Optional[int]) – 
probability (Optional[float]) – 
score (Optional[float]) –
langchain_experimental.rl_chain.vw_logger.VwLogger¶
class langchain_experimental.rl_chain.vw_logger.VwLogger(path: Optional[Union[str, PathLike]])[source]¶
Vowpal Wabbit custom logger.
Methods
__init__(path)
log(vw_ex)
logging_enabled()
Parameters
path (Optional[Union[str, PathLike]]) – 
__init__(path: Optional[Union[str, PathLike]])[source]¶
Parameters
path (Optional[Union[str, PathLike]]) – 
log(vw_ex: str) → None[source]¶
Parameters
vw_ex (str) – 
Return type
None
logging_enabled() → bool[source]¶
Return type
bool
langchain_experimental.rl_chain.pick_best_chain.PickBestEvent¶
class langchain_experimental.rl_chain.pick_best_chain.PickBestEvent(inputs: Dict[str, Any], to_select_from: Dict[str, Any], based_on: Dict[str, Any], selected: Optional[PickBestSelected] = None)[source]¶
Event class for PickBest chain.
Attributes
Methods
__init__(inputs, to_select_from, based_on[, ...])
Parameters
inputs (Dict[str, Any]) – 
to_select_from (Dict[str, Any]) – 
based_on (Dict[str, Any]) – 
selected (Optional[TSelected]) – 
__init__(inputs: Dict[str, Any], to_select_from: Dict[str, Any], based_on: Dict[str, Any], selected: Optional[PickBestSelected] = None)[source]¶
Parameters
inputs (Dict[str, Any]) – 
to_select_from (Dict[str, Any]) – 
based_on (Dict[str, Any]) – 
selected (Optional[PickBestSelected]) –
langchain_experimental.rl_chain.base.prepare_inputs_for_autoembed¶
langchain_experimental.rl_chain.base.prepare_inputs_for_autoembed(inputs: Dict[str, Any]) → Dict[str, Any][source]¶
Prepare the inputs for auto embedding.
Go over all the inputs and if something is either wrapped in _ToSelectFrom or _BasedOn, and if their inner values are not already _Embed,
then wrap them in EmbedAndKeep while retaining their _ToSelectFrom or _BasedOn status
Parameters
inputs (Dict[str, Any]) – 
Return type
Dict[str, Any]
langchain_experimental.rl_chain.base.parse_lines¶
langchain_experimental.rl_chain.base.parse_lines(parser: vw.TextFormatParser, input_str: str) → List['vw.Example'][source]¶
Parse the input string into a list of examples.
Parameters
parser (vw.TextFormatParser) – 
input_str (str) – 
Return type
List[‘vw.Example’]
langchain_experimental.rl_chain.base.get_based_on_and_to_select_from¶
langchain_experimental.rl_chain.base.get_based_on_and_to_select_from(inputs: Dict[str, Any]) → Tuple[Dict, Dict][source]¶
Get the BasedOn and ToSelectFrom from the inputs.
Parameters
inputs (Dict[str, Any]) – 
Return type
Tuple[Dict, Dict]
langchain_experimental.rl_chain.pick_best_chain.PickBestRandomPolicy¶
class langchain_experimental.rl_chain.pick_best_chain.PickBestRandomPolicy(feature_embedder: Embedder, **kwargs: Any)[source]¶
Random policy for PickBest chain.
Methods
__init__(feature_embedder, **kwargs)
learn(event)
log(event)
predict(event)
save()
Parameters
feature_embedder (base.Embedder) – 
kwargs (Any) – 
__init__(feature_embedder: Embedder, **kwargs: Any)[source]¶
Parameters
feature_embedder (Embedder) – 
kwargs (Any) – 
learn(event: PickBestEvent) → None[source]¶
Parameters
event (PickBestEvent) – 
Return type
None
log(event: PickBestEvent) → None[source]¶
Parameters
event (PickBestEvent) – 
Return type
None
predict(event: PickBestEvent) → List[Tuple[int, float]][source]¶
Parameters
event (PickBestEvent) – 
Return type
List[Tuple[int, float]]
save() → None¶
Return type
None
langchain_prompty.langchain.create_chat_prompt¶
langchain_prompty.langchain.create_chat_prompt(path: str, input_name_agent_scratchpad: str = 'agent_scratchpad') → Runnable[Dict[str, Any], ChatPromptTemplate][source]¶
Parameters
path (str) – 
input_name_agent_scratchpad (str) – 
Return type
Runnable[Dict[str, Any], ChatPromptTemplate]
langchain_core.structured_query.Visitor¶
class langchain_core.structured_query.Visitor[source]¶
Defines interface for IR translation using visitor pattern.
Attributes
allowed_comparators
allowed_operators
Methods
__init__()
visit_comparison(comparison)
Translate a Comparison.
visit_operation(operation)
Translate an Operation.
visit_structured_query(structured_query)
Translate a StructuredQuery.
__init__()¶
abstract visit_comparison(comparison: Comparison) → Any[source]¶
Translate a Comparison.
Parameters
comparison (Comparison) – 
Return type
Any
abstract visit_operation(operation: Operation) → Any[source]¶
Translate an Operation.
Parameters
operation (Operation) – 
Return type
Any
abstract visit_structured_query(structured_query: StructuredQuery) → Any[source]¶
Translate a StructuredQuery.
Parameters
structured_query (StructuredQuery) – 
Return type
Any