Tony20100/langchain_full huggingface dataset:
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]
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: Any¶
The type of input this runnable accepts specified as a type annotation.
property OutputType: Type[List[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]¶
langchain_core.runnables.utils.indent_lines_after_first¶
langchain_core.runnables.utils.indent_lines_after_first(text: str, prefix: str) → str[source]¶
Indent all lines of text after the first line.
Parameters
text (str) – The text to indent
prefix (str) – Used to determine the number of spaces to indent
Returns
The indented text
Return type
str
langchain_core.runnables.schema.EventData¶
class langchain_core.runnables.schema.EventData[source]¶
Data associated with a streaming event.
Attributes
input
The input passed to the runnable that generated the event.
output
The output of the Runnable that generated the event.
chunk
A streaming chunk from the output that generated the event.
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.
get(key, default=None, /)¶
Return the value for key if key is in the dictionary, else default.
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.runnables.graph_ascii.VertexViewer¶
class langchain_core.runnables.graph_ascii.VertexViewer(name: str)[source]¶
Class to define vertex box boundaries that will be accounted for during
graph building by grandalf.
Parameters
name (str) – name of the vertex.
Attributes
HEIGHT
h
Height of the box.
w
Width of the box.
Methods
__init__(name)
__init__(name: str) → None[source]¶
Parameters
name (str) – 
Return type
None
langchain_core.runnables.config.acall_func_with_variable_args¶
langchain_core.runnables.config.acall_func_with_variable_args(func: Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]], input: Input, config: RunnableConfig, run_manager: Optional[AsyncCallbackManagerForChainRun] = None, **kwargs: Any) → Awaitable[Output][source]¶
Call function that may optionally accept a run_manager and/or config.
Parameters
(Union[Callable[[Input] (func) – AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,
AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):
The function to call.
Awaitable[Output]] – AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,
AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):
The function to call.
Callable[[Input – AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,
AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):
The function to call.
func (Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]) – 
input (Input) – 
config (RunnableConfig) – 
run_manager (Optional[AsyncCallbackManagerForChainRun]) – 
kwargs (Any) – 
Return type
Awaitable[Output]
kwargs (Any) – 
Return type
Awaitable[Output]
:paramAsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input,AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]):
The function to call.
Parameters
input (Input) – The input to the function.
run_manager (AsyncCallbackManagerForChainRun) – The run manager
to pass to the function.
config (RunnableConfig) – The config to pass to the function.
**kwargs (Any) – The keyword arguments to pass to the function.
func (Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]) – 
Returns
The output of the function.
Return type
Output
langchain_core.runnables.graph_png.PngDrawer¶
class langchain_core.runnables.graph_png.PngDrawer(fontname: Optional[str] = None, labels: Optional[LabelsDict] = None)[source]¶
Helper class to draw a state graph into a PNG file.
It requires graphviz and pygraphviz to be installed.
:param fontname: The font to use for the labels
:param labels: A dictionary of label overrides. The dictionary
should have the following format:
{
“nodes”: {“node1”: “CustomLabel1”,
“node2”: “CustomLabel2”,
“__end__”: “End Node”
},
“edges”: {
“continue”: “ContinueLabel”,
“end”: “EndLabel”
}
}
The keys are the original labels, and the values are the new labels.
Usage:drawer = PngDrawer()
drawer.draw(state_graph, ‘graph.png’)
Initializes the PNG drawer.
Parameters
fontname (Optional[str]) – The font to use for the labels
labels (Optional[LabelsDict]) – A dictionary of label overrides. The dictionary
should have the following format:
{
”nodes”: {“node1”: “CustomLabel1”,
“node2”: “CustomLabel2”,
“__end__”: “End Node”
},
“edges”: {
”continue”: “ContinueLabel”,
“end”: “EndLabel”
}
}
The keys are the original labels, and the values are the new labels.
Methods
__init__([fontname, labels])
Initializes the PNG drawer.
add_edge(viz, source, target[, label, ...])
Adds an edge to the graph.
add_edges(viz, graph)
add_node(viz, node)
Adds a node to the graph.
add_node(viz, node)
Adds a node to the graph.
add_nodes(viz, graph)
draw(graph[, output_path])
Draw the given state graph into a PNG file.
get_edge_label(label)
Returns the label to use for an edge.
get_node_label(label)
Returns the label to use for a node.
update_styles(viz, graph)
__init__(fontname: Optional[str] = None, labels: Optional[LabelsDict] = None) → None[source]¶
Initializes the PNG drawer.
Parameters
fontname (Optional[str]) – The font to use for the labels
labels (Optional[LabelsDict]) – A dictionary of label overrides. The dictionary
should have the following format:
{
”nodes”: {“node1”: “CustomLabel1”,
“node2”: “CustomLabel2”,
“__end__”: “End Node”
},
“edges”: {
”continue”: “ContinueLabel”,
“end”: “EndLabel”
}
}
The keys are the original labels, and the values are the new labels.
Return type
None
add_edge(viz: Any, source: str, target: str, label: Optional[str] = None, conditional: bool = False) → None[source]¶
Adds an edge to the graph.
Parameters
viz (Any) – The graphviz object
source (str) – The source node
target (str) – The target node
label (Optional[str]) – The label for the edge. Defaults to None.
conditional (bool) – Whether the edge is conditional. Defaults to False.
Returns
None
Return type
None
add_edges(viz: Any, graph: Graph) → None[source]¶
Parameters
viz (Any) – 
graph (Graph) – 
Return type
None
viz (Any) – 
graph (Graph) – 
Return type
None
add_node(viz: Any, node: str) → None[source]¶
Adds a node to the graph.
Parameters
viz (Any) – The graphviz object
node (str) – The node to add
Returns
None
Return type
None
add_nodes(viz: Any, graph: Graph) → None[source]¶
Parameters
viz (Any) – 
graph (Graph) – 
Return type
None
draw(graph: Graph, output_path: Optional[str] = None) → Optional[bytes][source]¶
Draw the given state graph into a PNG file.
Requires graphviz and pygraphviz to be installed.
:param graph: The graph to draw
:param output_path: The path to save the PNG. If None, PNG bytes are returned.
Parameters
graph (Graph) – 
output_path (Optional[str]) – 
Return type
Optional[bytes]
get_edge_label(label: str) → str[source]¶
Returns the label to use for an edge.
Parameters
label (str) – The original label
Returns
The new label.
Return type
str
get_node_label(label: str) → str[source]¶
Returns the label to use for a node.
Parameters
label (str) – The original label
Returns
The new label.
Return type
str
update_styles(viz: Any, graph: Graph) → None[source]¶
Parameters
viz (Any) – 
graph (Graph) – 
Return type
None
langchain_core.runnables.graph.Branch¶
class langchain_core.runnables.graph.Branch(condition: Callable[..., str], ends: Optional[dict[str, str]])[source]¶
Branch in a graph.
Create new instance of Branch(condition, ends)
Attributes
condition
Alias for field number 0
ends
Alias for field number 1
Methods
__init__()
count(value, /)
Return number of occurrences of value.
index(value[, start, stop])
Return first index of value.
Parameters
condition (Callable[[...], str]) – 
ends (Optional[dict[str, str]]) – 
__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.
langchain_core.runnables.config.get_config_list¶
langchain_core.runnables.config.get_config_list(config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]], length: int) → List[RunnableConfig][source]¶
Get a list of configs from a single config or a list of configs.
It is useful for subclasses overriding batch() or abatch().
Parameters
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – The config or list of configs.
length (int) – The length of the list.
Returns
The list of configs.
Return type
List[RunnableConfig]
Raises
ValueError – If the length of the list is not equal to the length of the inputs.
langchain_core.runnables.base.RunnableParallel¶
class langchain_core.runnables.base.RunnableParallel[source]¶
Bases: RunnableSerializable[Input, Dict[str, Any]]
Runnable that runs a mapping of Runnables in parallel, and returns a mapping
of their outputs.
RunnableParallel is one of the two main composition primitives for the LCEL,
alongside RunnableSequence. It invokes Runnables concurrently, providing the same
input to each.
A RunnableParallel can be instantiated directly or by using a dict literal within a
sequence.
Here is a simple example that uses functions to illustrate the use of
RunnableParallel:
from langchain_core.runnables import RunnableLambda
def add_one(x: int) -> int:
    return x + 1
