跳转到内容

RemoteGraph

langgraph.pregel.remote

RemoteGraph

基类: PregelProtocol

RemoteGraph 类是用于调用实现了 LangGraph 服务器 API 规范的远程 API 的客户端实现。

例如,RemoteGraph 类可用于调用 LangSmith Deployment 上部署的 API。

RemoteGraph 的行为方式与 Graph 相同,可以直接用作另一个 Graph 中的节点。

方法 描述
__init__

指定 urlapi_key 和/或 headers 来创建默认的同步和异步客户端。

with_config

将配置绑定到 Runnable,返回一个新的 Runnable

get_graph

按图名称获取图。

aget_graph

按图名称获取图。

get_state

获取线程的状态。

aget_state

获取线程的状态。

get_state_history

获取线程的状态历史记录。

aget_state_history

获取线程的状态历史记录。

update_state

更新线程的状态。

aupdate_state

更新线程的状态。

stream

创建一个运行并以流式传输结果。

astream

创建一个运行并以流式传输结果。

astream_events

生成事件流。

invoke

创建一个运行,等待其完成并返回最终状态。

ainvoke

创建一个运行,等待其完成并返回最终状态。

get_name

获取 Runnable 的名称。

get_input_schema

获取可用于验证 Runnable 输入的 Pydantic 模型。

get_input_jsonschema

获取表示 Runnable 输入的 JSON 模式。

get_output_schema

获取可用于验证 Runnable 输出的 Pydantic 模型。

get_output_jsonschema

获取表示 Runnable 输出的 JSON 模式。

config_schema

Runnable 接受的配置类型,指定为 Pydantic 模型。

get_config_jsonschema

获取表示 Runnable 配置的 JSON 模式。

get_prompts

返回此 Runnable 使用的提示列表。

__or__

Runnable "or" 运算符。

__ror__

Runnable "reverse-or" 运算符。

pipe

管道连接 Runnable 对象。

pick

从此 Runnable 的输出 dict 中选择键。

assign

向此 Runnabledict 输出分配新字段。

batch

默认实现使用线程池执行器并行运行 invoke。

batch_as_completed

在输入列表上并行运行 invoke

abatch

默认实现使用 asyncio.gather 并行运行 ainvoke

abatch_as_completed

在输入列表上并行运行 ainvoke

astream_log

流式传输 Runnable 的所有输出,如回调系统所报告。

transform

将输入转换为输出。

atransform

将输入转换为输出。

bind

将参数绑定到 Runnable,返回一个新的 Runnable

with_listeners

将生命周期侦听器绑定到 Runnable,返回一个新的 Runnable

with_alisteners

将异步生命周期侦听器绑定到 Runnable

with_types

将输入和输出类型绑定到 Runnable,返回一个新的 Runnable

with_retry

创建一个新的 Runnable,它在发生异常时重试原始的 Runnable

map

返回一个新的 Runnable,它将输入列表映射到输出列表。

with_fallbacks

Runnable 添加回退机制,返回一个新的 Runnable

as_tool

Runnable 创建一个 BaseTool

name instance-attribute

name: str | None

Runnable 的名称。用于调试和追踪。

InputType property

InputType: type[Input]

输入类型。

Runnable 接受的输入类型,以类型注解形式指定。

引发 描述
TypeError

如果输入类型无法推断。

OutputType property

OutputType: type[Output]

输出类型。

Runnable 产生的输出类型,指定为类型注解。

引发 描述
TypeError

如果无法推断输出类型。

input_schema property

input_schema: type[BaseModel]

Runnable 接受的输入类型,指定为 Pydantic 模型。

output_schema property

output_schema: type[BaseModel]

输出模式。

Runnable 产生的输出类型,指定为 Pydantic 模型。

config_specs property

config_specs: list[ConfigurableFieldSpec]

列出此 Runnable 的可配置字段。

__init__

__init__(
    assistant_id: str,
    /,
    *,
    url: str | None = None,
    api_key: str | None = None,
    headers: dict[str, str] | None = None,
    client: LangGraphClient | None = None,
    sync_client: SyncLangGraphClient | None = None,
    config: RunnableConfig | None = None,
    name: str | None = None,
    distributed_tracing: bool = False,
)

指定 urlapi_key 和/或 headers 来创建默认的同步和异步客户端。

如果提供了 clientsync_client,则将使用它们而不是默认客户端。有关默认客户端的详细信息,请参阅 LangGraphClientSyncLangGraphClient。必须提供 urlclientsync_client 中的至少一个。

参数 描述
assistant_id

要使用的远程图的助手 ID 或图名称。

类型: str

url

远程 API 的 URL。

类型: str | None 默认值: None

api_key

用于身份验证的 API 密钥。如果未提供,将从环境中读取(LANGGRAPH_API_KEYLANGSMITH_API_KEYLANGCHAIN_API_KEY)。

类型: str | None 默认值: None

headers

要在请求中包含的附加标头。

类型: dict[str, str] | None 默认值: None

client

一个要使用的 LangGraphClient 实例,而不是创建默认客户端。

类型: LangGraphClient | None 默认值: None

sync_client

一个要使用的 SyncLangGraphClient 实例,而不是创建默认客户端。

类型: SyncLangGraphClient | None 默认值: None

配置

一个可选的 RunnableConfig 实例,包含附加配置。

类型: RunnableConfig | None 默认值: None

name

附加到 RemoteGraph 实例的人类可读名称。这对于通过 graph.add_node(remote_graph) 添加 RemoteGraph 作为子图非常有用。如果未提供,则默认为助手 ID。

类型: str | None 默认值: None

distributed_tracing

是否启用发送 LangSmith 分布式跟踪标头。

类型: bool 默认值: False

with_config

with_config(config: RunnableConfig | None = None, **kwargs: Any) -> Self

将配置绑定到 Runnable,返回一个新的 Runnable

参数 描述
配置

要绑定到 Runnable 的配置。

类型: RunnableConfig | None 默认值: None

**kwargs

要传递给 Runnable 的其他关键字参数。

类型: Any 默认值: {}

返回 描述
Runnable[Input, Output]

一个绑定了配置的新 Runnable

get_graph

get_graph(
    config: RunnableConfig | None = None,
    *,
    xray: int | bool = False,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
) -> Graph

按图名称获取图。

此方法调用 GET /assistants/{assistant_id}/graph

参数 描述
配置

此参数未使用。

类型: RunnableConfig | None 默认值: None

xray

包含子图的图表示。如果提供一个整数值,则只包含深度小于或等于该值的子图。

类型: int | bool 默认值: False

返回 描述
Graph

助手的图信息,格式为 JSON。

aget_graph async

aget_graph(
    config: RunnableConfig | None = None,
    *,
    xray: int | bool = False,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
) -> Graph

按图名称获取图。

此方法调用 GET /assistants/{assistant_id}/graph

参数 描述
配置

此参数未使用。

类型: RunnableConfig | None 默认值: None

xray

包含子图的图表示。如果提供一个整数值,则只包含深度小于或等于该值的子图。

类型: int | bool 默认值: False

返回 描述
Graph

助手的图信息,格式为 JSON。

get_state

get_state(
    config: RunnableConfig,
    *,
    subgraphs: bool = False,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
) -> StateSnapshot

获取线程的状态。

如果在配置中指定了检查点,此方法调用 POST /threads/{thread_id}/state/checkpoint;如果未指定检查点,则调用 GET /threads/{thread_id}/state

参数 描述
配置

一个 RunnableConfig,其 configurable 字段中包含 thread_id

类型: RunnableConfig

subgraphs

在状态中包含子图。

类型: bool 默认值: False

headers

可选的自定义标头,用于随请求一起发送。

类型: dict[str, str] | None 默认值: None

params

可选的查询参数,用于随请求一起发送。

类型: QueryParamTypes | None 默认值: None

返回 描述
StateSnapshot

线程的最新状态。

aget_state async

aget_state(
    config: RunnableConfig,
    *,
    subgraphs: bool = False,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
) -> StateSnapshot

获取线程的状态。

如果在配置中指定了检查点,此方法调用 POST /threads/{thread_id}/state/checkpoint;如果未指定检查点,则调用 GET /threads/{thread_id}/state

参数 描述
配置

一个 RunnableConfig,其 configurable 字段中包含 thread_id

类型: RunnableConfig

subgraphs

在状态中包含子图。

类型: bool 默认值: False

headers

可选的自定义标头,用于随请求一起发送。

类型: dict[str, str] | None 默认值: None

params

可选的查询参数,用于随请求一起发送。

类型: QueryParamTypes | None 默认值: None

返回 描述
StateSnapshot

线程的最新状态。

get_state_history

get_state_history(
    config: RunnableConfig,
    *,
    filter: dict[str, Any] | None = None,
    before: RunnableConfig | None = None,
    limit: int | None = None,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
) -> Iterator[StateSnapshot]

获取线程的状态历史记录。

此方法调用 POST /threads/{thread_id}/history

参数 描述
配置

一个 RunnableConfig,其 configurable 字段中包含 thread_id

类型: RunnableConfig

filter

用于筛选的元数据。

类型: dict[str, Any] | None 默认值: None

before

一个 RunnableConfig,包含检查点元数据。

类型: RunnableConfig | None 默认值: None

limit

返回的最大状态数。

TYPE: int | None DEFAULT: None

返回 描述
Iterator[StateSnapshot]

线程的状态。

aget_state_history async

aget_state_history(
    config: RunnableConfig,
    *,
    filter: dict[str, Any] | None = None,
    before: RunnableConfig | None = None,
    limit: int | None = None,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
) -> AsyncIterator[StateSnapshot]

获取线程的状态历史记录。

此方法调用 POST /threads/{thread_id}/history

参数 描述
配置

一个 RunnableConfig,其 configurable 字段中包含 thread_id

类型: RunnableConfig

filter

用于筛选的元数据。

类型: dict[str, Any] | None 默认值: None

before

一个 RunnableConfig,包含检查点元数据。

类型: RunnableConfig | None 默认值: None

limit

返回的最大状态数。

TYPE: int | None DEFAULT: None

headers

可选的自定义标头,用于随请求一起发送。

类型: dict[str, str] | None 默认值: None

params

可选的查询参数,用于随请求一起发送。

类型: QueryParamTypes | None 默认值: None

返回 描述
AsyncIterator[StateSnapshot]

线程的状态。

update_state

update_state(
    config: RunnableConfig,
    values: dict[str, Any] | Any | None,
    as_node: str | None = None,
    *,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
) -> RunnableConfig

