- class langgraph_agent_toolkit.core.prompts.chat_prompt_template.ObservabilityChatPromptTemplate(messages=None, *, prompt_name=None, prompt_version=None, prompt_label=None, load_at_runtime=False, observability_platform=None, observability_backend=None, cache_ttl_seconds=600, template_format='f-string', input_variables=None, partial_variables=None, name=None, optional_variables=[], input_types=<factory>, output_parser=None, metadata=None, tags=None, validate_template=False, **kwargs)[source][source]
Bases:
ChatPromptTemplate
A chat prompt template that loads prompts from observability platforms.
Initialize ObservabilityChatPromptTemplate.
- Parameters:
messages (Annotated[list[BaseMessagePromptTemplate | BaseMessage | BaseChatPromptTemplate], SkipValidation()])
prompt_name (str | None)
prompt_version (int | None)
prompt_label (str | None)
load_at_runtime (bool)
observability_platform (BaseObservabilityPlatform | None)
observability_backend (ObservabilityBackend | None)
cache_ttl_seconds (int)
template_format (str)
name (str | None)
output_parser (BaseOutputParser | None)
validate_template (bool)
kwargs (Any)
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'allow', 'protected_namespaces': ()}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- __init__(messages=None, *, prompt_name=None, prompt_version=None, prompt_label=None, load_at_runtime=False, observability_platform=None, observability_backend=None, cache_ttl_seconds=DEFAULT_CACHE_TTL_SECOND, template_format='f-string', input_variables=None, partial_variables=None, **kwargs)[source][source]
Initialize ObservabilityChatPromptTemplate.
- Parameters:
messages (Sequence[BaseMessagePromptTemplate | BaseMessage | BaseChatPromptTemplate | tuple[str | type, str | list[dict] | list[object]] | str | dict[str, Any]] | None)
prompt_name (str | None)
prompt_version (int | None)
prompt_label (str | None)
load_at_runtime (bool)
observability_platform (BaseObservabilityPlatform | None)
observability_backend (ObservabilityBackend | str | None)
cache_ttl_seconds (int)
template_format (Literal['f-string', 'mustache', 'jinja2'])
kwargs (Any)
- observability_backend: ObservabilityBackend | None
- input_variables: list[str]
A list of the names of the variables whose values are required as inputs to the prompt.
- partial_variables: Mapping[str, Any]
A dictionary of the partial variables the prompt template carries.
Partial variables populate the template so that you don’t need to pass them in every time you call the prompt.
- property observability_platform: BaseObservabilityPlatform | None
Get the observability platform.
- property InputType: type[Input]
The type of input this Runnable accepts specified as a type annotation.
- async abatch(inputs, config=None, *, return_exceptions=False, **kwargs)[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[Input]) – A list of inputs to the Runnable.
config (RunnableConfig | list[RunnableConfig] | None) – 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. Defaults to None.
return_exceptions (bool) – Whether to return exceptions instead of raising them. Defaults to False.
kwargs (Any | None) – Additional keyword arguments to pass to the Runnable.
- Returns:
A list of outputs from the Runnable.
- Return type:
list[Output]
- async abatch_as_completed(inputs, config=None, *, return_exceptions=False, **kwargs)[source]
Run ainvoke in parallel on a list of inputs.
Yields results as they complete.
- Parameters:
inputs (Sequence[Input]) – A list of inputs to the Runnable.
config (RunnableConfig | Sequence[RunnableConfig] | None) – 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. Defaults to None. Defaults to None.
return_exceptions (bool) – Whether to return exceptions instead of raising them. Defaults to False.
kwargs (Any | None) – Additional keyword arguments to pass to the Runnable.
- Yields:
A tuple of the index of the input and the output from the Runnable.
- Return type:
AsyncIterator[tuple[int, Output | Exception]]
- async aformat_messages(**kwargs)[source]
Async format the chat template into a list of finalized messages.
- Parameters:
**kwargs (Any) – keyword arguments to use for filling in template variables in all the template messages in this chat template.
- Returns:
list of formatted messages.
- Raises:
ValueError – If unexpected input.
- Return type:
list[BaseMessage]
- async aformat_prompt(**kwargs)[source]
Async format prompt. Should return a PromptValue.
- Parameters:
**kwargs (Any) – Keyword arguments to use for formatting.
- Returns:
PromptValue.
- Return type:
PromptValue
- as_tool(args_schema=None, *, name=None, description=None, arg_types=None)[source]
Create a BaseTool from a Runnable.
as_tool
will instantiate a BaseTool with a name, description, andargs_schema
from a Runnable. Where possible, schemas are inferred fromrunnable.get_input_schema
. Alternatively (e.g., if the Runnable takes a dict as input and the specific dict keys are not typed), the schema can be specified directly withargs_schema
. You can also passarg_types
to just specify the required arguments and their types.- Parameters:
args_schema (Optional[type[BaseModel]]) – The schema for the tool. Defaults to None.
name (Optional[str]) – The name of the tool. Defaults to None.
description (Optional[str]) – The description of the tool. Defaults to None.
arg_types (Optional[dict[str, type]]) – A dictionary of argument names to types. Defaults to None.
- Returns:
A BaseTool instance.
- Return type:
BaseTool
Typed dict input:
from typing_extensions import TypedDict from langchain_core.runnables import RunnableLambda class Args(TypedDict): a: int b: list[int] def f(x: Args) -> str: return str(x["a"] * max(x["b"])) runnable = RunnableLambda(f) as_tool = runnable.as_tool() as_tool.invoke({"a": 3, "b": [1, 2]})
dict
input, specifying schema viaargs_schema
:from typing import Any from pydantic import BaseModel, Field from langchain_core.runnables import RunnableLambda def f(x: dict[str, Any]) -> str: return str(x["a"] * max(x["b"])) class FSchema(BaseModel): """Apply a function to an integer and list of integers.""" a: int = Field(..., description="Integer") b: list[int] = Field(..., description="List of ints") runnable = RunnableLambda(f) as_tool = runnable.as_tool(FSchema) as_tool.invoke({"a": 3, "b": [1, 2]})
dict
input, specifying schema viaarg_types
:from typing import Any from langchain_core.runnables import RunnableLambda def f(x: dict[str, Any]) -> str: return str(x["a"] * max(x["b"])) runnable = RunnableLambda(f) as_tool = runnable.as_tool(arg_types={"a": int, "b": list[int]}) as_tool.invoke({"a": 3, "b": [1, 2]})
String input:
from langchain_core.runnables import RunnableLambda def f(x: str) -> str: return x + "a" def g(x: str) -> str: return x + "z" runnable = RunnableLambda(f) | g as_tool = runnable.as_tool() as_tool.invoke("b")
Added in version 0.2.14.
- assign(**kwargs)[source]
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.model_json_schema()) # {'title': 'PromptInput', 'type': 'object', 'properties': {'question': {'title': 'Question', 'type': 'string'}}} print(chain_with_assign.output_schema.model_json_schema()) # {'title': 'RunnableSequenceOutput', 'type': 'object', 'properties': {'str': {'title': 'Str', 'type': 'string'}, 'hello': {'title': 'Hello', 'type': 'string'}}}
- async astream(input, config=None, **kwargs)[source]
Default implementation of astream, which calls ainvoke.
Subclasses should override this method if they support streaming output.
- Parameters:
input (Input) – The input to the Runnable.
config (RunnableConfig | None) – The config to use for the Runnable. Defaults to None.
kwargs (Any | None) – Additional keyword arguments to pass to the Runnable.
- Yields:
The output of the Runnable.
- Return type:
AsyncIterator[Output]
- async astream_events(input, config=None, *, version='v2', include_names=None, include_types=None, include_tags=None, exclude_names=None, exclude_types=None, exclude_tags=None, **kwargs)[source]
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.
data
: dict[str, Any]
Below is a table that illustrates some events that might be emitted by various chains. Metadata fields have been omitted from the table for brevity. Chain definitions have been included after the table.
ATTENTION This reference table is for the V2 version of the schema.
event
name
chunk
input
output
on_chat_model_start
[model name]
{“messages”: [[SystemMessage, HumanMessage]]}
on_chat_model_stream
[model name]
AIMessageChunk(content=”hello”)
on_chat_model_end
[model name]
{“messages”: [[SystemMessage, HumanMessage]]}
AIMessageChunk(content=”hello world”)
on_llm_start
[model name]
{‘input’: ‘hello’}
on_llm_stream
[model name]
‘Hello’
on_llm_end
[model name]
‘Hello human!’
on_chain_start
format_docs
on_chain_stream
format_docs
“hello world!, goodbye world!”
on_chain_end
format_docs
[Document(…)]
“hello world!, goodbye world!”
on_tool_start
some_tool
{“x”: 1, “y”: “2”}
on_tool_end
some_tool
{“x”: 1, “y”: “2”}
on_retriever_start
[retriever name]
{“query”: “hello”}
on_retriever_end
[retriever name]
{“query”: “hello”}
[Document(…), ..]
on_prompt_start
[template_name]
{“question”: “hello”}
on_prompt_end
[template_name]
{“question”: “hello”}
ChatPromptValue(messages: [SystemMessage, …])
In addition to the standard events, users can also dispatch custom events (see example below).
Custom events will be only be surfaced with in the v2 version of the API!
A custom event has following format:
Attribute
Type
Description
name
str
A user defined name for the event.
data
Any
The data associated with the event. This can be anything, though we suggest making it JSON serializable.
Here are declarations associated with the standard events shown above:
format_docs:
def format_docs(docs: list[Document]) -> str: '''Format the docs.''' return ", ".join([doc.page_content for doc in docs]) format_docs = RunnableLambda(format_docs)
some_tool:
@tool def some_tool(x: int, y: str) -> dict: '''Some_tool.''' return {"x": x, "y": y}
prompt:
template = ChatPromptTemplate.from_messages( [("system", "You are Cat Agent 007"), ("human", "{question}")] ).with_config({"run_name": "my_template", "tags": ["my_template"]})
Example:
from langchain_core.runnables import RunnableLambda async def reverse(s: str) -> str: return s[::-1] chain = RunnableLambda(func=reverse) events = [ event async for event in chain.astream_events("hello", version="v2") ] # will produce the following events (run_id, and parent_ids # has been omitted for brevity): [ { "data": {"input": "hello"}, "event": "on_chain_start", "metadata": {}, "name": "reverse", "tags": [], }, { "data": {"chunk": "olleh"}, "event": "on_chain_stream", "metadata": {}, "name": "reverse", "tags": [], }, { "data": {"output": "olleh"}, "event": "on_chain_end", "metadata": {}, "name": "reverse", "tags": [], }, ]
Example: Dispatch Custom Event
from langchain_core.callbacks.manager import ( adispatch_custom_event, ) from langchain_core.runnables import RunnableLambda, RunnableConfig import asyncio async def slow_thing(some_input: str, config: RunnableConfig) -> str: """Do something that takes a long time.""" await asyncio.sleep(1) # Placeholder for some slow operation await adispatch_custom_event( "progress_event", {"message": "Finished step 1 of 3"}, config=config # Must be included for python < 3.10 ) await asyncio.sleep(1) # Placeholder for some slow operation await adispatch_custom_event( "progress_event", {"message": "Finished step 2 of 3"}, config=config # Must be included for python < 3.10 ) await asyncio.sleep(1) # Placeholder for some slow operation return "Done" slow_thing = RunnableLambda(slow_thing) async for event in slow_thing.astream_events("some_input", version="v2"): print(event)
- Parameters:
input (Any) – The input to the Runnable.
config (Optional[RunnableConfig]) – The config to use for the Runnable.
version (Literal['v1', 'v2']) – The version of the schema to use either v2 or v1. Users should use v2. v1 is for backwards compatibility and will be deprecated in 0.4.0. No default will be assigned until the API is stabilized. custom events will only be surfaced in v2.
include_names (Optional[Sequence[str]]) – Only include events from runnables with matching names.
include_types (Optional[Sequence[str]]) – Only include events from runnables with matching types.
include_tags (Optional[Sequence[str]]) – Only include events from runnables with matching tags.
exclude_names (Optional[Sequence[str]]) – Exclude events from runnables with matching names.
exclude_types (Optional[Sequence[str]]) – Exclude events from runnables with matching types.
exclude_tags (Optional[Sequence[str]]) – Exclude events from runnables with matching tags.
kwargs (Any) – Additional keyword arguments to pass to the Runnable. These will be passed to astream_log as this implementation of astream_events is built on top of astream_log.
- Yields:
An async stream of StreamEvents.
- Raises:
NotImplementedError – If the version is not v1 or v2.
- Return type:
AsyncIterator[StreamEvent]
- async astream_log(input, config=None, *, diff=True, with_streamed_output_list=True, include_names=None, include_types=None, include_tags=None, exclude_names=None, exclude_types=None, exclude_tags=None, **kwargs)[source]
Stream all output from a Runnable, as reported to the callback system.
This includes all inner runs of LLMs, Retrievers, Tools, etc.
Output is streamed as Log objects, which include a list of Jsonpatch ops that describe how the state of the run has changed in each step, and the final state of the run.
The Jsonpatch ops can be applied in order to construct state.
- Parameters:
input (Any) – The input to the Runnable.
config (Optional[RunnableConfig]) – The config to use for the Runnable.
diff (bool) – Whether to yield diffs between each step or the current state.
with_streamed_output_list (bool) – Whether to yield the streamed_output list.
include_names (Optional[Sequence[str]]) – Only include logs with these names.
include_types (Optional[Sequence[str]]) – Only include logs with these types.
include_tags (Optional[Sequence[str]]) – Only include logs with these tags.
exclude_names (Optional[Sequence[str]]) – Exclude logs with these names.
exclude_types (Optional[Sequence[str]]) – Exclude logs with these types.
exclude_tags (Optional[Sequence[str]]) – Exclude logs with these tags.
kwargs (Any) – Additional keyword arguments to pass to the Runnable.
- Yields:
A RunLogPatch or RunLog object.
- Return type:
Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]
- async atransform(input, config=None, **kwargs)[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]) – An async iterator of inputs to the Runnable.
config (RunnableConfig | None) – The config to use for the Runnable. Defaults to None.
kwargs (Any | None) – Additional keyword arguments to pass to the Runnable.
- Yields:
The output of the Runnable.
- Return type:
AsyncIterator[Output]
- batch(inputs, config=None, *, return_exceptions=False, **kwargs)[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.
- batch_as_completed(inputs, config=None, *, return_exceptions=False, **kwargs)[source]
Run invoke in parallel on a list of inputs.
Yields results as they complete.
- bind(**kwargs)[source]
Bind arguments to a Runnable, returning a new Runnable.
Useful when a Runnable in a chain requires an argument that is not in the output of the previous Runnable or included in the user input.
- Parameters:
kwargs (Any) – The arguments to bind to the Runnable.
- Returns:
A new Runnable with the arguments bound.
- Return type:
Runnable[Input, Output]
Example:
from langchain_community.chat_models import ChatOllama from langchain_core.output_parsers import StrOutputParser llm = ChatOllama(model='llama2') # Without bind. chain = ( llm | StrOutputParser() ) chain.invoke("Repeat quoted words exactly: 'One two three four five.'") # Output is 'One two three four five.' # With bind. chain = ( llm.bind(stop=["three"]) | StrOutputParser() ) chain.invoke("Repeat quoted words exactly: 'One two three four five.'") # Output is 'One two'
- config_schema(*, include=None)[source]
The type of config this Runnable accepts specified as a pydantic model.
To mark a field as configurable, see the configurable_fields and configurable_alternatives methods.
- configurable_alternatives(which, *, default_key='default', prefix_keys=False, **kwargs)[source]
Configure alternatives for Runnables that can be set at runtime.
- Parameters:
which (ConfigurableField) – The ConfigurableField instance that will be used to select the alternative.
default_key (str) – The default key to use if no alternative is selected. Defaults to “default”.
prefix_keys (bool) – Whether to prefix the keys with the ConfigurableField id. Defaults to False.
**kwargs (Runnable[Input, Output] | Callable[[], Runnable[Input, Output]]) – A dictionary of keys to Runnable instances or callables that return Runnable instances.
- Returns:
A new Runnable with the alternatives configured.
- Return type:
RunnableSerializable
from langchain_anthropic import ChatAnthropic from langchain_core.runnables.utils import ConfigurableField from langchain_openai import ChatOpenAI model = ChatAnthropic( model_name="claude-3-sonnet-20240229" ).configurable_alternatives( ConfigurableField(id="llm"), default_key="anthropic", openai=ChatOpenAI() ) # uses the default model ChatAnthropic print(model.invoke("which organization created you?").content) # uses ChatOpenAI print( model.with_config( configurable={"llm": "openai"} ).invoke("which organization created you?").content )
- configurable_fields(**kwargs)[source]
Configure particular Runnable fields at runtime.
- Parameters:
**kwargs (ConfigurableField | ConfigurableFieldSingleOption | ConfigurableFieldMultiOption) – A dictionary of ConfigurableField instances to configure.
- Returns:
A new Runnable with the fields configured.
- Return type:
RunnableSerializable
from langchain_core.runnables import ConfigurableField from langchain_openai import ChatOpenAI model = ChatOpenAI(max_tokens=20).configurable_fields( max_tokens=ConfigurableField( id="output_token_number", name="Max tokens in the output", description="The maximum number of tokens in the output", ) ) # max_tokens = 20 print( "max_tokens_20: ", model.invoke("tell me something about chess").content ) # max_tokens = 200 print("max_tokens_200: ", model.with_config( configurable={"output_token_number": 200} ).invoke("tell me something about chess").content )
- copy(*, include=None, exclude=None, update=None, deep=False)[source]
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `
- Parameters:
include (AbstractSetIntStr | MappingIntStrAny | None) – Optional set or mapping specifying which fields to include in the copied model.
exclude (AbstractSetIntStr | MappingIntStrAny | None) – Optional set or mapping specifying which fields to exclude in the copied model.
update (Dict[str, Any] | None) – Optional dictionary of field-value pairs to override field values in the copied model.
deep (bool) – If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- Return type:
Self
- dict(**kwargs)[source]
Return dictionary representation of prompt.
- Parameters:
kwargs (Any) – Any additional arguments to pass to the dictionary.
- Returns:
Dictionary representation of the prompt.
- Return type:
Dict
- Raises:
NotImplementedError – If the prompt type is not implemented.
- extend(messages)[source]
Extend the chat template with a sequence of messages.
- Parameters:
messages (Sequence[MessageLikeRepresentation]) – sequence of message representations to append.
- Return type:
None
- format_prompt(**kwargs)[source]
Format prompt. Should return a PromptValue.
- Parameters:
**kwargs (Any) – Keyword arguments to use for formatting.
- Returns:
PromptValue.
- Return type:
PromptValue
- classmethod from_messages(messages, template_format='f-string')[source]
Create a chat prompt template from a variety of message formats.
Examples
Instantiation from a list of message templates:
template = ChatPromptTemplate.from_messages([ ("human", "Hello, how are you?"), ("ai", "I'm doing well, thanks!"), ("human", "That's good to hear."), ])
Instantiation from mixed message formats:
template = ChatPromptTemplate.from_messages([ SystemMessage(content="hello"), ("human", "Hello, how are you?"), ])
- Parameters:
messages (Sequence[MessageLikeRepresentation]) – sequence of message representations. A message can be represented using the following formats: (1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of (message type, template); e.g., (“human”, “{user_input}”), (4) 2-tuple of (message class, template), (5) a string which is shorthand for (“human”, template); e.g., “{user_input}”.
template_format (PromptTemplateFormat) – format of the template. Defaults to “f-string”.
- Returns:
a chat prompt template.
- Return type:
ChatPromptTemplate
- classmethod from_role_strings(string_messages)[source]
Deprecated since version 0.0.1: Use
from_messages()
instead.Create a chat prompt template from a list of (role, template) tuples.
- classmethod from_strings(string_messages)[source]
Deprecated since version 0.0.1: Use
from_messages()
instead.Create a chat prompt template from a list of (role class, template) tuples.
- classmethod from_template(template, **kwargs)[source]
Create a chat prompt template from a template string.
Creates a chat template consisting of a single message assumed to be from the human.
- get_config_jsonschema(*, include=None)[source]
Get a JSON schema that represents the config of the Runnable.
- Parameters:
include (Sequence[str] | None) – A list of fields to include in the config schema.
- Returns:
A JSON schema that represents the config of the Runnable.
- Return type:
Added in version 0.3.0.
- get_graph(config=None)[source]
Return a graph representation of this Runnable.
- Parameters:
config (RunnableConfig | None)
- Return type:
Graph
- get_input_jsonschema(config=None)[source]
Get a JSON schema that represents the input to the Runnable.
- Parameters:
config (RunnableConfig | None) – A config to use when generating the schema.
- Returns:
A JSON schema that represents the input to the Runnable.
- Return type:
Example
from langchain_core.runnables import RunnableLambda def add_one(x: int) -> int: return x + 1 runnable = RunnableLambda(add_one) print(runnable.get_input_jsonschema())
Added in version 0.3.0.
- get_input_schema(config=None)[source]
Get the input schema for the prompt.
- Parameters:
config (RunnableConfig | None) – RunnableConfig, configuration for the prompt.
- Returns:
The input schema for the prompt.
- Return type:
Type[BaseModel]
- get_output_jsonschema(config=None)[source]
Get a JSON schema that represents the output of the Runnable.
- Parameters:
config (RunnableConfig | None) – A config to use when generating the schema.
- Returns:
A JSON schema that represents the output of the Runnable.
- Return type:
Example
from langchain_core.runnables import RunnableLambda def add_one(x: int) -> int: return x + 1 runnable = RunnableLambda(add_one) print(runnable.get_output_jsonschema())
Added in version 0.3.0.
- get_output_schema(config=None)[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.
- get_prompts(config=None)[source]
Return a list of prompts used by this Runnable.
- Parameters:
config (Optional[RunnableConfig])
- Return type:
list[BasePromptTemplate]
- property input_schema: type[BaseModel]
The type of input this Runnable accepts specified as a pydantic model.
- classmethod is_lc_serializable()[source]
Return whether this class is serializable.
Returns True.
- Return type:
- json(*, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=PydanticUndefined, models_as_dict=PydanticUndefined, **dumps_kwargs)[source]
- Parameters:
include (set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None)
exclude (set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None)
by_alias (bool)
exclude_unset (bool)
exclude_defaults (bool)
exclude_none (bool)
models_as_dict (bool)
dumps_kwargs (Any)
- Return type:
- property lc_attributes: dict
List of attribute names that should be included in the serialized kwargs.
These attributes must be accepted by the constructor. Default is an empty dictionary.
- classmethod lc_id()[source]
A unique identifier for this class for serialization purposes.
The unique identifier is a list of strings that describes the path to the object. For example, for the class langchain.llms.openai.OpenAI, the id is [“langchain”, “llms”, “openai”, “OpenAI”].
- property lc_secrets: dict[str, str]
A map of constructor argument names to secret ids.
- For example,
{“openai_api_key”: “OPENAI_API_KEY”}
- map()[source]
Return a new Runnable that maps a list of inputs to a list of outputs.
Calls invoke() with each input.
- Returns:
A new Runnable that maps a list of inputs to a list of outputs.
- Return type:
Example
from langchain_core.runnables import RunnableLambda def _lambda(x: int) -> int: return x + 1 runnable = RunnableLambda(_lambda) print(runnable.map().invoke([1, 2, 3])) # [2, 3, 4]
- model_computed_fields = {}
- classmethod model_construct(_fields_set=None, **values)[source]
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Parameters:
_fields_set (set[str] | None) – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values (Any) – Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- Return type:
- model_copy(*, update=None, deep=False)[source]
- !!! abstract “Usage Documentation”
[model_copy](../concepts/serialization.md#model_copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)[source]
- !!! abstract “Usage Documentation”
[model_dump](../concepts/serialization.md#modelmodel_dump)
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Parameters:
mode (Literal['json', 'python'] | str) – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include (set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None) – A set of fields to include in the output.
exclude (set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None) – A set of fields to exclude from the output.
context (Any | None) – Additional context to pass to the serializer.
by_alias (bool | None) – Whether to use the field’s alias in the dictionary key if defined.
exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.
exclude_defaults (bool) – Whether to exclude fields that are set to their default value.
exclude_none (bool) – Whether to exclude fields that have a value of None.
round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings (bool | Literal['none', 'warn', 'error']) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback (Callable[[Any], Any] | None) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.
- Returns:
A dictionary representation of the model.
- Return type:
- model_dump_json(*, indent=None, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)[source]
- !!! abstract “Usage Documentation”
[model_dump_json](../concepts/serialization.md#modelmodel_dump_json)
Generates a JSON representation of the model using Pydantic’s to_json method.
- Parameters:
indent (int | None) – Indentation to use in the JSON output. If None is passed, the output will be compact.
include (set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None) – Field(s) to include in the JSON output.
exclude (set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None) – Field(s) to exclude from the JSON output.
context (Any | None) – Additional context to pass to the serializer.
by_alias (bool | None) – Whether to serialize using field aliases.
exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.
exclude_defaults (bool) – Whether to exclude fields that are set to their default value.
exclude_none (bool) – Whether to exclude fields that have a value of None.
round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].
warnings (bool | Literal['none', 'warn', 'error']) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
fallback (Callable[[Any], Any] | None) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.
- Returns:
A JSON string representation of the model.
- Return type:
- property model_extra: dict[str, Any] | None
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- model_fields = {'cache_ttl_seconds': FieldInfo(annotation=int, required=False, default=600, description='Cache TTL for prompts'), 'input_types': FieldInfo(annotation=Dict[str, Any], required=False, default_factory=dict, exclude=True), 'input_variables': FieldInfo(annotation=list[str], required=True), 'load_at_runtime': FieldInfo(annotation=bool, required=False, default=False, description='Whether to load prompt at runtime'), 'messages': FieldInfo(annotation=list[Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate]], required=True, metadata=[SkipValidation()]), 'metadata': FieldInfo(annotation=Union[Dict[str, Any], NoneType], required=False, default=None), 'name': FieldInfo(annotation=Union[str, NoneType], required=False, default=None), 'observability_backend': FieldInfo(annotation=Union[ObservabilityBackend, NoneType], required=False, default=None, description='Observability backend to use'), 'optional_variables': FieldInfo(annotation=list[str], required=False, default=[]), 'output_parser': FieldInfo(annotation=Union[BaseOutputParser, NoneType], required=False, default=None), 'partial_variables': FieldInfo(annotation=Mapping[str, Any], required=False, default_factory=dict), 'prompt_label': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Label of the prompt'), 'prompt_name': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Name of the prompt to load'), 'prompt_version': FieldInfo(annotation=Union[int, NoneType], required=False, default=None, description='Version of the prompt'), 'tags': FieldInfo(annotation=Union[list[str], NoneType], required=False, default=None), 'template_format': FieldInfo(annotation=str, required=False, default='f-string', description='Format of the template'), 'validate_template': FieldInfo(annotation=bool, required=False, default=False)}
- property model_fields_set: set[str]
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- classmethod model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation')[source]
Generates a JSON schema for a model class.
- Parameters:
by_alias (bool) – Whether to use attribute aliases or not.
ref_template (str) – The reference template.
schema_generator (type[GenerateJsonSchema]) – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications
mode (Literal['validation', 'serialization']) – The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- Return type:
- classmethod model_parametrized_name(params)[source]
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Parameters:
params (tuple[type[Any], ...]) – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError – Raised when trying to generate concrete names for non-generic models.
- Return type:
- model_post_init(context, /)[source]
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self (BaseModel) – The BaseModel instance.
context (Any) – The context.
- Return type:
None
- classmethod model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None)[source]
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Parameters:
force (bool) – Whether to force the rebuilding of the model schema, defaults to False.
raise_errors (bool) – Whether to raise errors, defaults to True.
_parent_namespace_depth (int) – The depth level of the parent namespace, defaults to 2.
_types_namespace (MappingNamespace | None) – The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- Return type:
bool | None
- classmethod model_validate(obj, *, strict=None, from_attributes=None, context=None, by_alias=None, by_name=None)[source]
Validate a pydantic model instance.
- Parameters:
obj (Any) – The object to validate.
strict (bool | None) – Whether to enforce types strictly.
from_attributes (bool | None) – Whether to extract data from object attributes.
context (Any | None) – Additional context to pass to the validator.
by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.
by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.
- Raises:
ValidationError – If the object could not be validated.
- Returns:
The validated model instance.
- Return type:
- classmethod model_validate_json(json_data, *, strict=None, context=None, by_alias=None, by_name=None)[source]
- !!! abstract “Usage Documentation”
[JSON Parsing](../concepts/json.md#json-parsing)
Validate the given JSON data against the Pydantic model.
- Parameters:
json_data (str | bytes | bytearray) – The JSON data to validate.
strict (bool | None) – Whether to enforce types strictly.
context (Any | None) – Extra variables to pass to the validator.
by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.
by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError – If json_data is not a JSON string or the object could not be validated.
- Return type:
- classmethod model_validate_strings(obj, *, strict=None, context=None, by_alias=None, by_name=None)[source]
Validate the given object with string data against the Pydantic model.
- Parameters:
obj (Any) – The object containing string data to validate.
strict (bool | None) – Whether to enforce types strictly.
context (Any | None) – Extra variables to pass to the validator.
by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.
by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Return type:
- property output_schema: type[BaseModel]
The type of output this Runnable produces specified as a pydantic model.
- classmethod parse_file(path, *, content_type=None, encoding='utf8', proto=None, allow_pickle=False)[source]
- classmethod parse_raw(b, *, content_type=None, encoding='utf8', proto=None, allow_pickle=False)[source]
- partial(**kwargs)[source]
Get a new ChatPromptTemplate with some input variables already filled in.
- Parameters:
**kwargs (Any) – keyword arguments to use for filling in template variables. Ought to be a subset of the input variables.
- Returns:
A new ChatPromptTemplate.
- Return type:
ChatPromptTemplate
Example
from langchain_core.prompts import ChatPromptTemplate template = ChatPromptTemplate.from_messages( [ ("system", "You are an AI assistant named {name}."), ("human", "Hi I'm {user}"), ("ai", "Hi there, {user}, I'm {name}."), ("human", "{input}"), ] ) template2 = template.partial(user="Lucy", name="R2D2") template2.format_messages(input="hello")
- pick(keys)[source]
Pick keys from the output dict of this Runnable.
- Pick single key:
import json from langchain_core.runnables import RunnableLambda, RunnableMap as_str = RunnableLambda(str) as_json = RunnableLambda(json.loads) chain = RunnableMap(str=as_str, json=as_json) chain.invoke("[1, 2, 3]") # -> {"str": "[1, 2, 3]", "json": [1, 2, 3]} json_only_chain = chain.pick("json") json_only_chain.invoke("[1, 2, 3]") # -> [1, 2, 3]
- Pick list of keys:
from typing import Any import json from langchain_core.runnables import RunnableLambda, RunnableMap as_str = RunnableLambda(str) as_json = RunnableLambda(json.loads) def as_bytes(x: Any) -> bytes: return bytes(x, "utf-8") chain = RunnableMap( str=as_str, json=as_json, bytes=RunnableLambda(as_bytes) ) chain.invoke("[1, 2, 3]") # -> {"str": "[1, 2, 3]", "json": [1, 2, 3], "bytes": b"[1, 2, 3]"} json_and_bytes_chain = chain.pick(["json", "bytes"]) json_and_bytes_chain.invoke("[1, 2, 3]") # -> {"json": [1, 2, 3], "bytes": b"[1, 2, 3]"}
- pipe(*others, name=None)[source]
Compose this Runnable with Runnable-like objects to make a RunnableSequence.
Equivalent to RunnableSequence(self, *others) or self | others[0] | …
Example
from langchain_core.runnables import RunnableLambda def add_one(x: int) -> int: return x + 1 def mul_two(x: int) -> int: return x * 2 runnable_1 = RunnableLambda(add_one) runnable_2 = RunnableLambda(mul_two) sequence = runnable_1.pipe(runnable_2) # Or equivalently: # sequence = runnable_1 | runnable_2 # sequence = RunnableSequence(first=runnable_1, last=runnable_2) sequence.invoke(1) await sequence.ainvoke(1) # -> 4 sequence.batch([1, 2, 3]) await sequence.abatch([1, 2, 3]) # -> [4, 6, 8]
- classmethod schema_json(*, by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, **dumps_kwargs)[source]
- stream(input, config=None, **kwargs)[source]
Default implementation of stream, which calls invoke.
Subclasses should override this method if they support streaming output.
- to_json()[source]
Serialize the Runnable to JSON.
- Returns:
A JSON-serializable representation of the Runnable.
- Return type:
SerializedConstructor | SerializedNotImplemented
- to_json_not_implemented()[source]
Serialize a “not implemented” object.
- Return type:
SerializedNotImplemented
- transform(input, config=None, **kwargs)[source]
Default implementation of transform, which buffers input and calls astream.
Subclasses should override this method if they can start producing output while input is still being generated.
- Parameters:
- Yields:
The output of the Runnable.
- Return type:
Iterator[Output]
- classmethod validate_input_variables(values)[source]
Validate input variables.
If input_variables is not set, it will be set to the union of all input variables in the messages.
- Parameters:
values (dict) – values to validate.
- Returns:
Validated values.
- Raises:
ValueError – If input variables do not match.
- Return type:
- validate_variable_names()[source]
Validate variable names do not include restricted names.
- Return type:
- with_alisteners(*, on_start=None, on_end=None, on_error=None)[source]
Bind async 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.
- Parameters:
on_start (Optional[AsyncListener]) – Asynchronously called before the Runnable starts running. Defaults to None.
on_end (Optional[AsyncListener]) – Asynchronously called after the Runnable finishes running. Defaults to None.
on_error (Optional[AsyncListener]) – Asynchronously called if the Runnable throws an error. Defaults to None.
- Returns:
A new Runnable with the listeners bound.
- Return type:
Runnable[Input, Output]
Example:
from langchain_core.runnables import RunnableLambda, Runnable from datetime import datetime, timezone import time import asyncio def format_t(timestamp: float) -> str: return datetime.fromtimestamp(timestamp, tz=timezone.utc).isoformat() async def test_runnable(time_to_sleep : int): print(f"Runnable[{time_to_sleep}s]: starts at {format_t(time.time())}") await asyncio.sleep(time_to_sleep) print(f"Runnable[{time_to_sleep}s]: ends at {format_t(time.time())}") async def fn_start(run_obj : Runnable): print(f"on start callback starts at {format_t(time.time())}") await asyncio.sleep(3) print(f"on start callback ends at {format_t(time.time())}") async def fn_end(run_obj : Runnable): print(f"on end callback starts at {format_t(time.time())}") await asyncio.sleep(2) print(f"on end callback ends at {format_t(time.time())}") runnable = RunnableLambda(test_runnable).with_alisteners( on_start=fn_start, on_end=fn_end ) async def concurrent_runs(): await asyncio.gather(runnable.ainvoke(2), runnable.ainvoke(3)) asyncio.run(concurrent_runs()) Result: on start callback starts at 2025-03-01T07:05:22.875378+00:00 on start callback starts at 2025-03-01T07:05:22.875495+00:00 on start callback ends at 2025-03-01T07:05:25.878862+00:00 on start callback ends at 2025-03-01T07:05:25.878947+00:00 Runnable[2s]: starts at 2025-03-01T07:05:25.879392+00:00 Runnable[3s]: starts at 2025-03-01T07:05:25.879804+00:00 Runnable[2s]: ends at 2025-03-01T07:05:27.881998+00:00 on end callback starts at 2025-03-01T07:05:27.882360+00:00 Runnable[3s]: ends at 2025-03-01T07:05:28.881737+00:00 on end callback starts at 2025-03-01T07:05:28.882428+00:00 on end callback ends at 2025-03-01T07:05:29.883893+00:00 on end callback ends at 2025-03-01T07:05:30.884831+00:00
- with_config(config=None, **kwargs)[source]
Bind config to a Runnable, returning a new Runnable.
- Parameters:
config (RunnableConfig | None) – The config to bind to the Runnable.
kwargs (Any) – Additional keyword arguments to pass to the Runnable.
- Returns:
A new Runnable with the config bound.
- Return type:
Runnable[Input, Output]
- with_fallbacks(fallbacks, *, exceptions_to_handle=(Exception,), exception_key=None)[source]
Add fallbacks to a Runnable, returning a new Runnable.
The new Runnable will try the original Runnable, and then each fallback in order, upon failures.
- 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. Defaults to (Exception,).
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. Defaults to None.
- Returns:
A new Runnable that will try the original Runnable, and then each fallback in order, upon failures.
- Return type:
RunnableWithFallbacksT[Input, Output]
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]
- with_listeners(*, on_start=None, on_end=None, on_error=None)[source]
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.
- Parameters:
on_start (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) – Called before the Runnable starts running. Defaults to None.
on_end (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) – Called after the Runnable finishes running. Defaults to None.
on_error (Optional[Union[Callable[[Run], None], Callable[[Run, RunnableConfig], None]]]) – Called if the Runnable throws an error. Defaults to None.
- Returns:
A new Runnable with the listeners bound.
- Return type:
Runnable[Input, Output]
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)
- with_retry(*, retry_if_exception_type=(Exception,), wait_exponential_jitter=True, exponential_jitter_params=None, stop_after_attempt=3)[source]
Create a new Runnable that retries the original Runnable on exceptions.
- Parameters:
retry_if_exception_type (tuple[type[BaseException], ...]) – A tuple of exception types to retry on. Defaults to (Exception,).
wait_exponential_jitter (bool) – Whether to add jitter to the wait time between retries. Defaults to True.
stop_after_attempt (int) – The maximum number of attempts to make before giving up. Defaults to 3.
exponential_jitter_params (Optional[ExponentialJitterParams]) – Parameters for
tenacity.wait_exponential_jitter
. Namely:initial
,max
,exp_base
, andjitter
(all float values).
- Returns:
A new Runnable that retries the original Runnable on exceptions.
- Return type:
Runnable[Input, Output]
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)
- with_types(*, input_type=None, output_type=None)[source]
Bind input and output types to a Runnable, returning a new Runnable.
- messages: Annotated[list[MessageLike], SkipValidation()]
List of messages consisting of either message prompt templates or messages.
- optional_variables: list[str]
A list of the names of the variables for placeholder or MessagePlaceholder that are optional. These variables are auto inferred from the prompt and user need not provide them.
- Type:
optional_variables
- input_types: Dict[str, Any]
A dictionary of the types of the variables the prompt template expects. If not provided, all variables are assumed to be strings.
- output_parser: BaseOutputParser | None
How to parse the output of calling an LLM on this formatted prompt.
- async ainvoke(input, config=None, **kwargs)[source][source]
Asynchronously invoke the prompt template.
- classmethod from_observability_platform(prompt_name, observability_platform, *, prompt_version=None, prompt_label=None, load_at_runtime=True, **kwargs)[source][source]
Create a chat prompt template from an observability platform.
- Parameters:
- Return type: