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:
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:
prompt_name: str | None
prompt_version: int | None
prompt_label: str | None
load_at_runtime: bool
observability_backend: ObservabilityBackend | None
cache_ttl_seconds: int
template_format: str
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]

Input type.

The type of input this Runnable accepts specified as a type annotation.

Raises:

TypeError – If the input type cannot be inferred.

property OutputType: Any

Return the output type of the prompt.

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 must 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 RunnableConfig for more details.

  • return_exceptions (bool) – Whether to return exceptions instead of raising them.

  • **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 RunnableConfig for more details.

  • return_exceptions (bool) – Whether to return exceptions instead of raising them.

  • **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(**kwargs)[source]

Async format the chat template into a string.

Parameters:

**kwargs (Any) – keyword arguments to use for filling in template variables in all the template messages in this chat template.

Returns:

formatted string.

Return type:

str

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 ChatPromptValue.

Parameters:

**kwargs (Any) – Keyword arguments to use for formatting.

Returns:

PromptValue.

Return type:

ChatPromptValue

append(message)[source]

Append a message to the end of the chat template.

Parameters:

message (BaseMessagePromptTemplate | BaseMessage | BaseChatPromptTemplate | tuple[str | type, str | list[dict] | list[object]] | str | dict[str, Any]) – representation of a message to append.

Return type:

None

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, and args_schema from a Runnable. Where possible, schemas are inferred from runnable.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 with args_schema.

You can also pass arg_types to just specify the required arguments and their types.

Parameters:
  • args_schema (type[BaseModel] | None) – The schema for the tool.

  • name (str | None) – The name of the tool.

  • description (str | None) – The description of the tool.

  • arg_types (dict[str, type] | None) – A dictionary of argument names to types.

Returns:

A BaseTool instance.

Return type:

BaseTool

!!! example “TypedDict input”

```python 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]}) ```

!!! example “dict input, specifying schema via args_schema

```python 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]}) ```

!!! example “dict input, specifying schema via arg_types

```python 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]}) ```

!!! example “str input”

```python 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”) ```

assign(**kwargs)[source]

Assigns new fields to the dict output of this Runnable.

```python from langchain_core.language_models.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}”

) model = FakeStreamingListLLM(responses=[“foo-lish”])

chain: Runnable = prompt | model | {“str”: StrOutputParser()}

chain_with_assign = chain.assign(hello=itemgetter(“str”) | model)

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’}}} ```

Parameters:

**kwargs (Runnable[dict[str, Any], Any] | Callable[[dict[str, Any]], Any] | Mapping[str, Runnable[dict[str, Any], Any] | Callable[[dict[str, Any]], Any]]) – A mapping of keys to Runnable or Runnable-like objects that will be invoked with the entire output dict of this Runnable.

Returns:

A new Runnable.

Return type:

RunnableSerializable[Any, Any]

async astream(input, config=None, **kwargs)[source]

Default implementation of astream, which calls ainvoke.

Subclasses must 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.

  • **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 StreamEvent that provide real-time information about the progress of the Runnable, including StreamEvent from intermediate results.

A StreamEvent is a dictionary with the following schema:

  • event: Event names are of the format:

    on_[runnable_type]_(start|stream|end).

  • name: The name of the Runnable that generated the event.

  • run_id: Randomly generated ID associated with the given execution of the

    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: The IDs of the parent runnables that generated 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: The tags of the Runnable that generated the event.

  • metadata: The metadata of the Runnable that generated the event.

  • data: The data associated with the event. The contents of this field

    depend on the type of event. See the table below for more details.

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.

!!! note

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:

```python 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:

```python @tool def some_tool(x: int, y: str) -> dict:

‘’’Some_tool.’’’ return {“x”: x, “y”: y}

```

prompt:

```python template = ChatPromptTemplate.from_messages(

[

(“system”, “You are Cat Agent 007”), (“human”, “{question}”),

]

).with_config({“run_name”: “my_template”, “tags”: [“my_template”]}) ```

!!! example

```python 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”: [],

},