更新线程的状态。

此方法调用 POST /threads/{thread_id}/state

参数 描述
配置

一个 RunnableConfig,其 configurable 字段中包含 thread_id

类型: RunnableConfig

values

要更新到状态的值。

类型: dict[str, Any] | Any | None

as_node

更新状态,就好像此节点刚刚执行过一样。

类型: str | None 默认值: None

返回 描述
RunnableConfig

用于更新线程的 RunnableConfig

aupdate_state async

aupdate_state(
    config: RunnableConfig,
    values: dict[str, Any] | Any | None,
    as_node: str | None = None,
    *,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
) -> RunnableConfig

更新线程的状态。

此方法调用 POST /threads/{thread_id}/state

参数 描述
配置

一个 RunnableConfig,其 configurable 字段中包含 thread_id

类型: RunnableConfig

values

要更新到状态的值。

类型: dict[str, Any] | Any | None

as_node

更新状态,就好像此节点刚刚执行过一样。

类型: str | None 默认值: None

返回 描述
RunnableConfig

用于更新线程的 RunnableConfig

stream

stream(
    input: dict[str, Any] | Any,
    config: RunnableConfig | None = None,
    *,
    stream_mode: StreamMode | list[StreamMode] | None = None,
    interrupt_before: All | Sequence[str] | None = None,
    interrupt_after: All | Sequence[str] | None = None,
    subgraphs: bool = False,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
    **kwargs: Any,
) -> Iterator[dict[str, Any] | Any]

创建一个运行并以流式传输结果。

如果在配置的 configurable 字段中指定了 thread_id,此方法将调用 POST /threads/{thread_id}/runs/stream;否则,将调用 POST /runs/stream

参数 描述
输入

图的输入。

类型: dict[str, Any] | Any

配置

用于图调用的 RunnableConfig

类型: RunnableConfig | None 默认值: None

stream_mode

要使用的流模式。

类型: StreamMode | list[StreamMode] | None 默认值: None

interrupt_before

在这些节点之前中断图。

类型: All | Sequence[str] | None 默认值: None

interrupt_after

在这些节点之后中断图。

类型: All | Sequence[str] | None 默认值: None

subgraphs

从子图流式传输。

类型: bool 默认值: False

headers

传递给请求的附加标头。

类型: dict[str, str] | None 默认值: None

**kwargs

传递给 client.runs.stream 的附加参数。

类型: Any 默认值: {}

YIELDS 描述
dict[str, Any] | Any

图的输出。

astream async

astream(
    input: dict[str, Any] | Any,
    config: RunnableConfig | None = None,
    *,
    stream_mode: StreamMode | list[StreamMode] | None = None,
    interrupt_before: All | Sequence[str] | None = None,
    interrupt_after: All | Sequence[str] | None = None,
    subgraphs: bool = False,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
    **kwargs: Any,
) -> AsyncIterator[dict[str, Any] | Any]

创建一个运行并以流式传输结果。

如果在配置的 configurable 字段中指定了 thread_id,此方法将调用 POST /threads/{thread_id}/runs/stream;否则,将调用 POST /runs/stream

参数 描述
输入

图的输入。

类型: dict[str, Any] | Any

配置

用于图调用的 RunnableConfig

类型: RunnableConfig | None 默认值: None

stream_mode

要使用的流模式。

类型: StreamMode | list[StreamMode] | None 默认值: None

interrupt_before

在这些节点之前中断图。

类型: All | Sequence[str] | None 默认值: None

interrupt_after

在这些节点之后中断图。

类型: All | Sequence[str] | None 默认值: None

subgraphs

从子图流式传输。

类型: bool 默认值: False

headers

传递给请求的附加标头。

类型: dict[str, str] | None 默认值: None

**kwargs

传递给 client.runs.stream 的附加参数。

类型: Any 默认值: {}

YIELDS 描述
AsyncIterator[dict[str, Any] | Any]

图的输出。

astream_events async

astream_events(
    input: Any,
    config: RunnableConfig | None = None,
    *,
    version: Literal["v1", "v2"],
    include_names: Sequence[All] | None = None,
    include_types: Sequence[All] | None = None,
    include_tags: Sequence[All] | None = None,
    exclude_names: Sequence[All] | None = None,
    exclude_types: Sequence[All] | None = None,
    exclude_tags: Sequence[All] | None = None,
    **kwargs: Any,
) -> AsyncIterator[dict[str, Any]]

生成事件流。

用于创建一个 StreamEvent 的迭代器,提供有关 Runnable 进度的实时信息,包括来自中间结果的 StreamEvent

一个 StreamEvent 是一个具有以下模式的字典

  • event:事件名称的格式为:on_[runnable_type]_(start|stream|end)
  • name:生成事件的 Runnable 的名称。
  • run_id:与发出事件的 Runnable 的给定执行相关联的随机生成的 ID。作为父 Runnable 执行的一部分被调用的子 Runnable 被分配其自己的唯一 ID。
  • parent_ids:生成事件的父可运行对象的 ID。根 Runnable 将有一个空列表。父 ID 的顺序是从根到直接父级。仅适用于 API 的 v2 版本。API 的 v1 版本将返回一个空列表。
  • tags:生成事件的 Runnable 的标签。
  • metadata:生成事件的 Runnable 的元数据。
  • data:与事件关联的数据。此字段的内容取决于事件的类型。有关更多详细信息,请参见下表。