def mul_two(x: int) -> int:
    return x * 2
def mul_three(x: int) -> int:
    return x * 3
runnable_1 = RunnableLambda(add_one)
runnable_2 = RunnableLambda(mul_two)
runnable_3 = RunnableLambda(mul_three)
sequence = runnable_1 | {  # this dict is coerced to a RunnableParallel
    "mul_two": runnable_2,
    "mul_three": runnable_3,
}
# Or equivalently:
# sequence = runnable_1 | RunnableParallel(
#     {"mul_two": runnable_2, "mul_three": runnable_3}
# )
# Also equivalently:
# sequence = runnable_1 | RunnableParallel(
#     mul_two=runnable_2,
#     mul_three=runnable_3,
# )
sequence.invoke(1)
await sequence.ainvoke(1)
sequence.batch([1, 2, 3])
await sequence.abatch([1, 2, 3])
await sequence.abatch([1, 2, 3])
RunnableParallel makes it easy to run Runnables in parallel. In the below example,
we simultaneously stream output from two different Runnables:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableParallel
from langchain_openai import ChatOpenAI
model = ChatOpenAI()
joke_chain = (
    ChatPromptTemplate.from_template("tell me a joke about {topic}")
    | model
)
poem_chain = (
    ChatPromptTemplate.from_template("write a 2-line poem about {topic}")
    | model
)
runnable = RunnableParallel(joke=joke_chain, poem=poem_chain)
# Display stream
output = {key: "" for key, _ in runnable.output_schema()}
for chunk in runnable.stream({"topic": "bear"}):
    for key in chunk:
        output[key] = output[key] + chunk[key].content
    print(output)  # noqa: T201
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 steps__: Mapping[str, Runnable[Input, Any]] [Required]¶
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]) –
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]]]
async ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Dict[str, Any][source]¶
Default implementation of ainvoke, calls invoke from a thread.
The default implementation allows usage of async code even if
the runnable did not implement a native async version of invoke.
Subclasses should override this method if they can run asynchronously.
Parameters
input (Input) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
Dict[str, Any]
assign(**kwargs: Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any], Mapping[str, Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]]]]) → RunnableSerializable[Any, Any]¶
Assigns new fields to the dict output of this runnable.
Returns a new runnable.
Assigns new fields to the dict output of this runnable.
Returns a new runnable.
from langchain_community.llms.fake import FakeStreamingListLLM
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import SystemMessagePromptTemplate
from langchain_core.runnables import Runnable
from operator import itemgetter
prompt = (
    SystemMessagePromptTemplate.from_template("You are a nice assistant.")
    + "{question}"
)
llm = FakeStreamingListLLM(responses=["foo-lish"])
chain: Runnable = prompt | llm | {"str": StrOutputParser()}
chain_with_assign = chain.assign(hello=itemgetter("str") | llm)
print(chain_with_assign.input_schema.schema())
# {'title': 'PromptInput', 'type': 'object', 'properties':
{'question': {'title': 'Question', 'type': 'string'}}}
print(chain_with_assign.output_schema.schema()) #
{'title': 'RunnableSequenceOutput', 'type': 'object', 'properties':
{'str': {'title': 'Str',
'type': 'string'}, 'hello': {'title': 'Hello', 'type': 'string'}}}
Parameters
kwargs (Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any], Mapping[str, Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]]]]) – 
Return type
RunnableSerializable[Any, Any]
async astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Dict[str, Any]][source]¶
Default implementation of astream, which calls ainvoke.
Subclasses should override this method if they support streaming output.
Parameters
input (Input) – 
config (Optional[RunnableConfig]) –
Parameters
input (Input) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
AsyncIterator[Dict[str, Any]]
astream_events(input: Any, config: Optional[RunnableConfig] = None, *, version: Literal['v1', 'v2'], include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Any) → AsyncIterator[StreamEvent]¶
[Beta] Generate a stream of events.
Use to create an iterator over StreamEvents that provide real-time information
about the progress of the runnable, including StreamEvents from intermediate
results.
A StreamEvent is a dictionary with the following schema:
event: str - Event names are of theformat: on_[runnable_type]_(start|stream|end).
name: str - The name of the runnable that generated the event.
run_id: str - randomly generated ID associated with the given execution ofthe runnable that emitted the event.
A child runnable that gets invoked as part of the execution of a
parent runnable is assigned its own unique ID.
parent_ids: List[str] - The IDs of the parent runnables thatgenerated the event. The root runnable will have an empty list.
The order of the parent IDs is from the root to the immediate parent.
Only available for v2 version of the API. The v1 version of the API
will return an empty list.
tags: Optional[List[str]] - The tags of the runnable that generatedthe event.
metadata: Optional[Dict[str, Any]] - The metadata of the runnablethat generated the event.
exclude_tags (Optional[Sequence[str]]) – Exclude logs with these tags.
kwargs (Any) – 
Return type
Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]
async atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Any) → AsyncIterator[Dict[str, Any]][source]¶
Default implementation of atransform, which buffers input and calls astream.
Subclasses should override this method if they can start producing output while
input is still being generated.
Parameters
input (AsyncIterator[Input]) – 
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
AsyncIterator[Dict[str, Any]]
batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶
Default implementation runs invoke in parallel using a thread pool executor.
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]
batch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → Iterator[Tuple[int, Union[Output, Exception]]]¶
Run invoke in parallel on a list of inputs,
yielding results as they complete.
Parameters
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][source]¶
Get the namespace of the langchain object.
Return type
List[str]
get_name(suffix: Optional[str] = None, *, name: Optional[str] = None) → str[source]¶
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][source]¶
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]
get_prompts(config: Optional[RunnableConfig] = None) → List[BasePromptTemplate]¶
Parameters
config (Optional[RunnableConfig]) – 
Return type
List[BasePromptTemplate]
invoke(input: Input, config: Optional[RunnableConfig] = None) → Dict[str, Any][source]¶
Transform a single input into an output. Override to implement.
Parameters