```python title=”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 (RunnableConfig | None) – 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 (Sequence[str] | None) – Only include events from Runnable objects with matching names.

  • include_types (Sequence[str] | None) – Only include events from Runnable objects with matching types.

  • include_tags (Sequence[str] | None) – Only include events from Runnable objects with matching tags.

  • exclude_names (Sequence[str] | None) – Exclude events from Runnable objects with matching names.

  • exclude_types (Sequence[str] | None) – Exclude events from Runnable objects with matching types.

  • exclude_tags (Sequence[str] | None) – Exclude events from Runnable objects 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 StreamEvent.

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 (RunnableConfig | None) – 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 (Sequence[str] | None) – Only include logs with these names.

  • include_types (Sequence[str] | None) – Only include logs with these types.

  • include_tags (Sequence[str] | None) – Only include logs with these tags.

  • exclude_names (Sequence[str] | None) – Exclude logs with these names.

  • exclude_types (Sequence[str] | None) – Exclude logs with these types.

  • exclude_tags (Sequence[str] | None) – Exclude logs with these tags.

  • **kwargs (Any) – Additional keyword arguments to pass to the Runnable.

Yields:

A RunLogPatch or RunLog object.

Return type:

AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]

async atransform(input, config=None, **kwargs)[source]

Transform inputs to outputs.

Default implementation of atransform, which buffers input and calls astream.

Subclasses must 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.

  • **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 must 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 RunnableConfig for more details.

  • return_exceptions (bool) – Whether to return exceptions instead of raising them.

  • **kwargs (Any | None) – Additional keyword arguments to pass to the Runnable.

Returns:

A list of outputs from the Runnable.

Return type:

list[Output]

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.

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 RunnableConfig for more details.

  • return_exceptions (bool) – Whether to return exceptions instead of raising them.

  • **kwargs (Any | None) – Additional keyword arguments to pass to the Runnable.

Yields:

Tuples of the index of the input and the output from the Runnable.

Return type:

Iterator[tuple[int, Output | Exception]]

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

```python from langchain_ollama import ChatOllama from langchain_core.output_parsers import StrOutputParser

model = ChatOllama(model=”llama3.1”)

# Without bind chain = model | StrOutputParser()

chain.invoke(“Repeat quoted words exactly: ‘One two three four five.’”) # Output is ‘One two three four five.’

# With bind chain = model.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.

Parameters:

include (Sequence[str] | None) – A list of fields to include in the config schema.

Returns:

A Pydantic model that can be used to validate config.

Return type:

type[BaseModel]

property config_specs: list[ConfigurableFieldSpec]

List configurable fields for this Runnable.

configurable_alternatives(which, *, default_key='default', prefix_keys=False, **kwargs)[source]

Configure alternatives for Runnable objects 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.

  • prefix_keys (bool) – Whether to prefix the keys with the ConfigurableField id.

  • **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

!!! example

```python from langchain_anthropic import ChatAnthropic from langchain_core.runnables.utils import ConfigurableField from langchain_openai import ChatOpenAI

model = ChatAnthropic(

model_name=”claude-sonnet-4-5-20250929”

).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.

Raises:

ValueError – If a configuration key is not found in the Runnable.

Returns:

A new Runnable with the fields configured.

Return type:

RunnableSerializable

!!! example

```python 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,

classmethod construct(_fields_set=None, **values)[source]
Parameters:
Return type:

Self

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

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(**kwargs)[source]

Format the chat template into a string.

Parameters:

**kwargs (Any) – keyword arguments to use for filling in template variables in all the template messages in this chat template.

Returns:

formatted string.

Return type:

str

format_messages(**kwargs)[source]

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.

Raises:

ValueError – if messages are of unexpected types.

Returns:

list of formatted messages.

Return type:

list[BaseMessage]

format_prompt(**kwargs)[source]

Format prompt. Should return a ChatPromptValue.

Parameters:

**kwargs (Any) – Keyword arguments to use for formatting.

Returns:

ChatPromptValue.

Return type:

ChatPromptValue

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:

```python 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:

```python template = ChatPromptTemplate.from_messages(

[

SystemMessage(content=”hello”), (“human”, “Hello, how are you?”),

]

)

param messages:

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}”

param template_format:

format of the template.

returns:

a chat prompt template.

Parameters:
  • messages (Sequence[MessageLikeRepresentation])

  • template_format (PromptTemplateFormat)

Return type:

ChatPromptTemplate

classmethod from_orm(obj)[source]
Parameters:

obj (Any)

Return type:

Self

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.

Parameters:
  • template (str) – template string

  • **kwargs (Any) – keyword arguments to pass to the constructor.

Returns:

A new instance of this class.

Return type:

ChatPromptTemplate

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:

dict[str, Any]

!!! version-added “Added in langchain-core 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:

dict[str, Any]

Example

```python from langchain_core.runnables import RunnableLambda

def add_one(x: int) -> int:

return x + 1

runnable = RunnableLambda(add_one)

print(runnable.get_input_jsonschema()) ```