下表说明了各种链可能发出的某些事件。为简洁起见,已从表中省略了元数据字段。链定义已包含在表之后。

注意

此参考表适用于模式的 v2 版本。

事件 name chunk 输入 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]' '你好'
on_llm_end '[model name]' '你好,人类!'
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, ...])

除了标准事件外,用户还可以分派自定义事件(见下例)。

自定义事件将仅在 API 的 v2 版本中出现!

自定义事件具有以下格式

属性 类型 描述
name str 用户为事件定义的名称。
data 任意 与事件关联的数据。这可以是任何东西,但我们建议使其可 JSON 序列化。

以下是与上面显示的标准事件相关的声明

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"]})

例如

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": [],
    },
]
示例:分派自定义事件
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)
参数 描述
输入

Runnable 的输入。

类型: Any

配置

用于 Runnable 的配置。

类型: RunnableConfig | None 默认值: None

版本

要使用的模式版本,可以是 'v2''v1'。用户应使用 'v2''v1' 是为了向后兼容,并将在 0.4.0 中弃用。在 API 稳定之前不会分配默认值。自定义事件将仅在 'v2' 中出现。

类型: Literal['v1', 'v2'] 默认值: 'v2'

包含名称

仅包括来自具有匹配名称的 Runnable 对象的事件。

类型: Sequence[str] | None 默认值: None

包含类型

仅包括来自具有匹配类型的 Runnable 对象的事件。

类型: Sequence[str] | None 默认值: None

包含标签

仅包括来自具有匹配标签的 Runnable 对象的事件。

类型: Sequence[str] | None 默认值: None

排除名称

排除来自具有匹配名称的 Runnable 对象的事件。

类型: Sequence[str] | None 默认值: None

排除类型

排除来自具有匹配类型的 Runnable 对象的事件。

类型: Sequence[str] | None 默认值: None

排除标签

排除来自具有匹配标签的 Runnable 对象的事件。

类型: Sequence[str] | None 默认值: None

**kwargs

要传递给 Runnable 的其他关键字参数。这些将传递给 astream_log,因为 astream_events 的此实现是建立在 astream_log 之上的。

类型: Any 默认值: {}

YIELDS 描述
AsyncIterator[StreamEvent]

StreamEvent 的异步流。

引发 描述
NotImplementedError

如果版本不是 'v1''v2'

invoke

invoke(
    input: dict[str, Any] | Any,
    config: RunnableConfig | None = None,
    *,
    interrupt_before: All | Sequence[str] | None = None,
    interrupt_after: All | Sequence[str] | None = None,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
    **kwargs: Any,
) -> dict[str, Any] | Any

创建一个运行,等待其完成并返回最终状态。

参数 描述
输入

图的输入。

类型: dict[str, Any] | Any

配置

用于图调用的 RunnableConfig

类型: RunnableConfig | None 默认值: None

interrupt_before

在这些节点之前中断图。

类型: All | Sequence[str] | None 默认值: None

interrupt_after

在这些节点之后中断图。

类型: All | Sequence[str] | None 默认值: None

headers

传递给请求的附加标头。

类型: dict[str, str] | None 默认值: None

**kwargs

传递给 RemoteGraph.stream 的附加参数。

类型: Any 默认值: {}

返回 描述
dict[str, Any] | Any

图的输出。

ainvoke async

ainvoke(
    input: dict[str, Any] | Any,
    config: RunnableConfig | None = None,
    *,
    interrupt_before: All | Sequence[str] | None = None,
    interrupt_after: All | Sequence[str] | None = None,
    headers: dict[str, str] | None = None,
    params: QueryParamTypes | None = None,
    **kwargs: Any,
) -> dict[str, Any] | Any

创建一个运行,等待其完成并返回最终状态。

参数 描述
输入

图的输入。

类型: dict[str, Any] | Any

配置

用于图调用的 RunnableConfig

类型: RunnableConfig | None 默认值: None

interrupt_before

在这些节点之前中断图。

类型: All | Sequence[str] | None 默认值: None

interrupt_after

在这些节点之后中断图。

类型: All | Sequence[str] | None 默认值: None

headers

传递给请求的附加标头。

类型: dict[str, str] | None 默认值: None

**kwargs

传递给 RemoteGraph.astream 的附加参数。

类型: Any 默认值: {}

返回 描述
dict[str, Any] | Any

图的输出。

get_name

get_name(suffix: str | None = None, *, name: str | None = None) -> str

获取 Runnable 的名称。

参数 描述
后缀

一个可选的后缀,附加到名称上。

类型: str | None 默认值: None

name

一个可选的名称,用于代替 Runnable 的名称。

类型: str | None 默认值: None

返回 描述
str

Runnable 的名称。

get_input_schema

get_input_schema(config: RunnableConfig | None = None) -> type[BaseModel]

获取可用于验证 Runnable 输入的 Pydantic 模型。

利用 configurable_fieldsconfigurable_alternatives 方法的 Runnable 对象将具有一个动态输入模式,该模式取决于调用 Runnable 时使用的配置。

此方法允许获取特定配置的输入模式。

参数 描述
配置

生成模式时使用的配置。

