Tony20100/langchain_full huggingface dataset:
Transform a single input into an output. Override to implement.
Parameters
input (Input) – 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.
Returns
The output of the runnable.
Return type
Dict[str, Any]
classmethod is_lc_serializable() → bool[source]¶
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]]) – 
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) –
Parameters
by_alias (bool) – 
ref_template (unicode) – 
dumps_kwargs (Any) – 
Return type
unicode
stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Dict[str, Any]][source]¶
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[Dict[str, Any]]
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: Any) → Iterator[Dict[str, Any]][source]¶
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 (Any) – 
Return type
Iterator[Dict[str, Any]]
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
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]
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[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.
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.
Examples using RunnableParallel¶
Exa Search
Google Cloud Vertex AI Reranker
How to add message history
How to add values to a chain’s state
How to chain runnables
How to get a RAG application to add citations
How to invoke runnables in parallel
How to pass through arguments from one step to the next
How to retry when a parsing error occurs
LangChain Expression Language Cheatsheet
ZepCloudChatMessageHistory
langchain_core.runnables.graph.Graph¶
class langchain_core.runnables.graph.Graph(nodes: ~typing.Dict[str, ~langchain_core.runnables.graph.Node] = <factory>, edges: ~typing.List[~langchain_core.runnables.graph.Edge] = <factory>)[source]¶
Graph of nodes and edges.
Attributes
nodes
edges
Methods
__init__([nodes, edges])
add_edge(source, target[, data, conditional])
Add an edge to the graph and return it.
add_node(data[, id])
Add a node to the graph and return it.
draw_ascii()
draw_mermaid(*[, with_styles, curve_style, ...])
draw_mermaid_png(*[, curve_style, ...])
draw_png()
extend(graph, *[, prefix])
Add all nodes and edges from another graph.
first_node()
Find the single node that is not a target of any edge.
last_node()
Find the single node that is not a source of any edge.
next_id()
print_ascii()
remove_node(node)
Remove a node from the graphm and all edges connected to it.
to_json(*[, with_schemas])
Convert the graph to a JSON-serializable format.
trim_first_node()
Remove the first node if it exists and has a single outgoing edge, ie.
trim_last_node()
Remove the last node if it exists and has a single incoming edge, ie.
Parameters
nodes (Dict[str, Node]) – 
edges (List[Edge]) – 
__init__(nodes: ~typing.Dict[str, ~langchain_core.runnables.graph.Node] = <factory>, edges: ~typing.List[~langchain_core.runnables.graph.Edge] = <factory>) → None¶
Parameters
Parameters
nodes (Dict[str, Node]) – 
edges (List[Edge]) – 
Return type
None
add_edge(source: Node, target: Node, data: Optional[str] = None, conditional: bool = False) → Edge[source]¶
Add an edge to the graph and return it.
Parameters
source (Node) – 
target (Node) – 
data (Optional[str]) – 
conditional (bool) – 
Return type
Edge
add_node(data: Union[Type[BaseModel], RunnableType], id: Optional[str] = None) → Node[source]¶
Add a node to the graph and return it.
Parameters
data (Union[Type[BaseModel], RunnableType]) – 
id (Optional[str]) – 
Return type
Node
draw_ascii() → str[source]¶
Return type
str
draw_mermaid(*, with_styles: bool = True, curve_style: CurveStyle = CurveStyle.LINEAR, node_colors: NodeColors = NodeColors(start='#ffdfba', end='#baffc9', other='#fad7de'), wrap_label_n_words: int = 9) → str[source]¶
Parameters
with_styles (bool) – 
curve_style (CurveStyle) – 
node_colors (NodeColors) – 
wrap_label_n_words (int) – 
Return type
str
draw_mermaid_png(*, curve_style: CurveStyle = CurveStyle.LINEAR, node_colors: NodeColors = NodeColors(start='#ffdfba', end='#baffc9', other='#fad7de'), wrap_label_n_words: int = 9, output_file_path: Optional[str] = None, draw_method: MermaidDrawMethod = MermaidDrawMethod.API, background_color: str = 'white', padding: int = 10) → bytes[source]¶
Parameters
Parameters
curve_style (CurveStyle) – 
node_colors (NodeColors) – 
wrap_label_n_words (int) – 
output_file_path (Optional[str]) – 
draw_method (MermaidDrawMethod) – 
background_color (str) – 
padding (int) – 
Return type
bytes
draw_png(output_file_path: str, fontname: Optional[str] = None, labels: Optional[LabelsDict] = None) → None[source]¶
draw_png(output_file_path: None, fontname: Optional[str] = None, labels: Optional[LabelsDict] = None) → bytes
extend(graph: Graph, *, prefix: str = '') → Tuple[Optional[Node], Optional[Node]][source]¶
Add all nodes and edges from another graph.
Note this doesn’t check for duplicates, nor does it connect the graphs.
Parameters
graph (Graph) – 
prefix (str) – 
Return type
Tuple[Optional[Node], Optional[Node]]
first_node() → Optional[Node][source]¶
Find the single node that is not a target of any edge.
If there is no such node, or there are multiple, return None.
When drawing the graph this node would be the origin.
Return type
Optional[Node]
last_node() → Optional[Node][source]¶
Find the single node that is not a source of any edge.
If there is no such node, or there are multiple, return None.
When drawing the graph this node would be the destination.
Return type
Optional[Node]
next_id() → str[source]¶
Return type
str
print_ascii() → None[source]¶
Return type
None
remove_node(node: Node) → None[source]¶
Remove a node from the graphm and all edges connected to it.
Parameters
Remove a node from the graphm and all edges connected to it.
Parameters
node (Node) – 
Return type
None
to_json(*, with_schemas: bool = False) → Dict[str, List[Dict[str, Any]]][source]¶
Convert the graph to a JSON-serializable format.
Parameters
with_schemas (bool) – 
Return type
Dict[str, List[Dict[str, Any]]]
trim_first_node() → None[source]¶
Remove the first node if it exists and has a single outgoing edge,
ie. if removing it would not leave the graph without a “first” node.
Return type
None
trim_last_node() → None[source]¶
Remove the last node if it exists and has a single incoming edge,
ie. if removing it would not leave the graph without a “last” node.
Return type
None
langchain_core.runnables.graph.node_data_json¶
langchain_core.runnables.graph.node_data_json(node: Node, *, with_schemas: bool = False) → Dict[str, Union[str, Dict[str, Any]]][source]¶
Convert the data of a node to a JSON-serializable format.
Parameters
node (Node) – The node to convert.
with_schemas (bool) – Whether to include the schema of the data if
it is a Pydantic model.
Returns
A dictionary with the type of the data and the data itself.
Return type
Dict[str, Union[str, Dict[str, Any]]]
langchain_core.runnables.graph_ascii.AsciiCanvas¶
class langchain_core.runnables.graph_ascii.AsciiCanvas(cols: int, lines: int)[source]¶
Class for drawing in ASCII.
Parameters
cols (int) – number of columns in the canvas. Should be > 1.
lines (int) – number of lines in the canvas. Should be > 1.
Attributes
TIMEOUT
Methods
__init__(cols, lines)
box(x0, y0, width, height)
Create a box on ASCII canvas.
draw()
Draws ASCII canvas on the screen.
line(x0, y0, x1, y1, char)
Create a line on ASCII canvas.
point(x, y, char)
Create a point on ASCII canvas.
text(x, y, text)
Print a text on ASCII canvas.
__init__(cols: int, lines: int) → None[source]¶
Parameters
cols (int) – 
lines (int) – 
Return type
None
box(x0: int, y0: int, width: int, height: int) → None[source]¶
Create a box on ASCII canvas.
Parameters
x0 (int) – x coordinate of the box corner.
y0 (int) – y coordinate of the box corner.
width (int) – box width.
height (int) – box height.
Return type
None
draw() → str[source]¶
Draws ASCII canvas on the screen.
Return type
str
line(x0: int, y0: int, x1: int, y1: int, char: str) → None[source]¶
Create a line on ASCII canvas.
Parameters
Create a line on ASCII canvas.
Parameters
x0 (int) – x coordinate where the line should start.
y0 (int) – y coordinate where the line should start.
x1 (int) – x coordinate where the line should end.
y1 (int) – y coordinate where the line should end.
char (str) – character to draw the line with.
Return type
None
point(x: int, y: int, char: str) → None[source]¶
Create a point on ASCII canvas.
Parameters
x (int) – x coordinate. Should be >= 0 and < number of columns in
the canvas.
y (int) – y coordinate. Should be >= 0 an < number of lines in the
canvas.
char (str) – character to place in the specified point on the
canvas.
Return type
None
text(x: int, y: int, text: str) → None[source]¶
Print a text on ASCII canvas.
Parameters
x (int) – x coordinate where the text should start.
y (int) – y coordinate where the text should start.
text (str) – string that should be printed.
Return type
None
langchain_core.runnables.router.RouterRunnable¶
class langchain_core.runnables.router.RouterRunnable[source]¶
Bases: RunnableSerializable[RouterInput, Output]
Runnable that routes to a set of Runnables based on Input[‘key’].
Returns the output of the selected Runnable.
For example,
from langchain_core.runnables.router import RouterRunnable
from langchain_core.runnables import RunnableLambda
add = RunnableLambda(func=lambda x: x + 1)
square = RunnableLambda(func=lambda x: x**2)
router = RouterRunnable(runnables={"add": add, "square": square})
router.invoke({"key": "square", "input": 3})
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 runnables: Mapping[str, Runnable[Any, Output]] [Required]¶
async abatch(inputs: List[RouterInput], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output][source]¶
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[RouterInput]) – 
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
List[Output]
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: RouterInput, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Output[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 (RouterInput) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
Output
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.
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
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: RouterInput, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output][source]¶
Default implementation of astream, which calls ainvoke.
Subclasses should override this method if they support streaming output.
Parameters
input (RouterInput) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
AsyncIterator[Output]
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: Optional[Any]) → AsyncIterator[Output]¶
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 (Optional[Any]) – 
Return type
AsyncIterator[Output]
batch(inputs: List[RouterInput], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output][source]¶
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[RouterInput]) – 
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
inputs (Sequence[Input]) –
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¶
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]
get_prompts(config: Optional[RunnableConfig] = None) → List[BasePromptTemplate]¶
Parameters
config (Optional[RunnableConfig]) – 
Return type
List[BasePromptTemplate]
invoke(input: RouterInput, config: Optional[RunnableConfig] = None) → Output[source]¶
Transform a single input into an output. Override to implement.
Parameters
input (RouterInput) – The input to the runnable.
Parameters
input (RouterInput) – 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.
Returns
The output of the runnable.
Return type
Output
classmethod is_lc_serializable() → bool[source]¶
Return whether this class is 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]]) – 
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 lc_id() → List[str]¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
dumps_kwargs (Any) – 
Return type
unicode
stream(input: RouterInput, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output][source]¶
Default implementation of stream, which calls invoke.
Subclasses should override this method if they support streaming output.
Parameters
input (RouterInput) – 
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]) – 
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
with_alisteners(*, on_start: Optional[AsyncListener] = None, on_end: Optional[AsyncListener] = None, on_error: Optional[AsyncListener] = None) → Runnable[Input, Output]¶
langchain_core.runnables.configurable.make_options_spec¶
langchain_core.runnables.configurable.make_options_spec(spec: Union[ConfigurableFieldSingleOption, ConfigurableFieldMultiOption], description: Optional[str]) → ConfigurableFieldSpec[source]¶
Make a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or
ConfigurableFieldMultiOption.
Parameters
spec (Union[ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) – 
description (Optional[str]) – 
Return type
ConfigurableFieldSpec