!!! version-added “Added in langchain-core 0.3.0”

get_input_schema(config=None)[source]

Get the input schema for the prompt.

Parameters:

config (RunnableConfig | None) – Configuration for the prompt.

Returns:

The input schema for the prompt.

Return type:

type[BaseModel]

classmethod get_lc_namespace()[source]

Get the namespace of the LangChain object.

Returns:

[“langchain”, “prompts”, “chat”]

Return type:

list[str]

get_name(suffix=None, *, name=None)[source]

Get the name of the Runnable.

Parameters:
  • suffix (str | None) – An optional suffix to append to the name.

  • name (str | None) – An optional name to use instead of the Runnable’s name.

Returns:

The name of the Runnable.

Return type:

str

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:

dict[str, Any]

Example

```python from langchain_core.runnables import RunnableLambda

def add_one(x: int) -> int:

return x + 1

runnable = RunnableLambda(add_one)

print(runnable.get_output_jsonschema()) ```

!!! version-added “Added in langchain-core 0.3.0”

get_output_schema(config=None)[source]

Get a Pydantic model that can be used to validate output to the Runnable.

Runnable objects 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 (RunnableConfig | None) – 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=None)[source]

Return a list of prompts used by this Runnable.

Parameters:

config (RunnableConfig | None)

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 True as this class is serializable.

Return type:

bool

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:
Return type:

str

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]

Return 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”].

Return type:

list[str]

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:

Runnable[list[Input], list[Output]]

Example

```python 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:

Self

model_copy(*, update=None, deep=False)[source]
!!! abstract “Usage Documentation”

[model_copy](../concepts/models.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]).

Parameters:
  • update (Mapping[str, Any] | None) – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

  • deep (bool) – Set to True to make a deep copy of the model.

Returns:

New model instance.

Return type:

Self

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)[source]
!!! abstract “Usage Documentation”

[model_dump](../concepts/serialization.md#python-mode)

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.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • 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:

dict[str, Any]

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)[source]
!!! abstract “Usage Documentation”

[model_dump_json](../concepts/serialization.md#json-mode)

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.

  • ensure_ascii (bool) – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

  • 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.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • 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:

str

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', *, union_format='any_of')[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.

  • union_format (Literal['any_of', 'primitive_type_array']) –

    The format to use when combining schemas from unions together. Can be one of:

    keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

  • 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:

dict[str, Any]

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:

str

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, extra=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.

  • extra (Literal['allow', 'ignore', 'forbid'] | None) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • 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:

Self

classmethod model_validate_json(json_data, *, strict=None, extra=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.

  • extra (Literal['allow', 'ignore', 'forbid'] | None) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • 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:

Self

classmethod model_validate_strings(obj, *, strict=None, extra=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.

  • extra (Literal['allow', 'ignore', 'forbid'] | None) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • 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:

Self

property output_schema: type[BaseModel]

Output schema.

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]
Parameters:
  • path (str | Path)

  • content_type (str | None)

  • encoding (str)

  • proto (DeprecatedParseProtocol | None)

  • allow_pickle (bool)

Return type:

Self

classmethod parse_obj(obj)[source]
Parameters:

obj (Any)

Return type:

Self

classmethod parse_raw(b, *, content_type=None, encoding='utf8', proto=None, allow_pickle=False)[source]
Parameters:
  • b (str | bytes)

  • content_type (str | None)

  • encoding (str)

  • proto (DeprecatedParseProtocol | None)

  • allow_pickle (bool)

Return type:

Self

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

```python 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.

!!! example “Pick a single key”

```python 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] ```

!!! example “Pick a list of keys”

```python 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]”} ```

Parameters:

keys (str | list[str]) – A key or list of keys to pick from the output dict.

Returns:

a new Runnable.

Return type:

RunnableSerializable[Any, Any]

pipe(*others, name=None)[source]

Pipe Runnable objects.

Compose this Runnable with Runnable-like objects to make a RunnableSequence.

Equivalent to RunnableSequence(self, *others) or self | others[0] | …

Example

```python 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] ```

Parameters:
  • *others (Runnable[Any, Other] | Callable[[Any], Other]) – Other Runnable or Runnable-like objects to compose

  • name (str | None) – An optional name for the resulting RunnableSequence.

Returns:

A new Runnable.

Return type:

RunnableSerializable[-Input, ~Other]

pretty_print()[source]

Print a human-readable representation.

Return type:

None

pretty_repr(html=False)[source]