类型: RunnableConfig | None 默认值: None

返回 描述
type[BaseModel]

一个可用于验证输入的 Pydantic 模型。

get_input_jsonschema

get_input_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]

获取表示 Runnable 输入的 JSON 模式。

参数 描述
配置

生成模式时使用的配置。

类型: RunnableConfig | None 默认值: None

返回 描述
dict[str, Any]

表示 Runnable 输入的 JSON 模式。

示例
from langchain_core.runnables import RunnableLambda


def add_one(x: int) -> int:
    return x + 1


runnable = RunnableLambda(add_one)

print(runnable.get_input_jsonschema())

在 0.3.0 版本中新增。

get_output_schema

get_output_schema(config: RunnableConfig | None = None) -> type[BaseModel]

获取可用于验证 Runnable 输出的 Pydantic 模型。

利用 configurable_fieldsconfigurable_alternatives 方法的 Runnable 对象将具有一个动态输出模式,该模式取决于调用 Runnable 时使用的配置。

此方法允许获取特定配置的输出模式。

参数 描述
配置

生成模式时使用的配置。

类型: RunnableConfig | None 默认值: None

返回 描述
type[BaseModel]

一个可用于验证输出的 Pydantic 模型。

get_output_jsonschema

get_output_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]

获取表示 Runnable 输出的 JSON 模式。

参数 描述
配置

生成模式时使用的配置。

类型: RunnableConfig | None 默认值: None

返回 描述
dict[str, Any]

表示 Runnable 输出的 JSON 模式。

示例
from langchain_core.runnables import RunnableLambda


def add_one(x: int) -> int:
    return x + 1


runnable = RunnableLambda(add_one)

print(runnable.get_output_jsonschema())

在 0.3.0 版本中新增。

config_schema

config_schema(*, include: Sequence[str] | None = None) -> type[BaseModel]

Runnable 接受的配置类型,指定为 Pydantic 模型。

要将字段标记为可配置,请参阅 configurable_fieldsconfigurable_alternatives 方法。

参数 描述
包含

要包含在配置模式中的字段列表。

类型: Sequence[str] | None 默认值: None

返回 描述
type[BaseModel]

一个可用于验证配置的 Pydantic 模型。

get_config_jsonschema

get_config_jsonschema(*, include: Sequence[str] | None = None) -> dict[str, Any]

获取表示 Runnable 配置的 JSON 模式。

参数 描述
包含

要包含在配置模式中的字段列表。

类型: Sequence[str] | None 默认值: None

返回 描述
dict[str, Any]

表示 Runnable 配置的 JSON 模式。

在 0.3.0 版本中新增。

get_prompts

get_prompts(config: RunnableConfig | None = None) -> list[BasePromptTemplate]

返回此 Runnable 使用的提示列表。

__or__

__or__(
    other: Runnable[Any, Other]
    | Callable[[Iterator[Any]], Iterator[Other]]
    | Callable[[AsyncIterator[Any]], AsyncIterator[Other]]
    | Callable[[Any], Other]
    | Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any],
) -> RunnableSerializable[Input, Other]

Runnable "or" 运算符。

将此 Runnable 与另一个对象组合以创建 RunnableSequence

参数 描述
other

另一个 Runnable 或类 Runnable 对象。

类型: Runnable[Any, Other] | Callable[[Iterator[Any]], Iterator[Other]] | Callable[[AsyncIterator[Any]], AsyncIterator[Other]] | Callable[[Any], Other] | Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any]

返回 描述
RunnableSerializable[Input, Other]

一个新的 Runnable

__ror__

__ror__(
    other: Runnable[Other, Any]
    | Callable[[Iterator[Other]], Iterator[Any]]
    | Callable[[AsyncIterator[Other]], AsyncIterator[Any]]
    | Callable[[Other], Any]
    | Mapping[str, Runnable[Other, Any] | Callable[[Other], Any] | Any],
) -> RunnableSerializable[Other, Output]

Runnable "reverse-or" 运算符。

将此 Runnable 与另一个对象组合以创建 RunnableSequence

参数 描述
other

另一个 Runnable 或类 Runnable 对象。

类型: Runnable[Other, Any] | Callable[[Iterator[Other]], Iterator[Any]] | Callable[[AsyncIterator[Other]], AsyncIterator[Any]] | Callable[[Other], Any] | Mapping[str, Runnable[Other, Any] | Callable[[Other], Any] | Any]

返回 描述
RunnableSerializable[Other, Output]

一个新的 Runnable

pipe

pipe(
    *others: Runnable[Any, Other] | Callable[[Any], Other], name: str | None = None
) -> RunnableSerializable[Input, Other]

管道连接 Runnable 对象。

将此 Runnable 与类 Runnable 对象组合以构成一个 RunnableSequence

等同于 RunnableSequence(self, *others)self | others[0] | ...

示例
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]
参数 描述
*其他

其他要组合的 Runnable 或类 Runnable 对象

类型: Runnable[Any, Other] | Callable[[Any], Other] 默认值: ()

name

生成的 RunnableSequence 的一个可选名称。

类型: str | None 默认值: None

返回 描述
RunnableSerializable[Input, Other]

一个新的 Runnable

pick

pick(keys: str | list[str]) -> RunnableSerializable[Any, Any]

从此 Runnable 的输出 dict 中选择键。

选择单个键

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]

选择键列表

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]"}
参数 描述
keys

从输出字典中选择的一个键或键列表。

类型: str | list[str]

返回 描述
RunnableSerializable[Any, Any]

一个新的 Runnable

assign

向此 Runnabledict 输出分配新字段。

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}"
)
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'}}}
参数 描述
**kwargs

一个键到 Runnable 或类 Runnable 对象的映射,这些对象将使用此 Runnable 的整个输出字典来调用。

类型: Runnable[dict[str, Any], Any] | Callable[[dict[str, Any]], Any] | Mapping[str, Runnable[dict[str, Any], Any] | Callable[[dict[str, Any]], Any]] 默认值: {}

返回 描述
RunnableSerializable[Any, Any]

一个新的 Runnable

batch

batch(
    inputs: list[Input],
    config: RunnableConfig | list[RunnableConfig] | None = None,
    *,
    return_exceptions: bool = False,
    **kwargs: Any | None,
) -> list[Output]

默认实现使用线程池执行器并行运行 invoke。

批处理的默认实现对于 IO 密集型的 runnable 效果很好。

如果子类能够更有效地进行批处理,则必须重写此方法;例如,如果底层的 Runnable 使用支持批处理模式的 API。

参数 描述
inputs

Runnable 的输入列表。

类型: list[Input]

配置

调用 Runnable 时使用的配置。该配置支持标准键,如用于追踪目的的 'tags''metadata',用于控制并行工作量的 'max_concurrency',以及其他键。请参阅 RunnableConfig 以获取更多详细信息。

类型: RunnableConfig | list[RunnableConfig] | None 默认值: None

返回异常

是否返回异常而不是引发它们。

类型: bool 默认值: False

**kwargs

要传递给 Runnable 的其他关键字参数。

类型: Any | None 默认值: {}

返回 描述
list[Output]

来自 Runnable 的输出列表。

batch_as_completed

batch_as_completed(
    inputs: Sequence[Input],
    config: RunnableConfig | Sequence[RunnableConfig] | None = None,
    *,
    return_exceptions: bool = False,
    **kwargs: Any | None,
) -> Iterator[tuple[int, Output | Exception]]

在输入列表上并行运行 invoke

在结果完成时生成它们。

参数 描述
inputs

Runnable 的输入列表。

类型: Sequence[Input]

配置

调用 Runnable 时使用的配置。该配置支持标准键,如用于追踪目的的 'tags''metadata',用于控制并行工作量的 'max_concurrency',以及其他键。请参阅 RunnableConfig 以获取更多详细信息。

类型: RunnableConfig | Sequence[RunnableConfig] | None 默认值: None

返回异常

是否返回异常而不是引发它们。

类型: bool 默认值: False

**kwargs

要传递给 Runnable 的其他关键字参数。

类型: Any | None 默认值: {}

YIELDS 描述
tuple[int, Output | Exception]

由输入索引和 Runnable 输出组成的元组。

abatch async

abatch(
    inputs: list[Input],
    config: RunnableConfig | list[RunnableConfig] | None = None,
    *,
    return_exceptions: bool = False,
    **kwargs: Any | None,
) -> list[Output]

默认实现使用 asyncio.gather 并行运行 ainvoke

batch 的默认实现对于 IO 密集型的 runnable 效果很好。

如果子类能够更有效地进行批处理,则必须重写此方法;例如,如果底层的 Runnable 使用支持批处理模式的 API。

参数 描述
inputs

Runnable 的输入列表。

类型: list[Input]

配置

调用 Runnable 时使用的配置。该配置支持标准键,如用于追踪目的的 'tags''metadata',用于控制并行工作量的 'max_concurrency',以及其他键。请参阅 RunnableConfig 以获取更多详细信息。

类型: RunnableConfig | list[RunnableConfig] | None 默认值: None

返回异常

是否返回异常而不是引发它们。

类型: bool 默认值: False

**kwargs

要传递给 Runnable 的其他关键字参数。

类型: Any | None 默认值: {}

返回 描述
list[Output]

来自 Runnable 的输出列表。

abatch_as_completed async

abatch_as_completed(
    inputs: Sequence[Input],
    config: RunnableConfig | Sequence[RunnableConfig] | None = None,
    *,
    return_exceptions: bool = False,
    **kwargs: Any | None,
) -> AsyncIterator[tuple[int, Output | Exception]]

在输入列表上并行运行 ainvoke

在结果完成时生成它们。

参数 描述
inputs

Runnable 的输入列表。

类型: Sequence[Input]

配置

调用 Runnable 时使用的配置。该配置支持标准键,如用于追踪目的的 'tags''metadata',用于控制并行工作量的 'max_concurrency',以及其他键。请参阅 RunnableConfig 以获取更多详细信息。

类型: RunnableConfig | Sequence[RunnableConfig] | None 默认值: None

返回异常

是否返回异常而不是引发它们。

类型: bool 默认值: False

**kwargs

要传递给 Runnable 的其他关键字参数。

类型: Any | None 默认值: {}

YIELDS 描述
AsyncIterator[tuple[int, Output | Exception]]

一个由输入索引和 Runnable 输出组成的元组。

astream_log async