Human-readable representation.

Parameters:

html (bool) – Whether to format as HTML.

Returns:

Human-readable representation.

Return type:

str

save(file_path)[source]

Save prompt to file.

Parameters:

file_path (Path | str) – path to file.

Return type:

None

classmethod schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE)[source]
Parameters:
  • by_alias (bool)

  • ref_template (str)

Return type:

Dict[str, Any]

classmethod schema_json(*, by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, **dumps_kwargs)[source]
Parameters:
  • by_alias (bool)

  • ref_template (str)

  • dumps_kwargs (Any)

Return type:

str

stream(input, config=None, **kwargs)[source]

Default implementation of stream, which calls invoke.

Subclasses must 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.

  • **kwargs (Any | None) – Additional keyword arguments to pass to the Runnable.

Yields:

The output of the Runnable.

Return type:

Iterator[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.

Returns:

SerializedNotImplemented.

Return type:

SerializedNotImplemented

transform(input, config=None, **kwargs)[source]

Transform inputs to outputs.

Default implementation of transform, which buffers input and calls astream.

Subclasses must override this method if they can start producing output while input is still being generated.

Parameters:
  • input (Iterator[Input]) – An iterator of inputs to the Runnable.

  • config (RunnableConfig | None) – The config to use for the Runnable.

  • **kwargs (Any | None) – Additional keyword arguments to pass to the Runnable.

Yields:

The output of the Runnable.

Return type:

Iterator[Output]

classmethod update_forward_refs(**localns)[source]
Parameters:

localns (Any)

Return type:

None

classmethod validate(value)[source]
Parameters:

value (Any)

Return type:

Self

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:

Any

validate_variable_names()[source]

Validate variable names do not include restricted names.

Return type:

Self

with_alisteners(*, on_start=None, on_end=None, on_error=None)[source]

Bind async lifecycle listeners to a Runnable.

Returns a new Runnable.

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 (AsyncListener | None) – Called asynchronously before the Runnable starts running, with the Run object.

  • on_end (AsyncListener | None) – Called asynchronously after the Runnable finishes running, with the Run object.

  • on_error (AsyncListener | None) – Called asynchronously if the Runnable throws an error, with the Run object.

Returns:

A new Runnable with the listeners bound.

Return type:

Runnable[Input, Output]

Example

```python 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.

  • exception_key (str | None) –

    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]

Example

```python 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 (str | None) –

    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.

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 (Callable[[Run], None] | Callable[[Run, RunnableConfig], None] | None) – Called before the Runnable starts running, with the Run object.

  • on_end (Callable[[Run], None] | Callable[[Run, RunnableConfig], None] | None) – Called after the Runnable finishes running, with the Run object.

  • on_error (Callable[[Run], None] | Callable[[Run, RunnableConfig], None] | None) – Called if the Runnable throws an error, with the Run object.

Returns:

A new Runnable with the listeners bound.

Return type:

Runnable[Input, Output]

Example

```python 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.

  • 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.

  • exponential_jitter_params (ExponentialJitterParams | None) – Parameters for tenacity.wait_exponential_jitter. Namely: initial, max, exp_base, and jitter (all float values).

Returns:

A new Runnable that retries the original Runnable on exceptions.

Return type:

Runnable[Input, Output]

Example

```python 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.

Parameters:
  • input_type (type[Input] | None) – The input type to bind to the Runnable.

  • output_type (type[Output] | None) – The output type to bind to the Runnable.

Returns:

A new Runnable with the types bound.

Return type:

Runnable[Input, Output]

messages: Annotated[list[MessageLike], SkipValidation()]

List of messages consisting of either message prompt templates or messages.

validate_template: bool

Whether or not to try validating the template.

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.

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.

metadata: Dict[str, Any] | None

Metadata to be used for tracing.

tags: list[str] | None

Tags to be used for tracing.

name: str | None

The name of the Runnable. Used for debugging and tracing.

invoke(input, config=None, **kwargs)[source][source]

Invoke the prompt template.

Parameters:
Return type:

PromptValue

async ainvoke(input, config=None, **kwargs)[source][source]

Asynchronously invoke the prompt template.

Parameters:
Return type:

PromptValue

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:

ObservabilityChatPromptTemplate

classmethod from_observability_backend(prompt_name, observability_backend, *, prompt_version=None, prompt_label=None, load_at_runtime=True, **kwargs)[source][source]

Create a chat prompt template from an observability backend.

Parameters:
Return type:

ObservabilityChatPromptTemplate