astream_log(
    input: Any,
    config: RunnableConfig | None = None,
    *,
    diff: bool = True,
    with_streamed_output_list: bool = True,
    include_names: Sequence[str] | None = None,
    include_types: Sequence[str] | None = None,
    include_tags: Sequence[str] | None = None,
    exclude_names: Sequence[str] | None = None,
    exclude_types: Sequence[str] | None = None,
    exclude_tags: Sequence[str] | None = None,
    **kwargs: Any,
) -> AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]

流式传输 Runnable 的所有输出,如回调系统所报告。

这包括 LLM、检索器、工具等的所有内部运行。

输出以 Log 对象的形式流式传输,其中包括一个 Jsonpatch 操作列表,描述了运行状态在每一步中如何变化,以及运行的最终状态。

可以按顺序应用 Jsonpatch 操作来构造状态。

参数 描述
输入

Runnable 的输入。

类型: Any

配置

用于 Runnable 的配置。

类型: RunnableConfig | None 默认值: None

差异

是生成每一步之间的差异还是当前状态。

类型: bool 默认值: True

带流式输出列表

是否生成 streamed_output 列表。

类型: bool 默认值: True

包含名称

仅包含具有这些名称的日志。

类型: Sequence[str] | None 默认值: None

包含类型

仅包含具有这些类型的日志。

类型: Sequence[str] | None 默认值: None

包含标签

仅包含具有这些标签的日志。

类型: Sequence[str] | None 默认值: None

排除名称

排除具有这些名称的日志。

类型: Sequence[str] | None 默认值: None

排除类型

排除具有这些类型的日志。

类型: Sequence[str] | None 默认值: None

排除标签

排除具有这些标签的日志。

类型: Sequence[str] | None 默认值: None

**kwargs

要传递给 Runnable 的其他关键字参数。

类型: Any 默认值: {}

YIELDS 描述
AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]

一个 RunLogPatchRunLog 对象。

transform

transform(
    input: Iterator[Input], config: RunnableConfig | None = None, **kwargs: Any | None
) -> Iterator[Output]

将输入转换为输出。

transform 的默认实现,它缓冲输入并调用 astream

如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。

参数 描述
输入

Runnable 输入的迭代器。

类型: Iterator[Input]

配置

用于 Runnable 的配置。

类型: RunnableConfig | None 默认值: None

**kwargs

要传递给 Runnable 的其他关键字参数。

类型: Any | None 默认值: {}

YIELDS 描述
输出

Runnable 的输出。

atransform async

atransform(
    input: AsyncIterator[Input],
    config: RunnableConfig | None = None,
    **kwargs: Any | None,
) -> AsyncIterator[Output]

将输入转换为输出。

atransform 的默认实现,它缓冲输入并调用 astream

如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。

参数 描述
输入

Runnable 输入的异步迭代器。

类型: AsyncIterator[Input]

配置

用于 Runnable 的配置。

类型: RunnableConfig | None 默认值: None

**kwargs

要传递给 Runnable 的其他关键字参数。

类型: Any | None 默认值: {}

YIELDS 描述
AsyncIterator[Output]

Runnable 的输出。

bind

bind(**kwargs: Any) -> Runnable[Input, Output]

将参数绑定到 Runnable,返回一个新的 Runnable

当链中的 Runnable 需要一个不在前一个 Runnable 的输出中或未包含在用户输入中的参数时非常有用。

参数 描述
**kwargs

要绑定到 Runnable 的参数。

类型: Any 默认值: {}

返回 描述
Runnable[Input, Output]

一个绑定了参数的新 Runnable

示例
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'

with_listeners

with_listeners(
    *,
    on_start: Callable[[Run], None]
    | Callable[[Run, RunnableConfig], None]
    | None = None,
    on_end: Callable[[Run], None] | Callable[[Run, RunnableConfig], None] | None = None,
    on_error: Callable[[Run], None]
    | Callable[[Run, RunnableConfig], None]
    | None = None,
) -> Runnable[Input, Output]

将生命周期侦听器绑定到 Runnable,返回一个新的 Runnable

Run 对象包含有关运行的信息,包括其 idtypeinputoutputerrorstart_timeend_time 以及添加到运行中的任何标签或元数据。

参数 描述
开始时

Runnable 开始运行之前调用,并传入 Run 对象。

类型: Callable[[Run], None] | Callable[[Run, RunnableConfig], None] | None 默认值: None

结束时

Runnable 完成运行后调用,并传入 Run 对象。

类型: Callable[[Run], None] | Callable[[Run, RunnableConfig], None] | None 默认值: None

出错时

如果 Runnable 抛出错误,则调用此函数,并传入 Run 对象。

类型: Callable[[Run], None] | Callable[[Run, RunnableConfig], None] | None 默认值: None

返回 描述
Runnable[Input, Output]

一个绑定了监听器的新 Runnable

示例
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_alisteners

with_alisteners(
    *,
    on_start: AsyncListener | None = None,
    on_end: AsyncListener | None = None,
    on_error: AsyncListener | None = None,
) -> Runnable[Input, Output]

将异步生命周期侦听器绑定到 Runnable

返回一个新的 Runnable

Run 对象包含有关运行的信息,包括其 idtypeinputoutputerrorstart_timeend_time 以及添加到运行中的任何标签或元数据。

参数 描述
开始时

Runnable 开始运行之前异步调用,并传入 Run 对象。

类型: AsyncListener | None 默认值: None

结束时

Runnable 完成运行后异步调用,并传入 Run 对象。

类型: AsyncListener | None 默认值: None

出错时

如果 Runnable 抛出错误,则异步调用此函数,并传入 Run 对象。

类型: AsyncListener | None 默认值: None

返回 描述
Runnable[Input, Output]

一个绑定了监听器的新 Runnable

示例
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_types

with_types(
    *, input_type: type[Input] | None = None, output_type: type[Output] | None = None
) -> Runnable[Input, Output]

将输入和输出类型绑定到 Runnable,返回一个新的 Runnable

参数 描述
输入类型

要绑定到 Runnable 的输入类型。

类型: type[Input] | None 默认值: None

输出类型

要绑定到 Runnable 的输出类型。

类型: type[Output] | None 默认值: None

返回 描述
Runnable[Input, Output]

一个绑定了类型的新 Runnable

with_retry

with_retry(
    *,
    retry_if_exception_type: tuple[type[BaseException], ...] = (Exception,),
    wait_exponential_jitter: bool = True,
    exponential_jitter_params: ExponentialJitterParams | None = None,
    stop_after_attempt: int = 3,
) -> Runnable[Input, Output]

创建一个新的 Runnable,它在发生异常时重试原始的 Runnable

参数 描述
如果异常类型则重试

一个用于重试的异常类型元组。

类型: tuple[type[BaseException], ...] 默认值: (Exception,)

指数等待抖动

是否在两次重试之间的等待时间中添加抖动。

类型: bool 默认值: True

尝试后停止

放弃前尝试的最大次数。

类型: int 默认值: 3

指数抖动参数

tenacity.wait_exponential_jitter 的参数。即:initialmaxexp_basejitter(均为 float 值)。

类型: ExponentialJitterParams | None 默认值: None

返回 描述
Runnable[Input, Output]

一个新的 Runnable,它会在发生异常时重试原始的 Runnable。

示例
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

map

map() -> Runnable[list[Input], list[Output]]

返回一个新的 Runnable,它将输入列表映射到输出列表。

使用每个输入调用 invoke

返回 描述
Runnable[list[Input], list[Output]]

一个新的 Runnable,它将输入列表映射到输出列表。

示例
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]

with_fallbacks

with_fallbacks(
    fallbacks: Sequence[Runnable[Input, Output]],
    *,
    exceptions_to_handle: tuple[type[BaseException], ...] = (Exception,),
    exception_key: str | None = None,
) -> RunnableWithFallbacks[Input, Output]

Runnable 添加回退机制,返回一个新的 Runnable

新的 Runnable 将在失败时先尝试原始的 Runnable,然后按顺序尝试每个备选方案。

参数 描述
备用方案

如果原始 Runnable 失败,将尝试的一系列 runnable。

类型: Sequence[Runnable[Input, Output]]

要处理的异常

一个要处理的异常类型元组。

类型: tuple[type[BaseException], ...] 默认值: (Exception,)

异常键

如果指定了 string,则已处理的异常将作为输入的一部分,在指定的键下传递给备选方案。如果为 None,异常将不会传递给备选方案。如果使用,基础 Runnable 及其备选方案必须接受一个字典作为输入。

类型: str | None 默认值: None

返回 描述
RunnableWithFallbacks[Input, Output]

一个新的 Runnable,它会在失败时先尝试原始的 Runnable,然后按顺序尝试每个备选方案。

示例
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
参数 描述
备用方案

如果原始 Runnable 失败,将尝试的一系列 runnable。

类型: Sequence[Runnable[Input, Output]]

要处理的异常

一个要处理的异常类型元组。

类型: tuple[type[BaseException], ...] 默认值: (Exception,)

异常键

如果指定了 string,则已处理的异常将作为输入的一部分,在指定的键下传递给备选方案。如果为 None,异常将不会传递给备选方案。如果使用,基础 Runnable 及其备选方案必须接受一个字典作为输入。

类型: str | None 默认值: None

返回 描述
RunnableWithFallbacks[Input, Output]

一个新的 Runnable,它会在失败时先尝试原始的 Runnable,然后按顺序尝试每个备选方案。

as_tool

as_tool(
    args_schema: type[BaseModel] | None = None,
    *,
    name: str | None = None,
    description: str | None = None,
    arg_types: dict[str, type] | None = None,
) -> BaseTool

Runnable 创建一个 BaseTool

as_tool 将从一个 Runnable 实例化一个 BaseTool,该工具具有名称、描述和 args_schema。在可能的情况下,模式会从 runnable.get_input_schema 中推断。或者(例如,如果 Runnable 接受一个字典作为输入,并且特定的字典键没有类型),模式可以通过 args_schema 直接指定。你也可以传递 arg_types 来仅指定必需的参数及其类型。

参数 描述
参数模式

工具的模式。

类型: type[BaseModel] | None 默认值: None

name

工具的名称。

类型: str | None 默认值: None

描述

工具的描述。

类型: str | None 默认值: None

参数类型

一个从参数名称到类型的字典。

类型: dict[str, type] | None 默认值: None

返回 描述
BaseTool

一个 BaseTool 实例。

类型化字典输入

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 输入,通过 args_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 输入,通过 arg_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]})

字符串输入

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")
© . This site is unofficial and not affiliated with LangChain, Inc.