langchain-aws¶
注意
此软件包参考尚未完全迁移到 v1。
langchain_aws ¶
| 函数 | 描述 |
|---|---|
create_neptune_opencypher_qa_chain |
用于对 Neptune 图进行问答的链 |
create_neptune_sparql_qa_chain |
用于对 Neptune 图进行问答的链 |
ChatBedrock ¶
基类: BaseChatModel, BedrockBase
一个使用 Bedrock API 的聊天模型。
| 方法 | 描述 |
|---|---|
get_name |
获取 |
get_input_schema |
获取可用于验证 |
get_input_jsonschema |
获取表示 |
get_output_schema |
获取可用于验证 |
get_output_jsonschema |
获取表示 |
config_schema |
此 |
get_config_jsonschema |
获取表示 |
get_graph |
返回此 |
get_prompts |
返回此 |
__or__ |
Runnable "or" 运算符。 |
__ror__ |
Runnable "reverse-or" 运算符。 |
pipe |
管道连接 |
pick |
从此 |
assign |
向此 |
invoke |
将单个输入转换为输出。 |
ainvoke |
将单个输入转换为输出。 |
batch |
默认实现使用线程池执行器并行运行 invoke。 |
batch_as_completed |
在输入列表上并行运行 |
abatch |
默认实现使用 |
abatch_as_completed |
在输入列表上并行运行 |
stream |
|
astream |
|
astream_log |
流式传输 |
astream_events |
生成事件流。 |
transform |
将输入转换为输出。 |
atransform |
将输入转换为输出。 |
bind |
将参数绑定到 |
with_config |
将配置绑定到 |
with_listeners |
将生命周期侦听器绑定到 |
with_alisteners |
将异步生命周期侦听器绑定到 |
with_types |
将输入和输出类型绑定到 |
with_retry |
创建一个新的 |
map |
返回一个新的 |
with_fallbacks |
向 |
as_tool |
从 |
__init__ |
|
lc_id |
为此类返回一个用于序列化目的的唯一标识符。 |
to_json |
将 |
to_json_not_implemented |
序列化一个“未实现”的对象。 |
configurable_fields |
在运行时配置特定的 |
configurable_alternatives |
为可在运行时设置的 |
set_verbose |
如果 verbose 是 |
generate_prompt |
将一系列提示传递给模型并返回模型生成的内容。 |
agenerate_prompt |
异步地将一系列提示传递并返回模型生成的内容。 |
validate_environment |
验证环境中是否存在 AWS 凭证和 python 包。 |
generate |
将一系列提示传递给模型并返回模型生成的内容。 |
agenerate |
异步地将一系列提示传递给模型并返回生成的内容。 |
dict |
返回 LLM 的字典。 |
is_lc_serializable |
返回此模型是否可以被 Langchain 序列化。 |
get_lc_namespace |
获取 langchain 对象的命名空间。 |
build_extra |
根据传入的额外参数构建额外的关键字参数(kwargs)。 |
get_num_tokens_from_messages |
获取消息中的 token 数量。 |
get_num_tokens |
获取文本中存在的 token 数量。 |
get_token_ids |
返回文本中 token 的有序 ID。 |
set_system_prompt_with_tools |
绑定的变通方法。使用工具设置系统提示 |
bind_tools |
将类工具(tool-like)对象绑定到此聊天模型。 |
with_structured_output |
返回与给定模式匹配的格式化输出的模型包装器。 |
lc_secrets 属性 ¶
构造函数参数名称到密钥 ID 的映射。
例如,{"openai_api_key": "OPENAI_API_KEY"}
cache 类属性 实例属性 ¶
是否缓存响应。
- 如果为
True,将使用全局缓存。 - 如果为
False,将不使用缓存 - 如果为
None,如果设置了全局缓存,则使用全局缓存,否则不使用缓存。 - 如果是
BaseCache的实例,将使用提供的缓存。
目前不支持模型的流式方法的缓存。
verbose 类属性 实例属性 ¶
是否打印响应文本。
metadata 类属性 实例属性 ¶
添加到运行跟踪中的元数据。
custom_get_token_ids 类属性 实例属性 ¶
用于计算 token 的可选编码器。
bedrock_client 类属性 实例属性 ¶
用于进行控制平面 API 调用的 bedrock 客户端
region_name 类属性 实例属性 ¶
AWS 区域,例如 us-west-2。如果此处未提供,则回退到 AWS_REGION 或 AWS_DEFAULT_REGION 环境变量,或 ~/.aws/config 中指定的区域。
credentials_profile_name 类属性 实例属性 ¶
~/.aws/credentials 或 ~/.aws/config 文件中的配置文件名称,其中指定了访问密钥或角色信息。
如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
aws_access_key_id 类属性 实例属性 ¶
aws_access_key_id: SecretStr | None = Field(
default_factory=secret_from_env("AWS_ACCESS_KEY_ID", default=None)
)
AWS 访问密钥 ID。
如果提供,还必须提供 aws_secret_access_key。
如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_ACCESS_KEY_ID 环境变量中读取。
aws_secret_access_key 类属性 实例属性 ¶
aws_secret_access_key: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SECRET_ACCESS_KEY", default=None)
)
AWS secret_access_key。
如果提供,还必须提供 aws_access_key_id。
如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_SECRET_ACCESS_KEY 环境变量中读取。
aws_session_token 类属性 实例属性 ¶
aws_session_token: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SESSION_TOKEN", default=None)
)
AWS 会话令牌。
如果提供,还必须提供 aws_access_key_id 和 aws_secret_access_key。
除非使用临时凭证,否则不是必需的。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_SESSION_TOKEN 环境变量中读取。
provider 类属性 实例属性 ¶
provider: str | None = None
模型提供商,例如 'amazon'、'cohere'、'ai21' 等。如果未提供,则从 model_id 的第一部分提取提供商,例如 'amazon' 中的 'amazon.titan-text-express-v1'。对于 model_id 中不包含提供商的模型,例如具有关联 ARN 的自定义和预置模型,应提供此值。
model_id 类属性 实例属性 ¶
要调用的模型的 ID,例如 'amazon.titan-text-express-v1',这等同于 list-foundation-models api 中的 modelId 属性。对于自定义和预置模型,需要一个 ARN 值。
base_model_id 类属性 实例属性 ¶
一个可选字段,用于传递基础模型 ID。如果提供,将优先于 model_id 的值来识别基础模型。
guardrails 类属性 实例属性 ¶
guardrails: Mapping[str, Any] | None = {
"trace": None,
"guardrailIdentifier": None,
"guardrailVersion": None,
}
一个可选的字典,用于为 Bedrock 配置护栏。
此字段 guardrails 包含两个键:'guardrailId' 和 'guardrailVersion',它们应该是字符串,但初始化为 None。
它用于确定特定的护栏是否已启用并正确设置。
类型
Optional[Mapping[str, str]]:一个包含 'guardrailId' 和 'guardrailVersion' 键的映射。
示例
要为护栏启用跟踪,请将 'trace' 键设置为 True,并将回调处理程序传递给 'generate'、'_call' 方法的 'run_manager' 参数。
示例
有关回调处理程序的更多信息,请参阅 https://python.langchain.ac.cn/docs/concepts/callbacks/。
class BedrockAsyncCallbackHandler(AsyncCallbackHandler): async def on_llm_error( self, error: BaseException, **kwargs: Any, ) -> Any: reason = kwargs.get("reason") if reason == "GUARDRAIL_INTERVENED": ...处理护栏干预的逻辑...
rate_limiter 类属性 实例属性 ¶
rate_limiter: BaseRateLimiter | None = Field(default=None, exclude=True)
一个可选的速率限制器,用于限制请求数量。
disable_streaming 类属性 实例属性 ¶
是否为此模型禁用流式传输。
如果绕过流式传输,则 stream/astream/astream_events 将转而调用 invoke/ainvoke。
- 如果为
True,将始终绕过流式传输情况。 - 如果为
'tool_calling',仅当模型被调用时带有tools关键字参数时,才会绕过流式传输情况。换句话说,仅当提供 tools 参数时,LangChain 才会自动切换到非流式行为 (invoke)。这提供了两全其美的方案。 - 如果为
False(默认值),则在可用时始终使用流式传输情况。
此标志的主要原因是,代码可能是使用 stream 编写的,而用户可能希望将给定模型换成另一个实现不完全支持流式传输的模型。
output_version 类属性 实例属性 ¶
要存储在消息内容中的 AIMessage 输出格式的版本。
AIMessage.content_blocks 将懒解析 content 的内容为标准格式。此标志可用于额外将标准格式存储在消息内容中,例如,用于序列化目的。
支持的值
'v0':内容中特定于提供商的格式(可以使用content_blocks进行懒解析)'v1':内容中的标准化格式(与content_blocks一致)
合作伙伴包(例如 langchain-openai)也可以使用此字段以向后兼容的方式推出新的内容格式。
在版本 1.0 中添加
profile 属性 ¶
返回模型的性能分析信息。
此属性将依赖于 langchain-model-profiles 包来检索聊天模型的能力,例如上下文窗口大小和支持的功能。
| 引发 | 描述 |
|---|---|
ImportError
|
如果未安装 |
| 返回 | 描述 |
|---|---|
ModelProfile
|
一个 |
beta_use_converse_api 类属性 实例属性 ¶
beta_use_converse_api: bool = False
使用新的 Bedrock converse API,它为所有 Bedrock 模型提供了一个标准化的接口。支持仍处于测试阶段。更多信息请参见 ChatBedrockConverse 文档。
stop_sequences 类属性 实例属性 ¶
来自新的 Bedrock converse API 的停止序列推理参数,提供一个导致模型停止生成响应的字符序列。更多信息请参见 https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_InferenceConfiguration.html。
get_name ¶
get_input_schema ¶
get_input_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输入的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输入模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输入模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输入的 Pydantic 模型。 |
get_input_jsonschema ¶
get_input_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输入的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
get_output_schema ¶
get_output_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输出的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输出模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输出模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输出的 Pydantic 模型。 |
get_output_jsonschema ¶
get_output_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输出的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
config_schema ¶
get_config_jsonschema ¶
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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
__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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Other, Output]
|
一个新的 |
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]
| 参数 | 描述 |
|---|---|
*其他
|
其他要组合的 |
name
|
生成的
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
pick ¶
从此 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
|
从输出字典中选择的一个键或键列表。 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
assign ¶
assign(
**kwargs: 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 的 dict 输出分配新字段。
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
|
一个键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
invoke ¶
invoke(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> AIMessage
将单个输入转换为输出。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
调用
类型: |
| 返回 | 描述 |
|---|---|
输出
|
|
ainvoke 异步 ¶
ainvoke(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> AIMessage
将单个输入转换为输出。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
调用
类型: |
| 返回 | 描述 |
|---|---|
输出
|
|
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
tuple[int, Output | Exception]
|
由输入索引和 |
abatch 异步 ¶
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
abatch_as_completed 异步 ¶
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[tuple[int, Output | Exception]]
|
一个由输入索引和 |
stream ¶
stream(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> Iterator[AIMessageChunk]
stream 的默认实现,它调用 invoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
astream 异步 ¶
astream(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> AsyncIterator[AIMessageChunk]
astream 的默认实现,它调用 ainvoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
astream_log 异步 ¶
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 操作来构造状态。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
差异
|
是生成每一步之间的差异还是当前状态。
类型: |
带流式输出列表
|
是否生成
类型: |
包含名称
|
仅包含具有这些名称的日志。 |
包含类型
|
仅包含具有这些类型的日志。 |
包含标签
|
仅包含具有这些标签的日志。 |
排除名称
|
排除具有这些名称的日志。 |
排除类型
|
排除具有这些类型的日志。 |
排除标签
|
排除具有这些标签的日志。 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]
|
一个 |
astream_events 异步 ¶
astream_events(
input: Any,
config: RunnableConfig | None = None,
*,
version: Literal["v1", "v2"] = "v2",
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[StreamEvent]
生成事件流。
用于创建一个 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:
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)
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
版本
|
要使用的模式版本,可以是
类型: |
包含名称
|
仅包括来自具有匹配名称的 |
包含类型
|
仅包括来自具有匹配类型的 |
包含标签
|
仅包括来自具有匹配标签的 |
排除名称
|
排除来自具有匹配名称的 |
排除类型
|
排除来自具有匹配类型的 |
排除标签
|
排除来自具有匹配标签的 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[StreamEvent]
|
|
| 引发 | 描述 |
|---|---|
NotImplementedError
|
如果版本不是 |
transform ¶
transform(
input: Iterator[Input], config: RunnableConfig | None = None, **kwargs: Any | None
) -> Iterator[Output]
将输入转换为输出。
transform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
atransform 异步 ¶
atransform(
input: AsyncIterator[Input],
config: RunnableConfig | None = None,
**kwargs: Any | None,
) -> AsyncIterator[Output]
将输入转换为输出。
atransform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
bind ¶
将参数绑定到 Runnable,返回一个新的 Runnable。
当链中的 Runnable 需要一个不在前一个 Runnable 的输出中或未包含在用户输入中的参数时非常有用。
| 参数 | 描述 |
|---|---|
**kwargs
|
要绑定到
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了参数的新 |
示例
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_config ¶
with_config(
config: RunnableConfig | None = None, **kwargs: Any
) -> Runnable[Input, Output]
将配置绑定到 Runnable,返回一个新的 Runnable。
| 参数 | 描述 |
|---|---|
配置
|
要绑定到
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了配置的新 |
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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_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。
| 参数 | 描述 |
|---|---|
如果异常类型则重试
|
一个用于重试的异常类型元组。
类型: |
指数等待抖动
|
是否在两次重试之间的等待时间中添加抖动。
类型: |
尝试后停止
|
放弃前尝试的最大次数。
类型: |
指数抖动参数
|
类型: |
| 返回 | 描述 |
|---|---|
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 ¶
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,然后按顺序尝试每个备选方案。
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
示例
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
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
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 来仅指定必需的参数及其类型。
| 参数 | 描述 |
|---|---|
参数模式
|
工具的模式。 |
name
|
工具的名称。
类型: |
描述
|
工具的描述。
类型: |
参数类型
|
一个从参数名称到类型的字典。 |
| 返回 | 描述 |
|---|---|
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]})
字符串输入
lc_id 类方法 ¶
为此类返回一个用于序列化目的的唯一标识符。
唯一标识符是一个描述对象路径的字符串列表。
例如,对于类 langchain.llms.openai.OpenAI,id 是 ["langchain", "llms", "openai", "OpenAI"]。
to_json ¶
将 Runnable 序列化为 JSON。
| 返回 | 描述 |
|---|---|
SerializedConstructor | SerializedNotImplemented
|
一个 |
to_json_not_implemented ¶
序列化一个“未实现”的对象。
| 返回 | 描述 |
|---|---|
SerializedNotImplemented
|
|
configurable_fields ¶
configurable_fields(
**kwargs: AnyConfigurableField,
) -> RunnableSerializable[Input, Output]
在运行时配置特定的 Runnable 字段。
| 参数 | 描述 |
|---|---|
**kwargs
|
一个要配置的
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果在 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了字段的新 |
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,
)
configurable_alternatives ¶
configurable_alternatives(
which: ConfigurableField,
*,
default_key: str = "default",
prefix_keys: bool = False,
**kwargs: Runnable[Input, Output] | Callable[[], Runnable[Input, Output]],
) -> RunnableSerializable[Input, Output]
为可在运行时设置的 Runnable 对象配置备选项。
| 参数 | 描述 |
|---|---|
哪个
|
将用于选择备选项的
类型: |
默认键
|
如果未选择备选项,则使用的默认键。
类型: |
前缀键
|
是否用
类型: |
**kwargs
|
一个从键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了备选项的新 |
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
)
set_verbose ¶
generate_prompt ¶
generate_prompt(
prompts: list[PromptValue],
stop: list[str] | None = None,
callbacks: Callbacks = None,
**kwargs: Any,
) -> LLMResult
将一系列提示传递给模型并返回模型生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
agenerate_prompt 异步 ¶
agenerate_prompt(
prompts: list[PromptValue],
stop: list[str] | None = None,
callbacks: Callbacks = None,
**kwargs: Any,
) -> LLMResult
异步地将一系列提示传递并返回模型生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
generate ¶
generate(
messages: list[list[BaseMessage]],
stop: list[str] | None = None,
callbacks: Callbacks = None,
*,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
run_name: str | None = None,
run_id: UUID | None = None,
**kwargs: Any,
) -> LLMResult
将一系列提示传递给模型并返回模型生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
messages
|
消息列表的列表。
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
tags
|
要应用的标签。 |
metadata
|
要应用的元数据。 |
运行名称
|
运行的名称。
类型: |
run_id
|
运行的 ID。
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
agenerate 异步 ¶
agenerate(
messages: list[list[BaseMessage]],
stop: list[str] | None = None,
callbacks: Callbacks = None,
*,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
run_name: str | None = None,
run_id: UUID | None = None,
**kwargs: Any,
) -> LLMResult
异步地将一系列提示传递给模型并返回生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
messages
|
消息列表的列表。
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
tags
|
要应用的标签。 |
metadata
|
要应用的元数据。 |
运行名称
|
运行的名称。
类型: |
run_id
|
运行的 ID。
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
get_lc_namespace 类方法 ¶
get_num_tokens_from_messages ¶
get_num_tokens_from_messages(
messages: list[BaseMessage], tools: Sequence | None = None
) -> int
获取消息中的 token 数量。
用于检查输入是否适合模型的上下文窗口。
注意
get_num_tokens_from_messages 的基本实现忽略了工具模式。
| 参数 | 描述 |
|---|---|
messages
|
要进行分词的消息输入。
类型: |
工具
|
如果提供,则为要转换为工具模式的 dict、
类型: |
| 返回 | 描述 |
|---|---|
int
|
所有消息中词元数量的总和。 |
get_num_tokens ¶
get_token_ids ¶
set_system_prompt_with_tools ¶
set_system_prompt_with_tools(xml_tools_system_prompt: str) -> None
绑定的变通方法。使用工具设置系统提示
bind_tools ¶
bind_tools(
tools: Sequence[dict[str, Any] | TypeBaseModel | Callable | BaseTool],
*,
tool_choice: dict | str | Literal["auto", "none"] | bool | None = None,
**kwargs: Any,
) -> Runnable[LanguageModelInput, AIMessage]
将类工具(tool-like)对象绑定到此聊天模型。
假设模型具有工具调用 API。
| 参数 | 描述 |
|---|---|
工具
|
要绑定到此聊天模型的工具定义列表。可以是字典、Pydantic 模型、可调用对象或 BaseTool。Pydantic 模型、可调用对象和 BaseTool 将自动转换为其模式字典表示形式。
类型: |
工具选择
|
要求模型调用的工具。必须是提供的单个函数的名称,或“auto”以自动确定要调用的函数(如果有),或形式为 {"type": "function", "function": {"name": <...>}} 的字典。
类型: |
**kwargs
|
传递给 Runnable 构造函数的任何其他参数。
类型: |
with_structured_output ¶
with_structured_output(
schema: dict[str, Any] | TypeBaseModel | Type,
*,
include_raw: bool = False,
**kwargs: Any,
) -> Runnable[LanguageModelInput, dict | BaseModel]
返回与给定模式匹配的格式化输出的模型包装器。
| 参数 | 描述 |
|---|---|
模式
|
输出模式,可以是一个字典或一个 Pydantic 类。如果是一个 Pydantic 类,那么模型输出将是该类的对象。如果是一个字典,那么模型输出将是一个字典。使用 Pydantic 类时,返回的属性将得到验证,而使用字典时则不会。 |
包含原始数据
|
如果为 False,则只返回解析后的结构化输出。如果在模型输出解析过程中发生错误,将引发该错误。如果为 True,则返回原始模型响应(一个 BaseMessage)和解析后的模型响应。如果在输出解析过程中发生错误,它将被捕获并作为结果返回。最终输出总是一个包含 "raw"、"parsed" 和 "parsing_error" 键的字典。
类型: |
| 返回 | 描述 |
|---|---|
Runnable[LanguageModelInput, dict | BaseModel]
|
一个接受任何 ChatModel 输入的 Runnable。输出类型取决于 |
Runnable[LanguageModelInput, dict | BaseModel]
|
include_raw 和 schema。 |
Runnable[LanguageModelInput, dict | BaseModel]
|
如果 include_raw 为 True,则输出是一个包含以下键的字典:raw: BaseMessage, parsed: Optional[_DictOrPydantic], parsing_error: Optional[BaseException], |
Runnable[LanguageModelInput, dict | BaseModel]
|
如果 include_raw 为 False 且 schema 是一个 Dict,则 runnable 输出一个 Dict。 |
Runnable[LanguageModelInput, dict | BaseModel]
|
如果 include_raw 为 False 且 schema 是一个 Type[BaseModel],则 runnable |
Runnable[LanguageModelInput, dict | BaseModel]
|
输出一个 BaseModel。 |
Pydantic 模式 (include_raw=False)
from langchain_aws.chat_models.bedrock import ChatBedrock
from pydantic import BaseModel
class AnswerWithJustification(BaseModel):
'''An answer to the user question along with justification for the answer.'''
answer: str
justification: str
llm = ChatBedrock(
model_id="anthropic.claude-3-sonnet-20240229-v1:0",
model_kwargs={"temperature": 0.001},
) # type: ignore[call-arg]
structured_model = model.with_structured_output(AnswerWithJustification)
structured_model.invoke("What weighs more a pound of bricks or a pound of feathers")
# -> AnswerWithJustification(
# answer='They weigh the same',
# justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'
# )
Pydantic 模式 (include_raw=True)
from langchain_aws.chat_models.bedrock import ChatBedrock
from pydantic import BaseModel
class AnswerWithJustification(BaseModel):
'''An answer to the user question along with justification for the answer.'''
answer: str
justification: str
model = ChatBedrock(
model_id="anthropic.claude-3-sonnet-20240229-v1:0",
model_kwargs={"temperature": 0.001},
) # type: ignore[call-arg]
structured_model = model.with_structured_output(AnswerWithJustification, include_raw=True)
structured_model.invoke("What weighs more a pound of bricks or a pound of feathers")
# -> {
# 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_Ao02pnFYXD6GN1yzc0uXPsvF', 'function': {'arguments': '{"answer":"They weigh the same.","justification":"Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ."}', 'name': 'AnswerWithJustification'}, 'type': 'function'}]}),
# 'parsed': AnswerWithJustification(answer='They weigh the same.', justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'),
# 'parsing_error': None
# }
字典模式 (include_raw=False)
from langchain_aws.chat_models.bedrock import ChatBedrock
schema = {
"name": "AnswerWithJustification",
"description": "An answer to the user question along with justification for the answer.",
"input_schema": {
"type": "object",
"properties": {
"answer": {"type": "string"},
"justification": {"type": "string"},
},
"required": ["answer", "justification"]
}
}
model = ChatBedrock(
model_id="anthropic.claude-3-sonnet-20240229-v1:0",
model_kwargs={"temperature": 0.001},
) # type: ignore[call-arg]
structured_model = model.with_structured_output(schema)
structured_model.invoke("What weighs more a pound of bricks or a pound of feathers")
# -> {
# 'answer': 'They weigh the same',
# 'justification': 'Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume and density of the two substances differ.'
# }
ChatBedrockConverse ¶
基类: BaseChatModel
基于 Bedrock converse API 构建的 Bedrock 聊天模型集成。
一旦 Bedrock converse API 与旧版 Bedrock API 功能对等,此实现将最终取代现有的 ChatBedrock 实现。具体来说,converse API 尚不支持自定义 Bedrock 模型。
设置
要使用 Amazon Bedrock,请确保您已完成此处描述的所有步骤: https://docs.aws.amazon.com/bedrock/latest/userguide/setting-up.html
完成后,安装 LangChain 集成
关键初始化参数 — 完成参数: model: str 要使用的 BedrockConverse 模型名称。 temperature: float 采样温度。 max_tokens: Optional[int] 要生成的最大令牌数。
关键初始化参数 — 客户端参数: region_name: Optional[str] 要使用的 AWS 区域,例如 'us-west-2'。 base_url: Optional[str] 要使用的 Bedrock 端点。如果您不想默认使用 us-east-1 端点,则需要此项。 credentials_profile_name: Optional[str] ~/.aws/credentials 或 ~/.aws/config 文件中的配置文件名称。
有关支持的初始化参数及其描述的完整列表,请参见参数部分。
实例化
调用
messages = [
("system", "You are a helpful translator. Translate the user sentence to French."),
("human", "I love programming."),
]
model.invoke(messages)
AIMessage(content=[{'type': 'text', 'text': "J'aime la programmation."}], response_metadata={'ResponseMetadata': {'RequestId': '9ef1e313-a4c1-4f79-b631-171f658d3c0e', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sat, 15 Jun 2024 01:19:24 GMT', 'content-type': 'application/json', 'content-length': '205', 'connection': 'keep-alive', 'x-amzn-requestid': '9ef1e313-a4c1-4f79-b631-171f658d3c0e'}, 'RetryAttempts': 0}, 'stopReason': 'end_turn', 'metrics': {'latencyMs': 609}}, id='run-754e152b-2b41-4784-9538-d40d71a5c3bc-0', usage_metadata={'input_tokens': 25, 'output_tokens': 11, 'total_tokens': 36})
流
AIMessageChunk(content=[], id='run-da3c2606-4792-440a-ac66-72e0d1f6d117')
AIMessageChunk(content=[{'type': 'text', 'text': 'J', 'index': 0}], id='run-da3c2606-4792-440a-ac66-72e0d1f6d117')
AIMessageChunk(content=[{'text': "'", 'index': 0}], id='run-da3c2606-4792-440a-ac66-72e0d1f6d117')
AIMessageChunk(content=[{'text': 'a', 'index': 0}], id='run-da3c2606-4792-440a-ac66-72e0d1f6d117')
AIMessageChunk(content=[{'text': 'ime', 'index': 0}], id='run-da3c2606-4792-440a-ac66-72e0d1f6d117')
AIMessageChunk(content=[{'text': ' la', 'index': 0}], id='run-da3c2606-4792-440a-ac66-72e0d1f6d117')
AIMessageChunk(content=[{'text': ' programm', 'index': 0}], id='run-da3c2606-4792-440a-ac66-72e0d1f6d117')
AIMessageChunk(content=[{'text': 'ation', 'index': 0}], id='run-da3c2606-4792-440a-ac66-72e0d1f6d117')
AIMessageChunk(content=[{'text': '.', 'index': 0}], id='run-da3c2606-4792-440a-ac66-72e0d1f6d117')
AIMessageChunk(content=[{'index': 0}], id='run-da3c2606-4792-440a-ac66-72e0d1f6d117')
AIMessageChunk(content=[], response_metadata={'stopReason': 'end_turn'}, id='run-da3c2606-4792-440a-ac66-72e0d1f6d117')
AIMessageChunk(content=[], response_metadata={'metrics': {'latencyMs': 581}}, id='run-da3c2606-4792-440a-ac66-72e0d1f6d117', usage_metadata={'input_tokens': 25, 'output_tokens': 11, 'total_tokens': 36})
工具调用
from pydantic import BaseModel, Field
class GetWeather(BaseModel):
'''Get the current weather in a given location'''
location: str = Field(..., description="The city and state, e.g. San Francisco, CA")
class GetPopulation(BaseModel):
'''Get the current population in a given location'''
location: str = Field(..., description="The city and state, e.g. San Francisco, CA")
model_with_tools = model.bind_tools([GetWeather, GetPopulation])
ai_msg = model_with_tools.invoke("Which city is hotter today and which is bigger: LA or NY?")
ai_msg.tool_calls
[{'name': 'GetWeather',
'args': {'location': 'Los Angeles, CA'},
'id': 'tooluse_Mspi2igUTQygp-xbX6XGVw'},
{'name': 'GetWeather',
'args': {'location': 'New York, NY'},
'id': 'tooluse_tOPHiDhvR2m0xF5_5tyqWg'},
{'name': 'GetPopulation',
'args': {'location': 'Los Angeles, CA'},
'id': 'tooluse__gcY_klbSC-GqB-bF_pxNg'},
{'name': 'GetPopulation',
'args': {'location': 'New York, NY'},
'id': 'tooluse_-1HSoGX0TQCSaIg7cdFy8Q'}]
更多信息请参见 ChatBedrockConverse.bind_tools() 方法。
结构化输出
from typing import Optional
from pydantic import BaseModel, Field
class Joke(BaseModel):
'''Joke to tell user.'''
setup: str = Field(description="The setup of the joke")
punchline: str = Field(description="The punchline to the joke")
rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10")
structured_model = model.with_structured_output(Joke)
structured_model.invoke("Tell me a joke about cats")
Joke(setup='What do you call a cat that gets all dressed up?', punchline='A purrfessional!', rating=7)
更多信息请参见 ChatBedrockConverse.with_structured_output()。
扩展思考
一些模型,例如 Claude 3.7 Sonnet,支持一种扩展思考功能,可以输出导致答案的逐步推理过程。
要使用它,请在初始化 ChatBedrockConverse 时指定 thinking 参数,如下所示。
您需要指定一个令牌预算才能使用此功能。请参阅使用示例
from langchain_aws import ChatBedrockConverse
thinking_params= {
"thinking": {
"type": "enabled",
"budget_tokens": 2000
}
}
model = ChatBedrockConverse(
model="us.anthropic.claude-3-7-sonnet-20250219-v1:0",
max_tokens=5000,
region_name="us-west-2",
additional_model_request_fields=thinking_params,
)
response = model.invoke("What is the cube root of 50.653?")
print(response.content)
图像输入
import base64
import httpx
from langchain_core.messages import HumanMessage
image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
image_data = base64.b64encode(httpx.get(image_url).content).decode("utf-8")
message = HumanMessage(
content=[
{"type": "text", "text": "describe the weather in this image"},
{
"type": "image",
"source": {"type": "base64", "media_type": "image/jpeg", "data": image_data},
},
],
)
ai_msg = model.invoke([message])
ai_msg.content
[{'type': 'text',
'text': 'The image depicts a sunny day with a partly cloudy sky. The sky is a brilliant blue color with scattered white clouds drifting across. The lighting and cloud patterns suggest pleasant, mild weather conditions. The scene shows an open grassy field or meadow, indicating warm temperatures conducive for vegetation growth. Overall, the weather portrayed in this scenic outdoor image appears to be sunny with some clouds, likely representing a nice, comfortable day.'}]
令牌使用情况
响应元数据
```python
{'ResponseMetadata': {'RequestId': '776a2a26-5946-45ae-859e-82dc5f12017c',
'HTTPStatusCode': 200,
'HTTPHeaders': {'date': 'Mon, 17 Jun 2024 01:37:05 GMT',
'content-type': 'application/json',
'content-length': '206',
'connection': 'keep-alive',
'x-amzn-requestid': '776a2a26-5946-45ae-859e-82dc5f12017c'},
'RetryAttempts': 0},
'stopReason': 'end_turn',
'metrics': {'latencyMs': 1290}}
```
| 方法 | 描述 |
|---|---|
get_name |
获取 |
get_input_schema |
获取可用于验证 |
get_input_jsonschema |
获取表示 |
get_output_schema |
获取可用于验证 |
get_output_jsonschema |
获取表示 |
config_schema |
此 |
get_config_jsonschema |
获取表示 |
get_graph |
返回此 |
get_prompts |
返回此 |
__or__ |
Runnable "or" 运算符。 |
__ror__ |
Runnable "reverse-or" 运算符。 |
pipe |
管道连接 |
pick |
从此 |
assign |
向此 |
invoke |
将单个输入转换为输出。 |
ainvoke |
将单个输入转换为输出。 |
batch |
默认实现使用线程池执行器并行运行 invoke。 |
batch_as_completed |
在输入列表上并行运行 |
abatch |
默认实现使用 |
abatch_as_completed |
在输入列表上并行运行 |
stream |
|
astream |
|
astream_log |
流式传输 |
astream_events |
生成事件流。 |
transform |
将输入转换为输出。 |
atransform |
将输入转换为输出。 |
bind |
将参数绑定到 |
with_config |
将配置绑定到 |
with_listeners |
将生命周期侦听器绑定到 |
with_alisteners |
将异步生命周期侦听器绑定到 |
with_types |
将输入和输出类型绑定到 |
with_retry |
创建一个新的 |
map |
返回一个新的 |
with_fallbacks |
向 |
as_tool |
从 |
__init__ |
|
lc_id |
为此类返回一个用于序列化目的的唯一标识符。 |
to_json |
将 |
to_json_not_implemented |
序列化一个“未实现”的对象。 |
configurable_fields |
在运行时配置特定的 |
configurable_alternatives |
为可在运行时设置的 |
set_verbose |
如果 verbose 是 |
generate_prompt |
将一系列提示传递给模型并返回模型生成的内容。 |
agenerate_prompt |
异步地将一系列提示传递并返回模型生成的内容。 |
get_token_ids |
返回文本中 token 的有序 ID。 |
get_num_tokens |
获取文本中存在的 token 数量。 |
generate |
将一系列提示传递给模型并返回模型生成的内容。 |
agenerate |
异步地将一系列提示传递给模型并返回生成的内容。 |
dict |
返回 LLM 的字典。 |
create_cache_point |
为 Bedrock 创建一个提示缓存配置。 |
build_extra |
根据传入的额外参数构建额外的关键字参数(kwargs)。 |
validate_environment |
验证环境中是否存在 AWS 凭证和 python 包。 |
bind_tools |
将工具绑定到模型。 |
with_structured_output |
返回与给定模式匹配的格式化输出的模型包装器。 |
is_lc_serializable |
这个类是否可序列化? |
get_lc_namespace |
获取 LangChain 对象的命名空间。 |
get_num_tokens_from_messages |
使用 AWS Bedrock count_tokens API 获取消息中的令牌数量。 |
cache 类属性 实例属性 ¶
是否缓存响应。
- 如果为
True,将使用全局缓存。 - 如果为
False,将不使用缓存 - 如果为
None,如果设置了全局缓存,则使用全局缓存,否则不使用缓存。 - 如果是
BaseCache的实例,将使用提供的缓存。
目前不支持模型的流式方法的缓存。
verbose 类属性 实例属性 ¶
是否打印响应文本。
metadata 类属性 实例属性 ¶
添加到运行跟踪中的元数据。
custom_get_token_ids 类属性 实例属性 ¶
用于计算 token 的可选编码器。
rate_limiter 类属性 实例属性 ¶
rate_limiter: BaseRateLimiter | None = Field(default=None, exclude=True)
一个可选的速率限制器,用于限制请求数量。
disable_streaming 类属性 实例属性 ¶
是否为此模型禁用流式传输。
如果绕过流式传输,则 stream/astream/astream_events 将转而调用 invoke/ainvoke。
- 如果为
True,将始终绕过流式传输情况。 - 如果为
'tool_calling',仅当模型被调用时带有tools关键字参数时,才会绕过流式传输情况。换句话说,仅当提供 tools 参数时,LangChain 才会自动切换到非流式行为 (invoke)。这提供了两全其美的方案。 - 如果为
False(默认值),则在可用时始终使用流式传输情况。
此标志的主要原因是,代码可能是使用 stream 编写的,而用户可能希望将给定模型换成另一个实现不完全支持流式传输的模型。
output_version 类属性 实例属性 ¶
要存储在消息内容中的 AIMessage 输出格式的版本。
AIMessage.content_blocks 将懒解析 content 的内容为标准格式。此标志可用于额外将标准格式存储在消息内容中,例如,用于序列化目的。
支持的值
'v0':内容中特定于提供商的格式(可以使用content_blocks进行懒解析)'v1':内容中的标准化格式(与content_blocks一致)
合作伙伴包(例如 langchain-openai)也可以使用此字段以向后兼容的方式推出新的内容格式。
在版本 1.0 中添加
profile 属性 ¶
返回模型的性能分析信息。
此属性将依赖于 langchain-model-profiles 包来检索聊天模型的能力,例如上下文窗口大小和支持的功能。
| 引发 | 描述 |
|---|---|
ImportError
|
如果未安装 |
| 返回 | 描述 |
|---|---|
ModelProfile
|
一个 |
bedrock_client 类属性 实例属性 ¶
用于进行控制平面 API 调用的 bedrock 客户端
model_id 类属性 实例属性 ¶
要调用的模型的 ID。
例如,"anthropic.claude-3-sonnet-20240229-v1:0"。这等同于 list-foundation-models API 中的 modelID 属性。对于自定义和预置模型,需要一个 ARN 值。有关所有支持的内置模型的列表,请参阅 https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html#model-ids-arns。
base_model_id 类属性 实例属性 ¶
一个可选字段,用于传递基础模型 ID。如果提供,将优先于 model_id 的值来识别基础模型。
stop_sequences 类属性 实例属性 ¶
如果出现任何这些子字符串,则停止生成。
top_p 类属性 实例属性 ¶
top_p: float | None = None
为下一个令牌考虑的最可能候选者的百分比。
必须在 0 到 1 之间。
例如,如果您为 topP 选择值 0.8,模型将从序列中下一个可能的令牌概率分布的前 80% 中进行选择。
region_name 类属性 实例属性 ¶
region_name: str | None = None
AWS 区域,例如 us-west-2。
如果此处未提供,则回退到 AWS_REGION 或 AWS_DEFAULT_REGION 环境变量,或在 ~/.aws/config 中指定的区域。
credentials_profile_name 类属性 实例属性 ¶
~/.aws/credentials 或 ~/.aws/config 文件中的配置文件名称。
配置文件应指定访问密钥或角色信息。如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
aws_access_key_id 类属性 实例属性 ¶
aws_access_key_id: SecretStr | None = Field(
default_factory=secret_from_env("AWS_ACCESS_KEY_ID", default=None)
)
AWS 访问密钥 ID。
如果提供,还必须提供 aws_secret_access_key。如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 'AWS_ACCESS_KEY_ID' 环境变量中读取。
aws_secret_access_key 类属性 实例属性 ¶
aws_secret_access_key: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SECRET_ACCESS_KEY", default=None)
)
AWS secret_access_key。
如果提供,则必须同时提供 aws_access_key_id。如果未指定,将使用默认的凭证配置文件,或者(如果是在 EC2 实例上)将使用来自 IMDS 的凭证。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从“AWS_SECRET_ACCESS_KEY”环境变量中读取。
aws_session_token class-attribute instance-attribute ¶
aws_session_token: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SESSION_TOKEN", default=None)
)
AWS 会话令牌。
如果提供,则必须同时提供 aws_access_key_id 和 aws_secret_access_key。除非使用临时凭证,否则不需要。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从“AWS_SESSION_TOKEN”环境变量中读取。
provider class-attribute instance-attribute ¶
provider: str = ''
模型提供商,例如 amazon、cohere、ai21 等。
如果未提供,提供商将从 model_id 的第一部分提取,例如“amazon.titan-text-express-v1”中的“amazon”。对于 model_id 中不包含提供商的模型,例如具有关联 ARN 的自定义模型和预置模型,应提供此值。
endpoint_url class-attribute instance-attribute ¶
如果您不想默认使用 us-east-1 端点,则需要此项。
config class-attribute instance-attribute ¶
config: Any = None
一个可选的 botocore.config.Config 实例,用于传递给客户端。
guardrail_config class-attribute instance-attribute ¶
您想在请求中使用的护栏的配置信息。
additional_model_request_fields class-attribute instance-attribute ¶
模型支持的附加推理参数。
除了 Converse 在 inferenceConfig 字段中支持的基本推理参数集之外的参数。
additional_model_response_field_paths class-attribute instance-attribute ¶
要在响应中返回的附加模型参数字段路径。
Converse 在 additionalModelResponseFields 字段中以 JSON 指针对象的形式返回请求的字段。以下是 additionalModelResponseFieldPaths 的 JSON 示例。
supports_tool_choice_values class-attribute instance-attribute ¶
模型支持的 tool_choice 值类型。
如果未指定,则会进行推断。如果使用“claude-3”模型,则推断为 ('auto', 'any', 'tool');如果使用“mistral-large”模型,则推断为 ('auto', 'any');如果使用“nova”模型,则推断为 ('auto');否则为空。
request_metadata class-attribute instance-attribute ¶
可用于筛选调用日志的键值对。
guard_last_turn_only class-attribute instance-attribute ¶
guard_last_turn_only: bool = False
仅对最后一轮应用护栏的布尔标志。
raw_blocks class-attribute instance-attribute ¶
可以传入的原始 Bedrock 消息块。
LangChain 会原封不动地转发它们,从而支持内容块类型的任意组合。这对于自定义护栏包装非常有用。
lc_secrets property ¶
构造函数参数名称到密钥 ID 的映射。
例如,{"openai_api_key": "OPENAI_API_KEY"}
get_name ¶
get_input_schema ¶
get_input_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输入的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输入模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输入模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输入的 Pydantic 模型。 |
get_input_jsonschema ¶
get_input_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输入的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
get_output_schema ¶
get_output_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输出的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输出模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输出模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输出的 Pydantic 模型。 |
get_output_jsonschema ¶
get_output_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输出的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
config_schema ¶
get_config_jsonschema ¶
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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
__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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Other, Output]
|
一个新的 |
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]
| 参数 | 描述 |
|---|---|
*其他
|
其他要组合的 |
name
|
生成的
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
pick ¶
从此 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
|
从输出字典中选择的一个键或键列表。 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
assign ¶
assign(
**kwargs: 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 的 dict 输出分配新字段。
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
|
一个键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
invoke ¶
invoke(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> AIMessage
将单个输入转换为输出。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
调用
类型: |
| 返回 | 描述 |
|---|---|
输出
|
|
ainvoke async ¶
ainvoke(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> AIMessage
将单个输入转换为输出。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
调用
类型: |
| 返回 | 描述 |
|---|---|
输出
|
|
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
tuple[int, Output | Exception]
|
由输入索引和 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[tuple[int, Output | Exception]]
|
一个由输入索引和 |
stream ¶
stream(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> Iterator[AIMessageChunk]
stream 的默认实现,它调用 invoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
astream async ¶
astream(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> AsyncIterator[AIMessageChunk]
astream 的默认实现,它调用 ainvoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
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 操作来构造状态。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
差异
|
是生成每一步之间的差异还是当前状态。
类型: |
带流式输出列表
|
是否生成
类型: |
包含名称
|
仅包含具有这些名称的日志。 |
包含类型
|
仅包含具有这些类型的日志。 |
包含标签
|
仅包含具有这些标签的日志。 |
排除名称
|
排除具有这些名称的日志。 |
排除类型
|
排除具有这些类型的日志。 |
排除标签
|
排除具有这些标签的日志。 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]
|
一个 |
astream_events async ¶
astream_events(
input: Any,
config: RunnableConfig | None = None,
*,
version: Literal["v1", "v2"] = "v2",
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[StreamEvent]
生成事件流。
用于创建一个 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:
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)
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
版本
|
要使用的模式版本,可以是
类型: |
包含名称
|
仅包括来自具有匹配名称的 |
包含类型
|
仅包括来自具有匹配类型的 |
包含标签
|
仅包括来自具有匹配标签的 |
排除名称
|
排除来自具有匹配名称的 |
排除类型
|
排除来自具有匹配类型的 |
排除标签
|
排除来自具有匹配标签的 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[StreamEvent]
|
|
| 引发 | 描述 |
|---|---|
NotImplementedError
|
如果版本不是 |
transform ¶
transform(
input: Iterator[Input], config: RunnableConfig | None = None, **kwargs: Any | None
) -> Iterator[Output]
将输入转换为输出。
transform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
atransform async ¶
atransform(
input: AsyncIterator[Input],
config: RunnableConfig | None = None,
**kwargs: Any | None,
) -> AsyncIterator[Output]
将输入转换为输出。
atransform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
bind ¶
将参数绑定到 Runnable,返回一个新的 Runnable。
当链中的 Runnable 需要一个不在前一个 Runnable 的输出中或未包含在用户输入中的参数时非常有用。
| 参数 | 描述 |
|---|---|
**kwargs
|
要绑定到
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了参数的新 |
示例
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_config ¶
with_config(
config: RunnableConfig | None = None, **kwargs: Any
) -> Runnable[Input, Output]
将配置绑定到 Runnable,返回一个新的 Runnable。
| 参数 | 描述 |
|---|---|
配置
|
要绑定到
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了配置的新 |
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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_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。
| 参数 | 描述 |
|---|---|
如果异常类型则重试
|
一个用于重试的异常类型元组。
类型: |
指数等待抖动
|
是否在两次重试之间的等待时间中添加抖动。
类型: |
尝试后停止
|
放弃前尝试的最大次数。
类型: |
指数抖动参数
|
类型: |
| 返回 | 描述 |
|---|---|
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 ¶
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,然后按顺序尝试每个备选方案。
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
示例
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
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
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 来仅指定必需的参数及其类型。
| 参数 | 描述 |
|---|---|
参数模式
|
工具的模式。 |
name
|
工具的名称。
类型: |
描述
|
工具的描述。
类型: |
参数类型
|
一个从参数名称到类型的字典。 |
| 返回 | 描述 |
|---|---|
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]})
字符串输入
lc_id classmethod ¶
为此类返回一个用于序列化目的的唯一标识符。
唯一标识符是一个描述对象路径的字符串列表。
例如,对于类 langchain.llms.openai.OpenAI,id 是 ["langchain", "llms", "openai", "OpenAI"]。
to_json ¶
将 Runnable 序列化为 JSON。
| 返回 | 描述 |
|---|---|
SerializedConstructor | SerializedNotImplemented
|
一个 |
to_json_not_implemented ¶
序列化一个“未实现”的对象。
| 返回 | 描述 |
|---|---|
SerializedNotImplemented
|
|
configurable_fields ¶
configurable_fields(
**kwargs: AnyConfigurableField,
) -> RunnableSerializable[Input, Output]
在运行时配置特定的 Runnable 字段。
| 参数 | 描述 |
|---|---|
**kwargs
|
一个要配置的
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果在 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了字段的新 |
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,
)
configurable_alternatives ¶
configurable_alternatives(
which: ConfigurableField,
*,
default_key: str = "default",
prefix_keys: bool = False,
**kwargs: Runnable[Input, Output] | Callable[[], Runnable[Input, Output]],
) -> RunnableSerializable[Input, Output]
为可在运行时设置的 Runnable 对象配置备选项。
| 参数 | 描述 |
|---|---|
哪个
|
将用于选择备选项的
类型: |
默认键
|
如果未选择备选项,则使用的默认键。
类型: |
前缀键
|
是否用
类型: |
**kwargs
|
一个从键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了备选项的新 |
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
)
set_verbose ¶
generate_prompt ¶
generate_prompt(
prompts: list[PromptValue],
stop: list[str] | None = None,
callbacks: Callbacks = None,
**kwargs: Any,
) -> LLMResult
将一系列提示传递给模型并返回模型生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
agenerate_prompt async ¶
agenerate_prompt(
prompts: list[PromptValue],
stop: list[str] | None = None,
callbacks: Callbacks = None,
**kwargs: Any,
) -> LLMResult
异步地将一系列提示传递并返回模型生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
get_token_ids ¶
get_num_tokens ¶
generate ¶
generate(
messages: list[list[BaseMessage]],
stop: list[str] | None = None,
callbacks: Callbacks = None,
*,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
run_name: str | None = None,
run_id: UUID | None = None,
**kwargs: Any,
) -> LLMResult
将一系列提示传递给模型并返回模型生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
messages
|
消息列表的列表。
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
tags
|
要应用的标签。 |
metadata
|
要应用的元数据。 |
运行名称
|
运行的名称。
类型: |
run_id
|
运行的 ID。
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
agenerate async ¶
agenerate(
messages: list[list[BaseMessage]],
stop: list[str] | None = None,
callbacks: Callbacks = None,
*,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
run_name: str | None = None,
run_id: UUID | None = None,
**kwargs: Any,
) -> LLMResult
异步地将一系列提示传递给模型并返回生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
messages
|
消息列表的列表。
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
tags
|
要应用的标签。 |
metadata
|
要应用的元数据。 |
运行名称
|
运行的名称。
类型: |
run_id
|
运行的 ID。
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
create_cache_point classmethod ¶
为 Bedrock 创建一个提示词缓存配置。参数:cache_type:缓存点类型。默认为“default”。返回:包含提示词缓存配置的字典。
bind_tools ¶
with_structured_output ¶
with_structured_output(
schema: _DictOrPydanticClass, *, include_raw: bool = False, **kwargs: Any
) -> Runnable[LanguageModelInput, dict | BaseModel]
返回与给定模式匹配的格式化输出的模型包装器。
| 参数 | 描述 |
|---|---|
模式
|
输出模式。可以作为以下形式传入:
如果 有关在指定 Pydantic 或 |
包含原始数据
|
如果为 最终输出总是一个带有键
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果有任何不支持的 |
NotImplementedError
|
如果模型没有实现 |
| 返回 | 描述 |
|---|---|
Runnable[LanguageModelInput, Dict | BaseModel]
|
一个接受与 如果
|
示例:Pydantic 模式 (include_raw=False)
from pydantic import BaseModel
class AnswerWithJustification(BaseModel):
'''An answer to the user question along with justification for the answer.'''
answer: str
justification: str
model = ChatModel(model="model-name", temperature=0)
structured_model = model.with_structured_output(AnswerWithJustification)
structured_model.invoke(
"What weighs more a pound of bricks or a pound of feathers"
)
# -> AnswerWithJustification(
# answer='They weigh the same',
# justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'
# )
示例:Pydantic 模式 (include_raw=True)
from pydantic import BaseModel
class AnswerWithJustification(BaseModel):
'''An answer to the user question along with justification for the answer.'''
answer: str
justification: str
model = ChatModel(model="model-name", temperature=0)
structured_model = model.with_structured_output(
AnswerWithJustification, include_raw=True
)
structured_model.invoke(
"What weighs more a pound of bricks or a pound of feathers"
)
# -> {
# 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_Ao02pnFYXD6GN1yzc0uXPsvF', 'function': {'arguments': '{"answer":"They weigh the same.","justification":"Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ."}', 'name': 'AnswerWithJustification'}, 'type': 'function'}]}),
# 'parsed': AnswerWithJustification(answer='They weigh the same.', justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'),
# 'parsing_error': None
# }
示例:dict 模式 (include_raw=False)
from pydantic import BaseModel
from langchain_core.utils.function_calling import convert_to_openai_tool
class AnswerWithJustification(BaseModel):
'''An answer to the user question along with justification for the answer.'''
answer: str
justification: str
dict_schema = convert_to_openai_tool(AnswerWithJustification)
model = ChatModel(model="model-name", temperature=0)
structured_model = model.with_structured_output(dict_schema)
structured_model.invoke(
"What weighs more a pound of bricks or a pound of feathers"
)
# -> {
# 'answer': 'They weigh the same',
# 'justification': 'Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume and density of the two substances differ.'
# }
行为在 0.2.26 版本中已更改
添加了对 TypedDict 类的支持。
is_lc_serializable classmethod ¶
is_lc_serializable() -> bool
这个类是否可序列化?
根据设计,即使一个类继承自 Serializable,它默认也是不可序列化的。这是为了防止意外序列化不应被序列化的对象。
| 返回 | 描述 |
|---|---|
bool
|
类是否可序列化。默认为 |
get_lc_namespace classmethod ¶
get_num_tokens_from_messages ¶
get_num_tokens_from_messages(
messages: list[BaseMessage], tools: Sequence | None = None
) -> int
使用 AWS Bedrock count_tokens API 获取消息中的令牌数量。
此方法使用 AWS Bedrock 的 count_tokens API,该 API 在推理前为支持的模型提供准确的令牌计数。对于不支持的模型,将回退到基本实现。
| 参数 | 描述 |
|---|---|
messages
|
要进行分词的消息输入。
类型: |
工具
|
工具模式(被忽略,count_tokens API 不支持)。
类型: |
| 返回 | 描述 |
|---|---|
int
|
消息中的输入令牌数量。 |
BedrockRerank ¶
基类: BaseDocumentCompressor
使用 AWS Bedrock Rerank API 的文档压缩器。
| 方法 | 描述 |
|---|---|
acompress_documents |
异步地根据查询上下文压缩检索到的文档。 |
initialize_client |
初始化 AWS Bedrock 客户端。 |
rerank |
根据与查询的相关性返回一个有序的文档列表。 |
compress_documents |
使用 Bedrock 的 rerank API 压缩文档。 |
client class-attribute instance-attribute ¶
用于压缩文档的 Bedrock 客户端。
region_name class-attribute instance-attribute ¶
region_name: str | None = None
AWS 区域,例如 us-west-2。
如果未在此处提供,则回退到 `AWS_REGION` 或 `AWS_DEFAULT_REGION` 环境变量或 `~/.aws/config` 中指定的区域。
credentials_profile_name class-attribute instance-attribute ¶
credentials_profile_name: str | None = Field(
default_factory=from_env("AWS_PROFILE", default=None)
)
用于身份验证的 AWS 配置文件,可选。
aws_access_key_id class-attribute instance-attribute ¶
aws_access_key_id: SecretStr | None = Field(
default_factory=secret_from_env("AWS_ACCESS_KEY_ID", default=None)
)
AWS 访问密钥 ID。
如果提供,则必须同时提供 `aws_secret_access_key`。如果未指定,将使用默认的凭证配置文件,或者(如果是在 EC2 实例上)将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_ACCESS_KEY_ID 环境变量中读取。
aws_secret_access_key class-attribute instance-attribute ¶
aws_secret_access_key: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SECRET_ACCESS_KEY", default=None)
)
AWS secret_access_key。
如果提供,则必须同时提供 aws_access_key_id。如果未指定,将使用默认的凭证配置文件,或者(如果是在 EC2 实例上)将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_SECRET_ACCESS_KEY 环境变量中读取。
aws_session_token class-attribute instance-attribute ¶
aws_session_token: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SESSION_TOKEN", default=None)
)
AWS 会话令牌。
如果提供,则必须同时提供 aws_access_key_id 和 aws_secret_access_key。除非使用临时凭证,否则不需要。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_SESSION_TOKEN 环境变量中读取。
endpoint_url class-attribute instance-attribute ¶
如果您不想默认使用 us-east-1 端点,则需要此项。
config class-attribute instance-attribute ¶
config: Any = None
一个可选的 botocore.config.Config 实例,用于传递给客户端。
acompress_documents async ¶
initialize_client classmethod ¶
初始化 AWS Bedrock 客户端。
rerank ¶
rerank(
documents: Sequence[str | Document | dict],
query: str,
top_n: int | None = None,
additional_model_request_fields: dict[str, Any] | None = None,
) -> list[dict[str, Any]]
BedrockEmbeddings ¶
基类:BaseModel, Embeddings
Bedrock 嵌入模型。
为了进行身份验证,AWS 客户端使用以下方法自动加载凭证:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果应使用特定的凭证配置文件,您必须传递要使用的 ~/.aws/credentials 文件中的配置文件名称。
确保所使用的凭证/角色具有访问 Bedrock 服务所需的策略。
| 方法 | 描述 |
|---|---|
validate_environment |
验证环境中是否存在 AWS 凭证和 python 包。 |
embed_documents |
使用 Bedrock 模型计算文档嵌入。 |
embed_query |
使用 Bedrock 模型计算查询嵌入。 |
aembed_query |
异步地使用 Bedrock 模型计算查询嵌入。 |
aembed_documents |
异步地使用 Bedrock 模型计算文档嵌入。 |
client class-attribute instance-attribute ¶
Bedrock 客户端。
region_name class-attribute instance-attribute ¶
region_name: str | None = None
AWS 区域,例如 `us-west-2`。
如果未在此处提供,则回退到 `AWS_REGION`/`AWS_DEFAULT_REGION` 环境变量或 `~/.aws/config` 中指定的区域。
credentials_profile_name class-attribute instance-attribute ¶
credentials_profile_name: str | None = None
`~/.aws/credentials` 或 `~/.aws/config` 文件中的配置文件名称,其中指定了访问密钥或角色信息。如果未指定,将使用默认的凭证配置文件,或者(如果是在 EC2 实例上)将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
aws_access_key_id class-attribute instance-attribute ¶
aws_access_key_id: SecretStr | None = Field(
default_factory=secret_from_env("AWS_ACCESS_KEY_ID", default=None)
)
AWS 访问密钥 ID。
如果提供,则必须同时提供 aws_secret_access_key。如果未指定,将使用默认的凭证配置文件,或者(如果是在 EC2 实例上)将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_ACCESS_KEY_ID 环境变量中读取。
aws_secret_access_key class-attribute instance-attribute ¶
aws_secret_access_key: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SECRET_ACCESS_KEY", default=None)
)
AWS secret_access_key。
如果提供,则必须同时提供 aws_access_key_id。如果未指定,将使用默认的凭证配置文件,或者(如果是在 EC2 实例上)将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_SECRET_ACCESS_KEY 环境变量中读取。
aws_session_token class-attribute instance-attribute ¶
aws_session_token: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SESSION_TOKEN", default=None)
)
AWS 会话令牌。
如果提供,还必须提供 aws_access_key_id 和 aws_secret_access_key。
除非使用临时凭证,否则不是必需的。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_SESSION_TOKEN 环境变量中读取。
model_id class-attribute instance-attribute ¶
model_id: str = 'amazon.titan-embed-text-v1'
要调用的模型 ID,例如 `'amazon.titan-embed-text-v1'`,这相当于 list-foundation-models api 中的 `modelId` 属性
provider class-attribute instance-attribute ¶
provider: str | None = None
提供商的名称,例如 amazon、cohere 等。如果未指定,将从 `model_id` 推断提供商。
endpoint_url class-attribute instance-attribute ¶
endpoint_url: str | None = None
如果您不想默认使用 'us-east-1' 端点,则需要此项。
config class-attribute instance-attribute ¶
config: Any = None
一个可选的 botocore.config.Config 实例,传递给客户端。
embed_documents ¶
embed_query ¶
aembed_query async ¶
NeptuneAnalyticsGraph ¶
基类: BaseNeptuneGraph
用于图操作的 Neptune Analytics 包装器。
| 参数 | 描述 |
|---|---|
client
|
可选的 boto3 Neptune 客户端
类型: |
credentials_profile_name
|
可选的 AWS 配置文件名称
类型: |
region_name
|
可选的 AWS 区域,例如 us-west-2
类型: |
graph_identifier
|
Neptune Analytics 图的图标识符
类型: |
安全提示:请确保数据库连接使用的凭证具有严格限定的范围,仅包含必要的权限。否则可能导致数据损坏或丢失,因为调用代码可能会在适当提示下尝试执行会导致删除、篡改数据的命令,或者如果数据库中存在敏感数据,则会读取这些数据。防止此类负面结果的最佳方法是(酌情)限制授予此工具使用的凭证的权限。
See https://docs.langchain.org.cn/oss/python/security-policy for more information.
| 方法 | 描述 |
|---|---|
__init__ |
创建一个新的 Neptune Analytics 图包装器实例。 |
query |
查询 Neptune 数据库。 |
__init__ ¶
__init__(
graph_identifier: str,
client: Any = None,
credentials_profile_name: str | None = None,
region_name: str | None = None,
aws_access_key_id: SecretStr | None = None,
aws_secret_access_key: SecretStr | None = None,
aws_session_token: SecretStr | None = None,
endpoint_url: str | None = None,
config: Config | None = None,
property_descriptions: dict[tuple[str, str], str] | None = None,
) -> None
创建一个新的 Neptune Analytics 图包装器实例。
NeptuneGraph ¶
基类: BaseNeptuneGraph
用于图操作的 Neptune 包装器。
| 参数 | 描述 |
|---|---|
host
|
数据库实例的端点
类型: |
port
|
数据库实例的端口号,默认为 8182
类型: |
use_https
|
是否使用安全连接,默认为 True
类型: |
client
|
可选的 boto3 Neptune 客户端
类型: |
credentials_profile_name
|
可选的 AWS 配置文件名称
类型: |
region_name
|
可选的 AWS 区域,例如 us-west-2
类型: |
sign
|
是否对请求负载进行签名,默认为 True
类型: |
aws_access_key_id
|
可选的 AWS 访问密钥 ID
类型: |
aws_secret_access_key
|
可选的 AWS 秘密访问密钥
类型: |
aws_session_token
|
可选的 AWS 会话令牌
类型: |
endpoint_url
|
可选的自定义端点 URL
类型: |
配置
|
可选的 botocore Config 对象
类型: |
安全提示:请确保数据库连接使用的凭证具有严格限定的范围,仅包含必要的权限。否则可能导致数据损坏或丢失,因为调用代码可能会在适当提示下尝试执行会导致删除、篡改数据的命令,或者如果数据库中存在敏感数据,则会读取这些数据。防止此类负面结果的最佳方法是(酌情)限制授予此工具使用的凭证的权限。
See https://docs.langchain.org.cn/oss/python/security-policy for more information.
| 方法 | 描述 |
|---|---|
__init__ |
创建一个新的 Neptune 图包装器实例。 |
query |
查询 Neptune 数据库。 |
__init__ ¶
__init__(
host: str,
port: int = 8182,
use_https: bool = True,
client: Any = None,
credentials_profile_name: str | None = None,
region_name: str | None = None,
sign: bool = True,
aws_access_key_id: SecretStr | None = None,
aws_secret_access_key: SecretStr | None = None,
aws_session_token: SecretStr | None = None,
endpoint_url: str | None = None,
config: Config | None = None,
property_descriptions: dict[tuple[str, str], str] | None = None,
) -> None
创建一个新的 Neptune 图包装器实例。
BedrockLLM ¶
基类: LLM, BedrockBase
Bedrock 模型。
为了进行身份验证,AWS 客户端使用以下方法自动加载凭证:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果应使用特定的凭证配置文件,您必须传递要使用的 `~/.aws/credentials` 文件中的配置文件名称。
确保所使用的凭证/角色具有访问 Bedrock 服务所需的策略。
| 方法 | 描述 |
|---|---|
get_name |
获取 |
get_input_schema |
获取可用于验证 |
get_input_jsonschema |
获取表示 |
get_output_schema |
获取可用于验证 |
get_output_jsonschema |
获取表示 |
config_schema |
此 |
get_config_jsonschema |
获取表示 |
get_graph |
返回此 |
get_prompts |
返回此 |
__or__ |
Runnable "or" 运算符。 |
__ror__ |
Runnable "reverse-or" 运算符。 |
pipe |
管道连接 |
pick |
从此 |
assign |
向此 |
invoke |
将单个输入转换为输出。 |
ainvoke |
将单个输入转换为输出。 |
batch |
默认实现使用线程池执行器并行运行 invoke。 |
batch_as_completed |
在输入列表上并行运行 |
abatch |
默认实现使用 |
abatch_as_completed |
在输入列表上并行运行 |
stream |
|
astream |
|
astream_log |
流式传输 |
astream_events |
生成事件流。 |
transform |
将输入转换为输出。 |
atransform |
将输入转换为输出。 |
bind |
将参数绑定到 |
with_config |
将配置绑定到 |
with_listeners |
将生命周期侦听器绑定到 |
with_alisteners |
将异步生命周期侦听器绑定到 |
with_types |
将输入和输出类型绑定到 |
with_retry |
创建一个新的 |
map |
返回一个新的 |
with_fallbacks |
向 |
as_tool |
从 |
__init__ |
|
lc_id |
为此类返回一个用于序列化目的的唯一标识符。 |
to_json |
将 |
to_json_not_implemented |
序列化一个“未实现”的对象。 |
configurable_fields |
在运行时配置特定的 |
configurable_alternatives |
为可在运行时设置的 |
set_verbose |
如果 verbose 是 |
generate_prompt |
将一系列提示传递给模型并返回模型生成的内容。 |
agenerate_prompt |
异步地将一系列提示传递并返回模型生成的内容。 |
with_structured_output |
此类未实现。 |
get_num_tokens_from_messages |
获取消息中的 token 数量。 |
validate_environment |
验证环境中是否存在 AWS 凭证和 python 包。 |
generate |
向模型传递一系列提示并返回生成结果。 |
agenerate |
异步地将一系列提示传递给模型并返回生成的内容。 |
__str__ |
返回对象的字符串表示形式以供打印。 |
dict |
返回 LLM 的字典。 |
save |
保存 LLM。 |
is_lc_serializable |
返回此模型是否可以被 Langchain 序列化。 |
get_lc_namespace |
获取 langchain 对象的命名空间。 |
get_num_tokens |
获取文本中存在的 token 数量。 |
get_token_ids |
返回文本中 token 的有序 ID。 |
lc_secrets property ¶
构造函数参数名称到密钥 ID 的映射。
例如,{"openai_api_key": "OPENAI_API_KEY"}
cache class-attribute instance-attribute ¶
是否缓存响应。
- 如果为
True,将使用全局缓存。 - 如果为
False,将不使用缓存 - 如果为
None,如果设置了全局缓存,则使用全局缓存,否则不使用缓存。 - 如果是
BaseCache的实例,将使用提供的缓存。
目前不支持模型的流式方法的缓存。
verbose class-attribute instance-attribute ¶
是否打印响应文本。
callbacks class-attribute instance-attribute ¶
callbacks: Callbacks = Field(default=None, exclude=True)
添加到运行跟踪中的回调。
tags class-attribute instance-attribute ¶
添加到运行跟踪中的标签。
metadata class-attribute instance-attribute ¶
添加到运行跟踪中的元数据。
custom_get_token_ids class-attribute instance-attribute ¶
用于计算 token 的可选编码器。
client class-attribute instance-attribute ¶
用于进行数据平面 API 调用的 bedrock 运行时客户端
bedrock_client class-attribute instance-attribute ¶
用于进行控制平面 API 调用的 bedrock 客户端
region_name class-attribute instance-attribute ¶
AWS 区域,例如 us-west-2。如果此处未提供,则回退到 AWS_REGION 或 AWS_DEFAULT_REGION 环境变量,或 ~/.aws/config 中指定的区域。
credentials_profile_name class-attribute instance-attribute ¶
~/.aws/credentials 或 ~/.aws/config 文件中的配置文件名称,其中指定了访问密钥或角色信息。
如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
aws_access_key_id class-attribute instance-attribute ¶
aws_access_key_id: SecretStr | None = Field(
default_factory=secret_from_env("AWS_ACCESS_KEY_ID", default=None)
)
AWS 访问密钥 ID。
如果提供,还必须提供 aws_secret_access_key。
如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_ACCESS_KEY_ID 环境变量中读取。
aws_secret_access_key class-attribute instance-attribute ¶
aws_secret_access_key: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SECRET_ACCESS_KEY", default=None)
)
AWS secret_access_key。
如果提供,还必须提供 aws_access_key_id。
如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_SECRET_ACCESS_KEY 环境变量中读取。
aws_session_token class-attribute instance-attribute ¶
aws_session_token: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SESSION_TOKEN", default=None)
)
AWS 会话令牌。
如果提供,还必须提供 aws_access_key_id 和 aws_secret_access_key。
除非使用临时凭证,否则不是必需的。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_SESSION_TOKEN 环境变量中读取。
config class-attribute instance-attribute ¶
config: Any = None
一个可选的 botocore.config.Config 实例,传递给客户端。
provider class-attribute instance-attribute ¶
provider: str | None = None
模型提供商,例如 'amazon'、'cohere'、'ai21' 等。如果未提供,则从 model_id 的第一部分提取提供商,例如 'amazon' 中的 'amazon.titan-text-express-v1'。对于 model_id 中不包含提供商的模型,例如具有关联 ARN 的自定义和预置模型,应提供此值。
model_id class-attribute instance-attribute ¶
要调用的模型的 ID,例如 'amazon.titan-text-express-v1',这等同于 list-foundation-models api 中的 modelId 属性。对于自定义和预置模型,需要一个 ARN 值。
base_model_id class-attribute instance-attribute ¶
一个可选字段,用于传递基础模型 ID。如果提供,将优先于 model_id 的值来识别基础模型。
model_kwargs class-attribute instance-attribute ¶
传递给模型的关键字参数。
endpoint_url class-attribute instance-attribute ¶
endpoint_url: str | None = None
如果您不想默认使用 'us-east-1' 端点,则需要此项。
guardrails class-attribute instance-attribute ¶
guardrails: Mapping[str, Any] | None = {
"trace": None,
"guardrailIdentifier": None,
"guardrailVersion": None,
}
一个可选的字典,用于为 Bedrock 配置护栏。
此字段 guardrails 包含两个键:'guardrailId' 和 'guardrailVersion',它们应该是字符串,但初始化为 None。
它用于确定特定的护栏是否已启用并正确设置。
类型
Optional[Mapping[str, str]]:一个包含 'guardrailId' 和 'guardrailVersion' 键的映射。
示例
要为护栏启用跟踪,请将 'trace' 键设置为 True,并将回调处理程序传递给 'generate'、'_call' 方法的 'run_manager' 参数。
示例
有关回调处理程序的更多信息,请参阅 https://python.langchain.ac.cn/docs/concepts/callbacks/。
class BedrockAsyncCallbackHandler(AsyncCallbackHandler): async def on_llm_error( self, error: BaseException, **kwargs: Any, ) -> Any: reason = kwargs.get("reason") if reason == "GUARDRAIL_INTERVENED": ...处理护栏干预的逻辑...
lc_attributes property ¶
应包含在序列化 kwargs 中的属性名称列表。
这些属性必须被构造函数接受。
默认为空字典。
get_name ¶
get_input_schema ¶
get_input_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输入的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输入模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输入模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输入的 Pydantic 模型。 |
get_input_jsonschema ¶
get_input_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输入的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
get_output_schema ¶
get_output_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输出的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输出模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输出模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输出的 Pydantic 模型。 |
get_output_jsonschema ¶
get_output_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输出的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
config_schema ¶
get_config_jsonschema ¶
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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
__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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Other, Output]
|
一个新的 |
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]
| 参数 | 描述 |
|---|---|
*其他
|
其他要组合的 |
name
|
生成的
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
pick ¶
从此 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
|
从输出字典中选择的一个键或键列表。 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
assign ¶
assign(
**kwargs: 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 的 dict 输出分配新字段。
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
|
一个键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
invoke ¶
invoke(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> str
将单个输入转换为输出。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
调用
类型: |
| 返回 | 描述 |
|---|---|
输出
|
|
ainvoke async ¶
ainvoke(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> str
将单个输入转换为输出。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
调用
类型: |
| 返回 | 描述 |
|---|---|
输出
|
|
batch ¶
batch(
inputs: list[LanguageModelInput],
config: RunnableConfig | list[RunnableConfig] | None = None,
*,
return_exceptions: bool = False,
**kwargs: Any,
) -> list[str]
默认实现使用线程池执行器并行运行 invoke。
批处理的默认实现对于 IO 密集型的 runnable 效果很好。
如果子类能够更有效地进行批处理,则必须重写此方法;例如,如果底层的 Runnable 使用支持批处理模式的 API。
| 参数 | 描述 |
|---|---|
inputs
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
tuple[int, Output | Exception]
|
由输入索引和 |
abatch async ¶
abatch(
inputs: list[LanguageModelInput],
config: RunnableConfig | list[RunnableConfig] | None = None,
*,
return_exceptions: bool = False,
**kwargs: Any,
) -> list[str]
默认实现使用 asyncio.gather 并行运行 ainvoke。
batch 的默认实现对于 IO 密集型的 runnable 效果很好。
如果子类能够更有效地进行批处理,则必须重写此方法;例如,如果底层的 Runnable 使用支持批处理模式的 API。
| 参数 | 描述 |
|---|---|
inputs
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[tuple[int, Output | Exception]]
|
一个由输入索引和 |
stream ¶
stream(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> Iterator[str]
stream 的默认实现,它调用 invoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
astream async ¶
astream(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> AsyncIterator[str]
astream 的默认实现,它调用 ainvoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
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 操作来构造状态。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
差异
|
是生成每一步之间的差异还是当前状态。
类型: |
带流式输出列表
|
是否生成
类型: |
包含名称
|
仅包含具有这些名称的日志。 |
包含类型
|
仅包含具有这些类型的日志。 |
包含标签
|
仅包含具有这些标签的日志。 |
排除名称
|
排除具有这些名称的日志。 |
排除类型
|
排除具有这些类型的日志。 |
排除标签
|
排除具有这些标签的日志。 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]
|
一个 |
astream_events async ¶
astream_events(
input: Any,
config: RunnableConfig | None = None,
*,
version: Literal["v1", "v2"] = "v2",
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[StreamEvent]
生成事件流。
用于创建一个 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:
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)
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
版本
|
要使用的模式版本,可以是
类型: |
包含名称
|
仅包括来自具有匹配名称的 |
包含类型
|
仅包括来自具有匹配类型的 |
包含标签
|
仅包括来自具有匹配标签的 |
排除名称
|
排除来自具有匹配名称的 |
排除类型
|
排除来自具有匹配类型的 |
排除标签
|
排除来自具有匹配标签的 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[StreamEvent]
|
|
| 引发 | 描述 |
|---|---|
NotImplementedError
|
如果版本不是 |
transform ¶
transform(
input: Iterator[Input], config: RunnableConfig | None = None, **kwargs: Any | None
) -> Iterator[Output]
将输入转换为输出。
transform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
atransform async ¶
atransform(
input: AsyncIterator[Input],
config: RunnableConfig | None = None,
**kwargs: Any | None,
) -> AsyncIterator[Output]
将输入转换为输出。
atransform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
bind ¶
将参数绑定到 Runnable,返回一个新的 Runnable。
当链中的 Runnable 需要一个不在前一个 Runnable 的输出中或未包含在用户输入中的参数时非常有用。
| 参数 | 描述 |
|---|---|
**kwargs
|
要绑定到
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了参数的新 |
示例
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_config ¶
with_config(
config: RunnableConfig | None = None, **kwargs: Any
) -> Runnable[Input, Output]
将配置绑定到 Runnable,返回一个新的 Runnable。
| 参数 | 描述 |
|---|---|
配置
|
要绑定到
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了配置的新 |
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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_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。
| 参数 | 描述 |
|---|---|
如果异常类型则重试
|
一个用于重试的异常类型元组。
类型: |
指数等待抖动
|
是否在两次重试之间的等待时间中添加抖动。
类型: |
尝试后停止
|
放弃前尝试的最大次数。
类型: |
指数抖动参数
|
类型: |
| 返回 | 描述 |
|---|---|
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 ¶
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,然后按顺序尝试每个备选方案。
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
示例
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
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
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 来仅指定必需的参数及其类型。
| 参数 | 描述 |
|---|---|
参数模式
|
工具的模式。 |
name
|
工具的名称。
类型: |
描述
|
工具的描述。
类型: |
参数类型
|
一个从参数名称到类型的字典。 |
| 返回 | 描述 |
|---|---|
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]})
字符串输入
lc_id classmethod ¶
为此类返回一个用于序列化目的的唯一标识符。
唯一标识符是一个描述对象路径的字符串列表。
例如,对于类 langchain.llms.openai.OpenAI,id 是 ["langchain", "llms", "openai", "OpenAI"]。
to_json ¶
将 Runnable 序列化为 JSON。
| 返回 | 描述 |
|---|---|
SerializedConstructor | SerializedNotImplemented
|
一个 |
to_json_not_implemented ¶
序列化一个“未实现”的对象。
| 返回 | 描述 |
|---|---|
SerializedNotImplemented
|
|
configurable_fields ¶
configurable_fields(
**kwargs: AnyConfigurableField,
) -> RunnableSerializable[Input, Output]
在运行时配置特定的 Runnable 字段。
| 参数 | 描述 |
|---|---|
**kwargs
|
一个要配置的
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果在 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了字段的新 |
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,
)
configurable_alternatives ¶
configurable_alternatives(
which: ConfigurableField,
*,
default_key: str = "default",
prefix_keys: bool = False,
**kwargs: Runnable[Input, Output] | Callable[[], Runnable[Input, Output]],
) -> RunnableSerializable[Input, Output]
为可在运行时设置的 Runnable 对象配置备选项。
| 参数 | 描述 |
|---|---|
哪个
|
将用于选择备选项的
类型: |
默认键
|
如果未选择备选项,则使用的默认键。
类型: |
前缀键
|
是否用
类型: |
**kwargs
|
一个从键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了备选项的新 |
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
)
set_verbose ¶
generate_prompt ¶
generate_prompt(
prompts: list[PromptValue],
stop: list[str] | None = None,
callbacks: Callbacks | list[Callbacks] | None = None,
**kwargs: Any,
) -> LLMResult
将一系列提示传递给模型并返回模型生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
agenerate_prompt async ¶
agenerate_prompt(
prompts: list[PromptValue],
stop: list[str] | None = None,
callbacks: Callbacks | list[Callbacks] | None = None,
**kwargs: Any,
) -> LLMResult
异步地将一系列提示传递并返回模型生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
with_structured_output ¶
with_structured_output(
schema: dict | type, **kwargs: Any
) -> Runnable[LanguageModelInput, dict | BaseModel]
此类未实现。
get_num_tokens_from_messages ¶
get_num_tokens_from_messages(
messages: list[BaseMessage], tools: Sequence | None = None
) -> int
获取消息中的 token 数量。
用于检查输入是否适合模型的上下文窗口。
注意
get_num_tokens_from_messages 的基本实现忽略了工具模式。
| 参数 | 描述 |
|---|---|
messages
|
要进行分词的消息输入。
类型: |
工具
|
如果提供,则为要转换为工具模式的 dict、
类型: |
| 返回 | 描述 |
|---|---|
int
|
所有消息中词元数量的总和。 |
generate ¶
generate(
prompts: list[str],
stop: list[str] | None = None,
callbacks: Callbacks | list[Callbacks] | None = None,
*,
tags: list[str] | list[list[str]] | None = None,
metadata: dict[str, Any] | list[dict[str, Any]] | None = None,
run_name: str | list[str] | None = None,
run_id: UUID | list[UUID | None] | None = None,
**kwargs: Any,
) -> LLMResult
向模型传递一系列提示并返回生成结果。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
字符串提示列表。 |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
tags
|
要与每个提示关联的标签列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
metadata
|
要与每个提示关联的元数据字典列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
运行名称
|
要与每个提示关联的运行名称列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
run_id
|
要与每个提示关联的运行 ID 列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果提示不是列表。 |
ValueError
|
如果 `callbacks`、`tags`、`metadata` 或 `run_name`(如果提供)的长度与提示的长度不匹配。 |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
agenerate async ¶
agenerate(
prompts: list[str],
stop: list[str] | None = None,
callbacks: Callbacks | list[Callbacks] | None = None,
*,
tags: list[str] | list[list[str]] | None = None,
metadata: dict[str, Any] | list[dict[str, Any]] | None = None,
run_name: str | list[str] | None = None,
run_id: UUID | list[UUID | None] | None = None,
**kwargs: Any,
) -> LLMResult
异步地将一系列提示传递给模型并返回生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
字符串提示列表。 |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
tags
|
要与每个提示关联的标签列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
metadata
|
要与每个提示关联的元数据字典列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
运行名称
|
要与每个提示关联的运行名称列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
run_id
|
要与每个提示关联的运行 ID 列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果 `callbacks`、`tags`、`metadata` 或 `run_name`(如果提供)的长度与提示的长度不匹配。 |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
save ¶
get_lc_namespace classmethod ¶
get_num_tokens ¶
SagemakerEndpoint ¶
基类:LLM
Sagemaker 推理终端节点模型。
要使用,您必须提供已部署的 Sagemaker 模型的终端节点名称及其部署的区域。
为了进行身份验证,AWS 客户端使用以下方法自动加载凭证:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果应使用特定的凭证配置文件,您必须传递要使用的 `~/.aws/credentials` 文件中的配置文件名称。
请确保所使用的凭证/角色具有访问 Sagemaker 终端节点所需的策略。
请参阅:https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html
| 方法 | 描述 |
|---|---|
get_name |
获取 |
get_input_schema |
获取可用于验证 |
get_input_jsonschema |
获取表示 |
get_output_schema |
获取可用于验证 |
get_output_jsonschema |
获取表示 |
config_schema |
此 |
get_config_jsonschema |
获取表示 |
get_graph |
返回此 |
get_prompts |
返回此 |
__or__ |
Runnable "or" 运算符。 |
__ror__ |
Runnable "reverse-or" 运算符。 |
pipe |
管道连接 |
pick |
从此 |
assign |
向此 |
invoke |
将单个输入转换为输出。 |
ainvoke |
将单个输入转换为输出。 |
batch |
默认实现使用线程池执行器并行运行 invoke。 |
batch_as_completed |
在输入列表上并行运行 |
abatch |
默认实现使用 |
abatch_as_completed |
在输入列表上并行运行 |
stream |
|
astream |
|
astream_log |
流式传输 |
astream_events |
生成事件流。 |
transform |
将输入转换为输出。 |
atransform |
将输入转换为输出。 |
bind |
将参数绑定到 |
with_config |
将配置绑定到 |
with_listeners |
将生命周期侦听器绑定到 |
with_alisteners |
将异步生命周期侦听器绑定到 |
with_types |
将输入和输出类型绑定到 |
with_retry |
创建一个新的 |
map |
返回一个新的 |
with_fallbacks |
向 |
as_tool |
从 |
__init__ |
|
is_lc_serializable |
这个类是否可序列化? |
get_lc_namespace |
获取 LangChain 对象的命名空间。 |
lc_id |
为此类返回一个用于序列化目的的唯一标识符。 |
to_json |
将 |
to_json_not_implemented |
序列化一个“未实现”的对象。 |
configurable_fields |
在运行时配置特定的 |
configurable_alternatives |
为可在运行时设置的 |
set_verbose |
如果 verbose 是 |
generate_prompt |
将一系列提示传递给模型并返回模型生成的内容。 |
agenerate_prompt |
异步地将一系列提示传递并返回模型生成的内容。 |
with_structured_output |
此类未实现。 |
get_token_ids |
返回文本中 token 的有序 ID。 |
get_num_tokens |
获取文本中存在的 token 数量。 |
get_num_tokens_from_messages |
获取消息中的 token 数量。 |
generate |
向模型传递一系列提示并返回生成结果。 |
agenerate |
异步地将一系列提示传递给模型并返回生成的内容。 |
__str__ |
返回对象的字符串表示形式以供打印。 |
dict |
返回 LLM 的字典。 |
save |
保存 LLM。 |
validate_environment |
如果客户端是外部提供的,则不执行任何操作 |
lc_secrets property ¶
构造函数参数名称到密钥 ID 的映射。
例如,{"openai_api_key": "OPENAI_API_KEY"}
cache class-attribute instance-attribute ¶
是否缓存响应。
- 如果为
True,将使用全局缓存。 - 如果为
False,将不使用缓存 - 如果为
None,如果设置了全局缓存,则使用全局缓存,否则不使用缓存。 - 如果是
BaseCache的实例,将使用提供的缓存。
目前不支持模型的流式方法的缓存。
verbose class-attribute instance-attribute ¶
是否打印响应文本。
callbacks class-attribute instance-attribute ¶
callbacks: Callbacks = Field(default=None, exclude=True)
添加到运行跟踪中的回调。
tags class-attribute instance-attribute ¶
添加到运行跟踪中的标签。
metadata class-attribute instance-attribute ¶
添加到运行跟踪中的元数据。
custom_get_token_ids class-attribute instance-attribute ¶
用于计算 token 的可选编码器。
endpoint_name class-attribute instance-attribute ¶
endpoint_name: str = ''
已部署的 Sagemaker 模型的终端节点名称。
在 AWS 区域内必须是唯一的。
inference_component_name class-attribute instance-attribute ¶
inference_component_name: str | None = None
如果与终端节点名称一起指定,则为要调用的推理组件的可选名称。
region_name class-attribute instance-attribute ¶
region_name: str = ''
Sagemaker 模型部署的 AWS 区域,例如 `'us-west-2'`。
credentials_profile_name class-attribute instance-attribute ¶
credentials_profile_name: str | None = None
在 `~/.aws/credentials` 或 `~/.aws/config` 文件中的配置文件名称,其中指定了访问密钥或角色信息。
如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
aws_access_key_id class-attribute instance-attribute ¶
aws_access_key_id: SecretStr | None = Field(
default_factory=secret_from_env("AWS_ACCESS_KEY_ID", default=None)
)
AWS 访问密钥 ID。
如果提供,还必须提供 aws_secret_access_key。如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 'AWS_ACCESS_KEY_ID' 环境变量中读取。
aws_secret_access_key class-attribute instance-attribute ¶
aws_secret_access_key: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SECRET_ACCESS_KEY", default=None)
)
AWS secret_access_key。
如果提供,还必须提供 aws_access_key_id。
如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_SECRET_ACCESS_KEY 环境变量中读取。
aws_session_token class-attribute instance-attribute ¶
aws_session_token: SecretStr | None = Field(
default_factory=secret_from_env("AWS_SESSION_TOKEN", default=None)
)
AWS 会话令牌。
如果提供,还必须提供 aws_access_key_id 和 aws_secret_access_key。
除非使用临时凭证,否则不是必需的。
参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
如果未提供,将从 AWS_SESSION_TOKEN 环境变量中读取。
config class-attribute instance-attribute ¶
config: Any = None
一个可选的 botocore.config.Config 实例,传递给客户端。
endpoint_url class-attribute instance-attribute ¶
endpoint_url: str | None = None
如果您不想默认使用 'us-east-1' 端点,则需要此项。
content_handler instance-attribute ¶
内容处理程序类,提供输入和输出转换函数,用于处理 LLM 和终端节点之间的格式。
endpoint_kwargs class-attribute instance-attribute ¶
endpoint_kwargs: dict | None = None
传递给 invoke_endpoint 函数的可选属性。有关更多信息,请参阅 `boto3` 文档。
get_name ¶
get_input_schema ¶
get_input_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输入的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输入模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输入模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输入的 Pydantic 模型。 |
get_input_jsonschema ¶
get_input_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输入的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
get_output_schema ¶
get_output_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输出的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输出模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输出模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输出的 Pydantic 模型。 |
get_output_jsonschema ¶
get_output_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输出的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
config_schema ¶
get_config_jsonschema ¶
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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
__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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Other, Output]
|
一个新的 |
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]
| 参数 | 描述 |
|---|---|
*其他
|
其他要组合的 |
name
|
生成的
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
pick ¶
从此 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
|
从输出字典中选择的一个键或键列表。 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
assign ¶
assign(
**kwargs: 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 的 dict 输出分配新字段。
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
|
一个键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
invoke ¶
invoke(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> str
将单个输入转换为输出。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
调用
类型: |
| 返回 | 描述 |
|---|---|
输出
|
|
ainvoke async ¶
ainvoke(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> str
将单个输入转换为输出。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
调用
类型: |
| 返回 | 描述 |
|---|---|
输出
|
|
batch ¶
batch(
inputs: list[LanguageModelInput],
config: RunnableConfig | list[RunnableConfig] | None = None,
*,
return_exceptions: bool = False,
**kwargs: Any,
) -> list[str]
默认实现使用线程池执行器并行运行 invoke。
批处理的默认实现对于 IO 密集型的 runnable 效果很好。
如果子类能够更有效地进行批处理,则必须重写此方法;例如,如果底层的 Runnable 使用支持批处理模式的 API。
| 参数 | 描述 |
|---|---|
inputs
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
tuple[int, Output | Exception]
|
由输入索引和 |
abatch async ¶
abatch(
inputs: list[LanguageModelInput],
config: RunnableConfig | list[RunnableConfig] | None = None,
*,
return_exceptions: bool = False,
**kwargs: Any,
) -> list[str]
默认实现使用 asyncio.gather 并行运行 ainvoke。
batch 的默认实现对于 IO 密集型的 runnable 效果很好。
如果子类能够更有效地进行批处理,则必须重写此方法;例如,如果底层的 Runnable 使用支持批处理模式的 API。
| 参数 | 描述 |
|---|---|
inputs
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[tuple[int, Output | Exception]]
|
一个由输入索引和 |
stream ¶
stream(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> Iterator[str]
stream 的默认实现,它调用 invoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
astream async ¶
astream(
input: LanguageModelInput,
config: RunnableConfig | None = None,
*,
stop: list[str] | None = None,
**kwargs: Any,
) -> AsyncIterator[str]
astream 的默认实现,它调用 ainvoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
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 操作来构造状态。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
差异
|
是生成每一步之间的差异还是当前状态。
类型: |
带流式输出列表
|
是否生成
类型: |
包含名称
|
仅包含具有这些名称的日志。 |
包含类型
|
仅包含具有这些类型的日志。 |
包含标签
|
仅包含具有这些标签的日志。 |
排除名称
|
排除具有这些名称的日志。 |
排除类型
|
排除具有这些类型的日志。 |
排除标签
|
排除具有这些标签的日志。 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]
|
一个 |
astream_events async ¶
astream_events(
input: Any,
config: RunnableConfig | None = None,
*,
version: Literal["v1", "v2"] = "v2",
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[StreamEvent]
生成事件流。
用于创建一个 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:
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)
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
版本
|
要使用的模式版本,可以是
类型: |
包含名称
|
仅包括来自具有匹配名称的 |
包含类型
|
仅包括来自具有匹配类型的 |
包含标签
|
仅包括来自具有匹配标签的 |
排除名称
|
排除来自具有匹配名称的 |
排除类型
|
排除来自具有匹配类型的 |
排除标签
|
排除来自具有匹配标签的 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[StreamEvent]
|
|
| 引发 | 描述 |
|---|---|
NotImplementedError
|
如果版本不是 |
transform ¶
transform(
input: Iterator[Input], config: RunnableConfig | None = None, **kwargs: Any | None
) -> Iterator[Output]
将输入转换为输出。
transform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
atransform async ¶
atransform(
input: AsyncIterator[Input],
config: RunnableConfig | None = None,
**kwargs: Any | None,
) -> AsyncIterator[Output]
将输入转换为输出。
atransform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
bind ¶
将参数绑定到 Runnable,返回一个新的 Runnable。
当链中的 Runnable 需要一个不在前一个 Runnable 的输出中或未包含在用户输入中的参数时非常有用。
| 参数 | 描述 |
|---|---|
**kwargs
|
要绑定到
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了参数的新 |
示例
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_config ¶
with_config(
config: RunnableConfig | None = None, **kwargs: Any
) -> Runnable[Input, Output]
将配置绑定到 Runnable,返回一个新的 Runnable。
| 参数 | 描述 |
|---|---|
配置
|
要绑定到
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了配置的新 |
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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_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。
| 参数 | 描述 |
|---|---|
如果异常类型则重试
|
一个用于重试的异常类型元组。
类型: |
指数等待抖动
|
是否在两次重试之间的等待时间中添加抖动。
类型: |
尝试后停止
|
放弃前尝试的最大次数。
类型: |
指数抖动参数
|
类型: |
| 返回 | 描述 |
|---|---|
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 ¶
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,然后按顺序尝试每个备选方案。
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
示例
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
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
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 来仅指定必需的参数及其类型。
| 参数 | 描述 |
|---|---|
参数模式
|
工具的模式。 |
name
|
工具的名称。
类型: |
描述
|
工具的描述。
类型: |
参数类型
|
一个从参数名称到类型的字典。 |
| 返回 | 描述 |
|---|---|
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]})
字符串输入
is_lc_serializable classmethod ¶
is_lc_serializable() -> bool
这个类是否可序列化?
根据设计,即使一个类继承自 Serializable,它默认也是不可序列化的。这是为了防止意外序列化不应被序列化的对象。
| 返回 | 描述 |
|---|---|
bool
|
类是否可序列化。默认为 |
get_lc_namespace classmethod ¶
lc_id classmethod ¶
为此类返回一个用于序列化目的的唯一标识符。
唯一标识符是一个描述对象路径的字符串列表。
例如,对于类 langchain.llms.openai.OpenAI,id 是 ["langchain", "llms", "openai", "OpenAI"]。
to_json ¶
将 Runnable 序列化为 JSON。
| 返回 | 描述 |
|---|---|
SerializedConstructor | SerializedNotImplemented
|
一个 |
to_json_not_implemented ¶
序列化一个“未实现”的对象。
| 返回 | 描述 |
|---|---|
SerializedNotImplemented
|
|
configurable_fields ¶
configurable_fields(
**kwargs: AnyConfigurableField,
) -> RunnableSerializable[Input, Output]
在运行时配置特定的 Runnable 字段。
| 参数 | 描述 |
|---|---|
**kwargs
|
一个要配置的
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果在 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了字段的新 |
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,
)
configurable_alternatives ¶
configurable_alternatives(
which: ConfigurableField,
*,
default_key: str = "default",
prefix_keys: bool = False,
**kwargs: Runnable[Input, Output] | Callable[[], Runnable[Input, Output]],
) -> RunnableSerializable[Input, Output]
为可在运行时设置的 Runnable 对象配置备选项。
| 参数 | 描述 |
|---|---|
哪个
|
将用于选择备选项的
类型: |
默认键
|
如果未选择备选项,则使用的默认键。
类型: |
前缀键
|
是否用
类型: |
**kwargs
|
一个从键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了备选项的新 |
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
)
set_verbose ¶
generate_prompt ¶
generate_prompt(
prompts: list[PromptValue],
stop: list[str] | None = None,
callbacks: Callbacks | list[Callbacks] | None = None,
**kwargs: Any,
) -> LLMResult
将一系列提示传递给模型并返回模型生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
agenerate_prompt async ¶
agenerate_prompt(
prompts: list[PromptValue],
stop: list[str] | None = None,
callbacks: Callbacks | list[Callbacks] | None = None,
**kwargs: Any,
) -> LLMResult
异步地将一系列提示传递并返回模型生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
类型: |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
with_structured_output ¶
with_structured_output(
schema: dict | type, **kwargs: Any
) -> Runnable[LanguageModelInput, dict | BaseModel]
此类未实现。
get_token_ids ¶
get_num_tokens ¶
get_num_tokens_from_messages ¶
get_num_tokens_from_messages(
messages: list[BaseMessage], tools: Sequence | None = None
) -> int
获取消息中的 token 数量。
用于检查输入是否适合模型的上下文窗口。
注意
get_num_tokens_from_messages 的基本实现忽略了工具模式。
| 参数 | 描述 |
|---|---|
messages
|
要进行分词的消息输入。
类型: |
工具
|
如果提供,则为要转换为工具模式的 dict、
类型: |
| 返回 | 描述 |
|---|---|
int
|
所有消息中词元数量的总和。 |
generate ¶
generate(
prompts: list[str],
stop: list[str] | None = None,
callbacks: Callbacks | list[Callbacks] | None = None,
*,
tags: list[str] | list[list[str]] | None = None,
metadata: dict[str, Any] | list[dict[str, Any]] | None = None,
run_name: str | list[str] | None = None,
run_id: UUID | list[UUID | None] | None = None,
**kwargs: Any,
) -> LLMResult
向模型传递一系列提示并返回生成结果。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
字符串提示列表。 |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
tags
|
要与每个提示关联的标签列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
metadata
|
要与每个提示关联的元数据字典列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
运行名称
|
要与每个提示关联的运行名称列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
run_id
|
要与每个提示关联的运行 ID 列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果提示不是列表。 |
ValueError
|
如果 `callbacks`、`tags`、`metadata` 或 `run_name`(如果提供)的长度与提示的长度不匹配。 |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
agenerate async ¶
agenerate(
prompts: list[str],
stop: list[str] | None = None,
callbacks: Callbacks | list[Callbacks] | None = None,
*,
tags: list[str] | list[list[str]] | None = None,
metadata: dict[str, Any] | list[dict[str, Any]] | None = None,
run_name: str | list[str] | None = None,
run_id: UUID | list[UUID | None] | None = None,
**kwargs: Any,
) -> LLMResult
异步地将一系列提示传递给模型并返回生成的内容。
对于提供批量 API 的模型,此方法应利用批量调用。
当你想要
- 利用批量调用,
- 需要从模型获得比最高生成值更多的输出,
- 正在构建与底层语言模型类型无关的链(例如,纯文本补全模型与聊天模型)。
| 参数 | 描述 |
|---|---|
prompts
|
字符串提示列表。 |
停止
|
生成时使用的停止词。模型输出在首次出现这些子字符串中的任何一个时被截断。 |
回调
|
要传递的
类型: |
tags
|
要与每个提示关联的标签列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
metadata
|
要与每个提示关联的元数据字典列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
运行名称
|
要与每个提示关联的运行名称列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
run_id
|
要与每个提示关联的运行 ID 列表。如果提供,列表的长度必须与提示列表的长度匹配。 |
**kwargs
|
任意附加的关键字参数。这些通常会传递给模型提供商的 API 调用。
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果 `callbacks`、`tags`、`metadata` 或 `run_name`(如果提供)的长度与提示的长度不匹配。 |
| 返回 | 描述 |
|---|---|
LLMResult
|
一个 |
save ¶
AmazonKendraRetriever ¶
基类: BaseRetriever
“Amazon Kendra 索引”检索器。
| 属性 | 描述 |
|---|---|
index_id |
Kendra 索引 ID
类型: |
region_name |
AWS 区域,例如 `'us-west-2'`。回退到 `AWS_REGION`/`AWS_DEFAULT_REGION` 环境变量或 `~/.aws/config` 中指定的区域。
类型: |
credentials_profile_name |
`~/.aws/credentials` 或 `~/.aws/config` 文件中的配置文件名称,其中指定了访问密钥或角色信息。如果未指定,将使用默认的凭证配置文件,或者(如果是在 EC2 实例上)将使用来自 IMDS 的凭证。
类型: |
aws_access_key_id |
AWS 访问密钥 ID。如果提供,还必须提供 `aws_secret_access_key`。如果未指定,将使用默认的凭证配置文件,或者在 EC2 实例上,将使用来自 IMDS 的凭证。 参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从
类型: |
aws_secret_access_key |
AWS secret_access_key。如果提供,还必须提供 `aws_access_key_id`。如果未指定,将使用默认的凭证配置文件,或者在 EC2 实例上,将使用来自 IMDS 的凭证。 参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从
类型: |
aws_session_token |
AWS 会话令牌。如果提供,还必须提供 `aws_access_key_id` 和 `aws_secret_access_key`。除非使用临时凭证,否则不需要。 参见: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从
类型: |
endpoint_url |
如果您不想默认使用 `'us-east-1'` 终端节点,则需要此项。
类型: |
配置 |
一个可选的
类型: |
top_k |
要返回的结果数
类型: |
attribute_filter |
基于元数据对结果进行额外筛选
类型: |
page_content_formatter |
生成 Document page_content,允许访问所有结果项属性。默认情况下,它使用项目的标题和摘要。 |
client |
Kendra 的 boto3 客户端
类型: |
user_context |
提供有关用户上下文的信息 请参阅:https://docs.aws.amazon.com/kendra/latest/APIReference
类型: |
| 方法 | 描述 |
|---|---|
get_name |
获取 |
get_input_schema |
获取可用于验证 |
get_input_jsonschema |
获取表示 |
get_output_schema |
获取可用于验证 |
get_output_jsonschema |
获取表示 |
config_schema |
此 |
get_config_jsonschema |
获取表示 |
get_graph |
返回此 |
get_prompts |
返回此 |
__or__ |
Runnable "or" 运算符。 |
__ror__ |
Runnable "reverse-or" 运算符。 |
pipe |
管道连接 |
pick |
从此 |
assign |
向此 |
invoke |
调用检索器以获取相关文档。 |
ainvoke |
异步调用检索器以获取相关文档。 |
batch |
默认实现使用线程池执行器并行运行 invoke。 |
batch_as_completed |
在输入列表上并行运行 |
abatch |
默认实现使用 |
abatch_as_completed |
在输入列表上并行运行 |
stream |
|
astream |
|
astream_log |
流式传输 |
astream_events |
生成事件流。 |
transform |
将输入转换为输出。 |
atransform |
将输入转换为输出。 |
bind |
将参数绑定到 |
with_config |
将配置绑定到 |
with_listeners |
将生命周期侦听器绑定到 |
with_alisteners |
将异步生命周期侦听器绑定到 |
with_types |
将输入和输出类型绑定到 |
with_retry |
创建一个新的 |
map |
返回一个新的 |
with_fallbacks |
向 |
as_tool |
从 |
__init__ |
|
is_lc_serializable |
这个类是否可序列化? |
get_lc_namespace |
获取 LangChain 对象的命名空间。 |
lc_id |
为此类返回一个用于序列化目的的唯一标识符。 |
to_json |
将 |
to_json_not_implemented |
序列化一个“未实现”的对象。 |
configurable_fields |
在运行时配置特定的 |
configurable_alternatives |
为可在运行时设置的 |
lc_secrets property ¶
构造函数参数名称到密钥 ID 的映射。
例如,{"openai_api_key": "OPENAI_API_KEY"}
tags class-attribute instance-attribute ¶
与检索器关联的可选标签列表。
这些标签将与对此检索器的每次调用相关联,并作为参数传递给在 callbacks 中定义的处理程序。
您可以使用这些标签来识别特定检索器实例及其用例。
metadata class-attribute instance-attribute ¶
与检索器关联的可选元数据。
此元数据将与对此检索器的每次调用相关联,并作为参数传递给在 callbacks 中定义的处理程序。
您可以使用这些标签来识别特定检索器实例及其用例。
get_name ¶
get_input_schema ¶
get_input_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输入的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输入模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输入模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输入的 Pydantic 模型。 |
get_input_jsonschema ¶
get_input_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输入的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
get_output_schema ¶
get_output_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输出的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输出模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输出模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输出的 Pydantic 模型。 |
get_output_jsonschema ¶
get_output_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输出的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
config_schema ¶
get_config_jsonschema ¶
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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
__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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Other, Output]
|
一个新的 |
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]
| 参数 | 描述 |
|---|---|
*其他
|
其他要组合的 |
name
|
生成的
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
pick ¶
从此 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
|
从输出字典中选择的一个键或键列表。 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
assign ¶
assign(
**kwargs: 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 的 dict 输出分配新字段。
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
|
一个键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
invoke ¶
invoke(
input: str, config: RunnableConfig | None = None, **kwargs: Any
) -> list[Document]
调用检索器以获取相关文档。
同步检索器调用的主入口点。
| 参数 | 描述 |
|---|---|
输入
|
查询字符串。
类型: |
配置
|
检索器的配置。
类型: |
**kwargs
|
要传递给检索器的额外参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
相关文档的列表。 |
示例
ainvoke async ¶
ainvoke(
input: str, config: RunnableConfig | None = None, **kwargs: Any
) -> list[Document]
异步调用检索器以获取相关文档。
异步检索器调用的主入口点。
| 参数 | 描述 |
|---|---|
输入
|
查询字符串。
类型: |
配置
|
检索器的配置。
类型: |
**kwargs
|
要传递给检索器的额外参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
相关文档的列表。 |
示例
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
tuple[int, Output | Exception]
|
由输入索引和 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[tuple[int, Output | Exception]]
|
一个由输入索引和 |
stream ¶
stream(
input: Input, config: RunnableConfig | None = None, **kwargs: Any | None
) -> Iterator[Output]
stream 的默认实现,它调用 invoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
astream async ¶
astream(
input: Input, config: RunnableConfig | None = None, **kwargs: Any | None
) -> AsyncIterator[Output]
astream 的默认实现,它调用 ainvoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
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 操作来构造状态。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
差异
|
是生成每一步之间的差异还是当前状态。
类型: |
带流式输出列表
|
是否生成
类型: |
包含名称
|
仅包含具有这些名称的日志。 |
包含类型
|
仅包含具有这些类型的日志。 |
包含标签
|
仅包含具有这些标签的日志。 |
排除名称
|
排除具有这些名称的日志。 |
排除类型
|
排除具有这些类型的日志。 |
排除标签
|
排除具有这些标签的日志。 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]
|
一个 |
astream_events async ¶
astream_events(
input: Any,
config: RunnableConfig | None = None,
*,
version: Literal["v1", "v2"] = "v2",
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[StreamEvent]
生成事件流。
用于创建一个 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:
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)
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
版本
|
要使用的模式版本,可以是
类型: |
包含名称
|
仅包括来自具有匹配名称的 |
包含类型
|
仅包括来自具有匹配类型的 |
包含标签
|
仅包括来自具有匹配标签的 |
排除名称
|
排除来自具有匹配名称的 |
排除类型
|
排除来自具有匹配类型的 |
排除标签
|
排除来自具有匹配标签的 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[StreamEvent]
|
|
| 引发 | 描述 |
|---|---|
NotImplementedError
|
如果版本不是 |
transform ¶
transform(
input: Iterator[Input], config: RunnableConfig | None = None, **kwargs: Any | None
) -> Iterator[Output]
将输入转换为输出。
transform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
atransform async ¶
atransform(
input: AsyncIterator[Input],
config: RunnableConfig | None = None,
**kwargs: Any | None,
) -> AsyncIterator[Output]
将输入转换为输出。
atransform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
bind ¶
将参数绑定到 Runnable,返回一个新的 Runnable。
当链中的 Runnable 需要一个不在前一个 Runnable 的输出中或未包含在用户输入中的参数时非常有用。
| 参数 | 描述 |
|---|---|
**kwargs
|
要绑定到
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了参数的新 |
示例
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_config ¶
with_config(
config: RunnableConfig | None = None, **kwargs: Any
) -> Runnable[Input, Output]
将配置绑定到 Runnable,返回一个新的 Runnable。
| 参数 | 描述 |
|---|---|
配置
|
要绑定到
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了配置的新 |
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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_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。
| 参数 | 描述 |
|---|---|
如果异常类型则重试
|
一个用于重试的异常类型元组。
类型: |
指数等待抖动
|
是否在两次重试之间的等待时间中添加抖动。
类型: |
尝试后停止
|
放弃前尝试的最大次数。
类型: |
指数抖动参数
|
类型: |
| 返回 | 描述 |
|---|---|
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 ¶
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,然后按顺序尝试每个备选方案。
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
示例
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
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
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 来仅指定必需的参数及其类型。
| 参数 | 描述 |
|---|---|
参数模式
|
工具的模式。 |
name
|
工具的名称。
类型: |
描述
|
工具的描述。
类型: |
参数类型
|
一个从参数名称到类型的字典。 |
| 返回 | 描述 |
|---|---|
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]})
字符串输入
is_lc_serializable classmethod ¶
is_lc_serializable() -> bool
这个类是否可序列化?
根据设计,即使一个类继承自 Serializable,它默认也是不可序列化的。这是为了防止意外序列化不应被序列化的对象。
| 返回 | 描述 |
|---|---|
bool
|
类是否可序列化。默认为 |
get_lc_namespace classmethod ¶
lc_id classmethod ¶
为此类返回一个用于序列化目的的唯一标识符。
唯一标识符是一个描述对象路径的字符串列表。
例如,对于类 langchain.llms.openai.OpenAI,id 是 ["langchain", "llms", "openai", "OpenAI"]。
to_json ¶
将 Runnable 序列化为 JSON。
| 返回 | 描述 |
|---|---|
SerializedConstructor | SerializedNotImplemented
|
一个 |
to_json_not_implemented ¶
序列化一个“未实现”的对象。
| 返回 | 描述 |
|---|---|
SerializedNotImplemented
|
|
configurable_fields ¶
configurable_fields(
**kwargs: AnyConfigurableField,
) -> RunnableSerializable[Input, Output]
在运行时配置特定的 Runnable 字段。
| 参数 | 描述 |
|---|---|
**kwargs
|
一个要配置的
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果在 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了字段的新 |
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,
)
configurable_alternatives ¶
configurable_alternatives(
which: ConfigurableField,
*,
default_key: str = "default",
prefix_keys: bool = False,
**kwargs: Runnable[Input, Output] | Callable[[], Runnable[Input, Output]],
) -> RunnableSerializable[Input, Output]
为可在运行时设置的 Runnable 对象配置备选项。
| 参数 | 描述 |
|---|---|
哪个
|
将用于选择备选项的
类型: |
默认键
|
如果未选择备选项,则使用的默认键。
类型: |
前缀键
|
是否用
类型: |
**kwargs
|
一个从键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了备选项的新 |
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
)
AmazonKnowledgeBasesRetriever ¶
基类: BaseRetriever
“Amazon Bedrock 知识库”检索。
有关更多信息,请参阅 https://aws.amazon.com/bedrock/knowledge-bases。
| 属性 | 描述 |
|---|---|
knowledge_base_id |
知识库 ID。
类型: |
region_name |
AWS 区域,例如 `'us-west-2'`。回退到 `AWS_REGION`/`AWS_DEFAULT_REGION` 环境变量或 `~/.aws/config` 中指定的区域。
类型: |
credentials_profile_name |
`~/.aws/credentials` 或 `~/.aws/config` 文件中的配置文件名称,其中指定了访问密钥或角色信息。如果未指定,将使用默认的凭证配置文件,或者(如果是在 EC2 实例上)将使用来自 IMDS 的凭证。
类型: |
aws_access_key_id |
AWS 访问密钥 ID。如果提供,还必须提供 `aws_secret_access_key`。如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从 `AWS_ACCESS_KEY_ID` 环境变量中读取。
类型: |
aws_secret_access_key |
AWS `secret_access_key`。如果提供,还必须提供 `aws_access_key_id`。如果未指定,将使用默认凭证配置文件,或者,如果在 EC2 实例上,将使用来自 IMDS 的凭证。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从 `AWS_SECRET_ACCESS_KEY` 环境变量中读取。
类型: |
aws_session_token |
AWS 会话令牌。如果提供,还必须提供 `aws_access_key_id` 和 `aws_secret_access_key`。除非使用临时凭证,否则不需要。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从 `AWS_SESSION_TOKEN` 环境变量中读取。
类型: |
endpoint_url |
如果您不想默认使用 `'us-east-1'` 终端节点,则需要此项。
类型: |
配置 |
一个可选的
类型: |
client |
用于 bedrock agent runtime 的 boto3 客户端。
类型: |
guardrail_config |
您想在请求中使用的护栏的配置信息。 |
retrieval_config |
指定为 Python 对象(RetrievalConfig)或字典的可选检索配置。 |
min_score_confidence |
用于筛选结果的最低分数置信度阈值(0.0 到 1.0)。
类型: |
示例
| 方法 | 描述 |
|---|---|
get_name |
获取 |
get_input_schema |
获取可用于验证 |
get_input_jsonschema |
获取表示 |
get_output_schema |
获取可用于验证 |
get_output_jsonschema |
获取表示 |
config_schema |
此 |
get_config_jsonschema |
获取表示 |
get_graph |
返回此 |
get_prompts |
返回此 |
__or__ |
Runnable "or" 运算符。 |
__ror__ |
Runnable "reverse-or" 运算符。 |
pipe |
管道连接 |
pick |
从此 |
assign |
向此 |
invoke |
调用检索器以获取相关文档。 |
ainvoke |
异步调用检索器以获取相关文档。 |
batch |
默认实现使用线程池执行器并行运行 invoke。 |
batch_as_completed |
在输入列表上并行运行 |
abatch |
默认实现使用 |
abatch_as_completed |
在输入列表上并行运行 |
stream |
|
astream |
|
astream_log |
流式传输 |
astream_events |
生成事件流。 |
transform |
将输入转换为输出。 |
atransform |
将输入转换为输出。 |
bind |
将参数绑定到 |
with_config |
将配置绑定到 |
with_listeners |
将生命周期侦听器绑定到 |
with_alisteners |
将异步生命周期侦听器绑定到 |
with_types |
将输入和输出类型绑定到 |
with_retry |
创建一个新的 |
map |
返回一个新的 |
with_fallbacks |
向 |
as_tool |
从 |
__init__ |
|
is_lc_serializable |
这个类是否可序列化? |
get_lc_namespace |
获取 LangChain 对象的命名空间。 |
lc_id |
为此类返回一个用于序列化目的的唯一标识符。 |
to_json |
将 |
to_json_not_implemented |
序列化一个“未实现”的对象。 |
configurable_fields |
在运行时配置特定的 |
configurable_alternatives |
为可在运行时设置的 |
lc_secrets property ¶
构造函数参数名称到密钥 ID 的映射。
例如,{"openai_api_key": "OPENAI_API_KEY"}
tags class-attribute instance-attribute ¶
与检索器关联的可选标签列表。
这些标签将与对此检索器的每次调用相关联,并作为参数传递给在 callbacks 中定义的处理程序。
您可以使用这些标签来识别特定检索器实例及其用例。
metadata class-attribute instance-attribute ¶
与检索器关联的可选元数据。
此元数据将与对此检索器的每次调用相关联,并作为参数传递给在 callbacks 中定义的处理程序。
您可以使用这些标签来识别特定检索器实例及其用例。
get_name ¶
get_input_schema ¶
get_input_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输入的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输入模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输入模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输入的 Pydantic 模型。 |
get_input_jsonschema ¶
get_input_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输入的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
get_output_schema ¶
get_output_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输出的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输出模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输出模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输出的 Pydantic 模型。 |
get_output_jsonschema ¶
get_output_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输出的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
config_schema ¶
get_config_jsonschema ¶
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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
__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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Other, Output]
|
一个新的 |
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]
| 参数 | 描述 |
|---|---|
*其他
|
其他要组合的 |
name
|
生成的
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
pick ¶
从此 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
|
从输出字典中选择的一个键或键列表。 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
assign ¶
assign(
**kwargs: 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 的 dict 输出分配新字段。
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
|
一个键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
invoke ¶
invoke(
input: str, config: RunnableConfig | None = None, **kwargs: Any
) -> list[Document]
调用检索器以获取相关文档。
同步检索器调用的主入口点。
| 参数 | 描述 |
|---|---|
输入
|
查询字符串。
类型: |
配置
|
检索器的配置。
类型: |
**kwargs
|
要传递给检索器的额外参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
相关文档的列表。 |
示例
ainvoke async ¶
ainvoke(
input: str, config: RunnableConfig | None = None, **kwargs: Any
) -> list[Document]
异步调用检索器以获取相关文档。
异步检索器调用的主入口点。
| 参数 | 描述 |
|---|---|
输入
|
查询字符串。
类型: |
配置
|
检索器的配置。
类型: |
**kwargs
|
要传递给检索器的额外参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
相关文档的列表。 |
示例
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
tuple[int, Output | Exception]
|
由输入索引和 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[tuple[int, Output | Exception]]
|
一个由输入索引和 |
stream ¶
stream(
input: Input, config: RunnableConfig | None = None, **kwargs: Any | None
) -> Iterator[Output]
stream 的默认实现,它调用 invoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
astream async ¶
astream(
input: Input, config: RunnableConfig | None = None, **kwargs: Any | None
) -> AsyncIterator[Output]
astream 的默认实现,它调用 ainvoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
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 操作来构造状态。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
差异
|
是生成每一步之间的差异还是当前状态。
类型: |
带流式输出列表
|
是否生成
类型: |
包含名称
|
仅包含具有这些名称的日志。 |
包含类型
|
仅包含具有这些类型的日志。 |
包含标签
|
仅包含具有这些标签的日志。 |
排除名称
|
排除具有这些名称的日志。 |
排除类型
|
排除具有这些类型的日志。 |
排除标签
|
排除具有这些标签的日志。 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]
|
一个 |
astream_events async ¶
astream_events(
input: Any,
config: RunnableConfig | None = None,
*,
version: Literal["v1", "v2"] = "v2",
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[StreamEvent]
生成事件流。
用于创建一个 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:
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)
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
版本
|
要使用的模式版本,可以是
类型: |
包含名称
|
仅包括来自具有匹配名称的 |
包含类型
|
仅包括来自具有匹配类型的 |
包含标签
|
仅包括来自具有匹配标签的 |
排除名称
|
排除来自具有匹配名称的 |
排除类型
|
排除来自具有匹配类型的 |
排除标签
|
排除来自具有匹配标签的 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[StreamEvent]
|
|
| 引发 | 描述 |
|---|---|
NotImplementedError
|
如果版本不是 |
transform ¶
transform(
input: Iterator[Input], config: RunnableConfig | None = None, **kwargs: Any | None
) -> Iterator[Output]
将输入转换为输出。
transform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
atransform async ¶
atransform(
input: AsyncIterator[Input],
config: RunnableConfig | None = None,
**kwargs: Any | None,
) -> AsyncIterator[Output]
将输入转换为输出。
atransform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
bind ¶
将参数绑定到 Runnable,返回一个新的 Runnable。
当链中的 Runnable 需要一个不在前一个 Runnable 的输出中或未包含在用户输入中的参数时非常有用。
| 参数 | 描述 |
|---|---|
**kwargs
|
要绑定到
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了参数的新 |
示例
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_config ¶
with_config(
config: RunnableConfig | None = None, **kwargs: Any
) -> Runnable[Input, Output]
将配置绑定到 Runnable,返回一个新的 Runnable。
| 参数 | 描述 |
|---|---|
配置
|
要绑定到
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了配置的新 |
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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_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。
| 参数 | 描述 |
|---|---|
如果异常类型则重试
|
一个用于重试的异常类型元组。
类型: |
指数等待抖动
|
是否在两次重试之间的等待时间中添加抖动。
类型: |
尝试后停止
|
放弃前尝试的最大次数。
类型: |
指数抖动参数
|
类型: |
| 返回 | 描述 |
|---|---|
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 ¶
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,然后按顺序尝试每个备选方案。
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
示例
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
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
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 来仅指定必需的参数及其类型。
| 参数 | 描述 |
|---|---|
参数模式
|
工具的模式。 |
name
|
工具的名称。
类型: |
描述
|
工具的描述。
类型: |
参数类型
|
一个从参数名称到类型的字典。 |
| 返回 | 描述 |
|---|---|
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]})
字符串输入
is_lc_serializable classmethod ¶
is_lc_serializable() -> bool
这个类是否可序列化?
根据设计,即使一个类继承自 Serializable,它默认也是不可序列化的。这是为了防止意外序列化不应被序列化的对象。
| 返回 | 描述 |
|---|---|
bool
|
类是否可序列化。默认为 |
get_lc_namespace classmethod ¶
lc_id classmethod ¶
为此类返回一个用于序列化目的的唯一标识符。
唯一标识符是一个描述对象路径的字符串列表。
例如,对于类 langchain.llms.openai.OpenAI,id 是 ["langchain", "llms", "openai", "OpenAI"]。
to_json ¶
将 Runnable 序列化为 JSON。
| 返回 | 描述 |
|---|---|
SerializedConstructor | SerializedNotImplemented
|
一个 |
to_json_not_implemented ¶
序列化一个“未实现”的对象。
| 返回 | 描述 |
|---|---|
SerializedNotImplemented
|
|
configurable_fields ¶
configurable_fields(
**kwargs: AnyConfigurableField,
) -> RunnableSerializable[Input, Output]
在运行时配置特定的 Runnable 字段。
| 参数 | 描述 |
|---|---|
**kwargs
|
一个要配置的
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果在 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了字段的新 |
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,
)
configurable_alternatives ¶
configurable_alternatives(
which: ConfigurableField,
*,
default_key: str = "default",
prefix_keys: bool = False,
**kwargs: Runnable[Input, Output] | Callable[[], Runnable[Input, Output]],
) -> RunnableSerializable[Input, Output]
为可在运行时设置的 Runnable 对象配置备选项。
| 参数 | 描述 |
|---|---|
哪个
|
将用于选择备选项的
类型: |
默认键
|
如果未选择备选项,则使用的默认键。
类型: |
前缀键
|
是否用
类型: |
**kwargs
|
一个从键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了备选项的新 |
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
)
AmazonS3VectorsRetriever ¶
AmazonS3VectorsRetriever 是一个用于 Amazon S3 Vectors 的检索器。
示例
from langchain_aws.vectorstores import AmazonS3Vectors
vector_store = AmazonS3Vectors(...)
retriever = vector_store.as_retriever()
| 方法 | 描述 |
|---|---|
get_name |
获取 |
get_input_schema |
获取可用于验证 |
get_input_jsonschema |
获取表示 |
get_output_schema |
获取可用于验证 |
get_output_jsonschema |
获取表示 |
config_schema |
此 |
get_config_jsonschema |
获取表示 |
get_graph |
返回此 |
get_prompts |
返回此 |
__or__ |
Runnable "or" 运算符。 |
__ror__ |
Runnable "reverse-or" 运算符。 |
pipe |
管道连接 |
pick |
从此 |
assign |
向此 |
invoke |
调用检索器以获取相关文档。 |
ainvoke |
异步调用检索器以获取相关文档。 |
batch |
默认实现使用线程池执行器并行运行 invoke。 |
batch_as_completed |
在输入列表上并行运行 |
abatch |
默认实现使用 |
abatch_as_completed |
在输入列表上并行运行 |
stream |
|
astream |
|
astream_log |
流式传输 |
astream_events |
生成事件流。 |
transform |
将输入转换为输出。 |
atransform |
将输入转换为输出。 |
bind |
将参数绑定到 |
with_config |
将配置绑定到 |
with_listeners |
将生命周期侦听器绑定到 |
with_alisteners |
将异步生命周期侦听器绑定到 |
with_types |
将输入和输出类型绑定到 |
with_retry |
创建一个新的 |
map |
返回一个新的 |
with_fallbacks |
向 |
as_tool |
从 |
__init__ |
|
is_lc_serializable |
这个类是否可序列化? |
get_lc_namespace |
获取 LangChain 对象的命名空间。 |
lc_id |
为此类返回一个用于序列化目的的唯一标识符。 |
to_json |
将 |
to_json_not_implemented |
序列化一个“未实现”的对象。 |
configurable_fields |
在运行时配置特定的 |
configurable_alternatives |
为可在运行时设置的 |
validate_search_type |
验证搜索类型。 |
add_documents |
将文档添加到 |
aadd_documents |
异步地将文档添加到 |
lc_secrets property ¶
构造函数参数名称到密钥 ID 的映射。
例如,{"openai_api_key": "OPENAI_API_KEY"}
tags class-attribute instance-attribute ¶
与检索器关联的可选标签列表。
这些标签将与对此检索器的每次调用相关联,并作为参数传递给在 callbacks 中定义的处理程序。
您可以使用这些标签来识别特定检索器实例及其用例。
metadata class-attribute instance-attribute ¶
与检索器关联的可选元数据。
此元数据将与对此检索器的每次调用相关联,并作为参数传递给在 callbacks 中定义的处理程序。
您可以使用这些标签来识别特定检索器实例及其用例。
search_kwargs class-attribute instance-attribute ¶
传递给搜索函数的关键字参数。
get_name ¶
get_input_schema ¶
get_input_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输入的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输入模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输入模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输入的 Pydantic 模型。 |
get_input_jsonschema ¶
get_input_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输入的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
get_output_schema ¶
get_output_schema(config: RunnableConfig | None = None) -> type[BaseModel]
获取可用于验证 Runnable 输出的 Pydantic 模型。
利用 configurable_fields 和 configurable_alternatives 方法的 Runnable 对象将具有一个动态输出模式,该模式取决于调用 Runnable 时使用的配置。
此方法允许获取特定配置的输出模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
type[BaseModel]
|
一个可用于验证输出的 Pydantic 模型。 |
get_output_jsonschema ¶
get_output_jsonschema(config: RunnableConfig | None = None) -> dict[str, Any]
获取表示 Runnable 输出的 JSON 模式。
| 参数 | 描述 |
|---|---|
配置
|
生成模式时使用的配置。
类型: |
| 返回 | 描述 |
|---|---|
dict[str, Any]
|
表示 |
示例
在 0.3.0 版本中新增。
config_schema ¶
get_config_jsonschema ¶
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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
__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
|
另一个
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Other, Output]
|
一个新的 |
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]
| 参数 | 描述 |
|---|---|
*其他
|
其他要组合的 |
name
|
生成的
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Other]
|
一个新的 |
pick ¶
从此 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
|
从输出字典中选择的一个键或键列表。 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
assign ¶
assign(
**kwargs: 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 的 dict 输出分配新字段。
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
|
一个键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Any, Any]
|
一个新的 |
invoke ¶
invoke(
input: str, config: RunnableConfig | None = None, **kwargs: Any
) -> list[Document]
调用检索器以获取相关文档。
同步检索器调用的主入口点。
| 参数 | 描述 |
|---|---|
输入
|
查询字符串。
类型: |
配置
|
检索器的配置。
类型: |
**kwargs
|
要传递给检索器的额外参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
相关文档的列表。 |
示例
ainvoke async ¶
ainvoke(
input: str, config: RunnableConfig | None = None, **kwargs: Any
) -> list[Document]
异步调用检索器以获取相关文档。
异步检索器调用的主入口点。
| 参数 | 描述 |
|---|---|
输入
|
查询字符串。
类型: |
配置
|
检索器的配置。
类型: |
**kwargs
|
要传递给检索器的额外参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
相关文档的列表。 |
示例
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
tuple[int, Output | Exception]
|
由输入索引和 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
list[Output]
|
来自 |
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
|
类型: |
配置
|
调用
类型: |
返回异常
|
是否返回异常而不是引发它们。
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[tuple[int, Output | Exception]]
|
一个由输入索引和 |
stream ¶
stream(
input: Input, config: RunnableConfig | None = None, **kwargs: Any | None
) -> Iterator[Output]
stream 的默认实现,它调用 invoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
astream async ¶
astream(
input: Input, config: RunnableConfig | None = None, **kwargs: Any | None
) -> AsyncIterator[Output]
astream 的默认实现,它调用 ainvoke。
如果子类支持流式输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
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 操作来构造状态。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
差异
|
是生成每一步之间的差异还是当前状态。
类型: |
带流式输出列表
|
是否生成
类型: |
包含名称
|
仅包含具有这些名称的日志。 |
包含类型
|
仅包含具有这些类型的日志。 |
包含标签
|
仅包含具有这些标签的日志。 |
排除名称
|
排除具有这些名称的日志。 |
排除类型
|
排除具有这些类型的日志。 |
排除标签
|
排除具有这些标签的日志。 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]
|
一个 |
astream_events async ¶
astream_events(
input: Any,
config: RunnableConfig | None = None,
*,
version: Literal["v1", "v2"] = "v2",
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[StreamEvent]
生成事件流。
用于创建一个 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:
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)
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
版本
|
要使用的模式版本,可以是
类型: |
包含名称
|
仅包括来自具有匹配名称的 |
包含类型
|
仅包括来自具有匹配类型的 |
包含标签
|
仅包括来自具有匹配标签的 |
排除名称
|
排除来自具有匹配名称的 |
排除类型
|
排除来自具有匹配类型的 |
排除标签
|
排除来自具有匹配标签的 |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[StreamEvent]
|
|
| 引发 | 描述 |
|---|---|
NotImplementedError
|
如果版本不是 |
transform ¶
transform(
input: Iterator[Input], config: RunnableConfig | None = None, **kwargs: Any | None
) -> Iterator[Output]
将输入转换为输出。
transform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
输出
|
|
atransform async ¶
atransform(
input: AsyncIterator[Input],
config: RunnableConfig | None = None,
**kwargs: Any | None,
) -> AsyncIterator[Output]
将输入转换为输出。
atransform 的默认实现,它缓冲输入并调用 astream。
如果子类可以在输入仍在生成时开始产生输出,则必须重写此方法。
| 参数 | 描述 |
|---|---|
输入
|
类型: |
配置
|
用于
类型: |
**kwargs
|
要传递给
类型: |
| YIELDS | 描述 |
|---|---|
AsyncIterator[Output]
|
|
bind ¶
将参数绑定到 Runnable,返回一个新的 Runnable。
当链中的 Runnable 需要一个不在前一个 Runnable 的输出中或未包含在用户输入中的参数时非常有用。
| 参数 | 描述 |
|---|---|
**kwargs
|
要绑定到
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了参数的新 |
示例
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_config ¶
with_config(
config: RunnableConfig | None = None, **kwargs: Any
) -> Runnable[Input, Output]
将配置绑定到 Runnable,返回一个新的 Runnable。
| 参数 | 描述 |
|---|---|
配置
|
要绑定到
类型: |
**kwargs
|
要传递给
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了配置的新 |
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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 对象包含有关运行的信息,包括其 id、type、input、output、error、start_time、end_time 以及添加到运行中的任何标签或元数据。
| 参数 | 描述 |
|---|---|
开始时
|
在
类型: |
结束时
|
在
类型: |
出错时
|
如果
类型: |
| 返回 | 描述 |
|---|---|
Runnable[Input, Output]
|
一个绑定了监听器的新 |
示例
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_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。
| 参数 | 描述 |
|---|---|
如果异常类型则重试
|
一个用于重试的异常类型元组。
类型: |
指数等待抖动
|
是否在两次重试之间的等待时间中添加抖动。
类型: |
尝试后停止
|
放弃前尝试的最大次数。
类型: |
指数抖动参数
|
类型: |
| 返回 | 描述 |
|---|---|
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 ¶
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,然后按顺序尝试每个备选方案。
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
示例
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
| 参数 | 描述 |
|---|---|
备用方案
|
如果原始 |
要处理的异常
|
一个要处理的异常类型元组。
类型: |
异常键
|
如果指定了
类型: |
| 返回 | 描述 |
|---|---|
RunnableWithFallbacks[Input, Output]
|
一个新的 |
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 来仅指定必需的参数及其类型。
| 参数 | 描述 |
|---|---|
参数模式
|
工具的模式。 |
name
|
工具的名称。
类型: |
描述
|
工具的描述。
类型: |
参数类型
|
一个从参数名称到类型的字典。 |
| 返回 | 描述 |
|---|---|
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]})
字符串输入
is_lc_serializable classmethod ¶
is_lc_serializable() -> bool
这个类是否可序列化?
根据设计,即使一个类继承自 Serializable,它默认也是不可序列化的。这是为了防止意外序列化不应被序列化的对象。
| 返回 | 描述 |
|---|---|
bool
|
类是否可序列化。默认为 |
get_lc_namespace classmethod ¶
lc_id classmethod ¶
为此类返回一个用于序列化目的的唯一标识符。
唯一标识符是一个描述对象路径的字符串列表。
例如,对于类 langchain.llms.openai.OpenAI,id 是 ["langchain", "llms", "openai", "OpenAI"]。
to_json ¶
将 Runnable 序列化为 JSON。
| 返回 | 描述 |
|---|---|
SerializedConstructor | SerializedNotImplemented
|
一个 |
to_json_not_implemented ¶
序列化一个“未实现”的对象。
| 返回 | 描述 |
|---|---|
SerializedNotImplemented
|
|
configurable_fields ¶
configurable_fields(
**kwargs: AnyConfigurableField,
) -> RunnableSerializable[Input, Output]
在运行时配置特定的 Runnable 字段。
| 参数 | 描述 |
|---|---|
**kwargs
|
一个要配置的
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果在 |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了字段的新 |
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,
)
configurable_alternatives ¶
configurable_alternatives(
which: ConfigurableField,
*,
default_key: str = "default",
prefix_keys: bool = False,
**kwargs: Runnable[Input, Output] | Callable[[], Runnable[Input, Output]],
) -> RunnableSerializable[Input, Output]
为可在运行时设置的 Runnable 对象配置备选项。
| 参数 | 描述 |
|---|---|
哪个
|
将用于选择备选项的
类型: |
默认键
|
如果未选择备选项,则使用的默认键。
类型: |
前缀键
|
是否用
类型: |
**kwargs
|
一个从键到
类型: |
| 返回 | 描述 |
|---|---|
RunnableSerializable[Input, Output]
|
一个配置了备选项的新 |
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
)
validate_search_type classmethod ¶
验证搜索类型。
| 参数 | 描述 |
|---|---|
values
|
待验证的值。
类型: |
| 返回 | 描述 |
|---|---|
任意
|
已验证的值。 |
| 引发 | 描述 |
|---|---|
ValueError
|
如果 |
ValueError
|
如果 |
add_documents ¶
InMemorySemanticCache ¶
基类:BaseCache
使用 MemoryDB 作为向量存储后端的缓存。
| 方法 | 描述 |
|---|---|
alookup |
基于 `prompt` 和 `llm_string` 进行异步查找。 |
aupdate |
基于 `prompt` 和 `llm_string` 异步更新缓存。 |
aclear |
异步清除缓存,可以接受额外的关键字参数。 |
__init__ |
通过传递 |
clear |
为给定的 llm_string 清除语义缓存。 |
lookup |
根据 prompt 和 llm_string 进行查找。 |
更新 |
根据 prompt 和 llm_string 更新缓存。 |
alookup async ¶
基于 `prompt` 和 `llm_string` 进行异步查找。
期望缓存实现从 `prompt` 和 `llm_string` 的 2 元组生成一个键(例如,通过用分隔符连接它们)。
| 参数 | 描述 |
|---|---|
prompt
|
提示的字符串表示。在聊天模型的情况下,提示是对语言模型提示的非平凡序列化。
类型: |
llm_string
|
LLM 配置的字符串表示。 这用于捕获 LLM 的调用参数(例如,模型名称、温度、停止标记、最大标记等)。 这些调用参数被序列化为字符串表示。
类型: |
| 返回 | 描述 |
|---|---|
RETURN_VAL_TYPE | None
|
缓存未命中时,返回 `None`。缓存命中时,返回缓存的值。 |
RETURN_VAL_TYPE | None
|
缓存的值是 `Generation`(或其子类)的列表。 |
aupdate async ¶
__init__ ¶
__init__(redis_url: str, embedding: Embeddings, score_threshold: float = 0.2)
通过传递 init GPTCache 函数进行初始化。
| 参数 | 描述 |
|---|---|
redis_url
|
用于连接 MemoryDB 的 URL。
类型: |
embedding
|
用于语义编码和搜索的嵌入提供程序。
类型: |
score_threshold
|
类型: |
示例:```python from langchain_core.globals import set_llm_cache
from langchain_aws.cache import InMemorySemanticCache
set_llm_cache(InMemorySemanticCache(
redis_url="redis://:6379",
embedding=OpenAIEmbeddings()
))
```
lookup ¶
根据 prompt 和 llm_string 进行查找。
InMemoryVectorStore ¶
Bases: VectorStore
InMemoryVectorStore 向量数据库。
要使用它,您应该为 AWS MemoryDB 安装 redis python 包
```bash
pip install redis
```
运行后,您可以使用以下 url 模式连接到 MemoryDB 服务器: - redis://
示例
以下示例展示了在 LangChain 中使用 Redis VectorStore 的各种方式。
初始化、创建索引并加载文档
from langchain_aws.vectorstores import InMemoryVectorStore
rds = InMemoryVectorStore.from_documents(
documents, # a list of Document objects from loaders or created
embeddings, # an Embeddings object
redis_url="redis://cluster_endpoint:6379",
)
初始化、创建索引并加载带元数据的文档
rds = InMemoryVectorStore.from_texts(
texts, # a list of strings
metadata, # a list of metadata dicts
embeddings, # an Embeddings object
redis_url="redis://cluster_endpoint:6379",
)
初始化、创建索引、加载带元数据的文档并返回键
```python
rds, keys = InMemoryVectorStore.from_texts_return_keys(
texts, # a list of strings
metadata, # a list of metadata dicts
embeddings, # an Embeddings object
redis_url="redis://cluster_endpoint:6379",
)
```
对于需要保持索引活动状态的用例,您可以使用索引名称进行初始化,以便以后更容易引用
```python
rds = InMemoryVectorStore.from_texts(
texts, # a list of strings
metadata, # a list of metadata dicts
embeddings, # an Embeddings object
index_name="my-index",
redis_url="redis://cluster_endpoint:6379",
)
```
初始化并连接到现有索引(来自上方)
```python
# must pass in schema and key_prefix from another index
existing_rds = InMemoryVectorStore.from_existing_index(
embeddings, # an Embeddings object
index_name="my-index",
schema=rds.schema, # schema dumped from another index
key_prefix=rds.key_prefix, # key prefix from another index
redis_url="redis://username:password@cluster_endpoint:6379",
)
```
高级示例
可以提供自定义向量模式来更改 MemoryDB 创建底层向量模式的方式。这对于您希望优化用例的向量模式的生产用例非常有用。例如,使用 HNSW 而非默认的 FLAT (knn)。
```python
vector_schema = {
"algorithm": "HNSW"
}
rds = InMemoryVectorStore.from_texts(
texts, # a list of strings
metadata, # a list of metadata dicts
embeddings, # an Embeddings object
vector_schema=vector_schema,
redis_url="redis://cluster_endpoint:6379",
)
```
可以提供自定义索引模式来更改元数据的索引方式。这对于您希望使用 MemoryDB 的混合查询(过滤)功能非常有用。
默认情况下,此实现将根据以下规则自动生成索引模式: - 所有字符串都索引为文本字段 - 所有数字都索引为数字字段 - 所有字符串列表都索引为标签字段(由 langchain_aws.vectorstores.inmemorydb.constants.INMEMORYDB_TAG_SEPARATOR 连接) - 所有 None 值不被索引但仍存储在 MemoryDB 中,这些值无法通过此接口检索,但可以使用原始 MemoryDB 客户端检索它们。 - 所有其他类型不被索引
要覆盖这些规则,您可以传入自定义索引模式,如下所示
```yaml
tag:
- name: credit_score
text:
- name: user
- name: job
```
通常,credit_score 字段会是一个文本字段,因为它是一个字符串,但是,我们可以通过指定字段类型来覆盖此行为,如上面的 yaml 配置(也可以是字典)和下面的代码所示。
```python
rds = InMemoryVectorStore.from_texts(
texts, # a list of strings
metadata, # a list of metadata dicts
embeddings, # an Embeddings object
index_schema="path/to/index_schema.yaml", # can also be a dictionary
redis_url="redis://cluster_endpoint:6379",
)
```
连接到已应用自定义模式的现有索引时,将相同的模式传递给 from_existing_index 方法非常重要。否则,新添加样本的模式将不正确,并且不会返回元数据。
| 方法 | 描述 |
|---|---|
get_by_ids |
根据 ID 获取文档。 |
aget_by_ids |
通过 ID 异步获取文档。 |
adelete |
按向量 ID 或其他条件异步删除。 |
aadd_texts |
通过嵌入异步运行更多文本并添加到 `VectorStore`。 |
add_documents |
在 `VectorStore` 中添加或更新文档。 |
aadd_documents |
异步运行更多文档通过嵌入并添加到 `VectorStore`。 |
search |
使用指定的搜索类型返回与查询最相似的文档。 |
asearch |
异步返回与查询最相似的文档,使用指定的搜索类型。 |
asimilarity_search_with_score |
异步运行带距离的相似性搜索。 |
similarity_search_with_relevance_scores |
返回文档和在 `[0, 1]` 范围内的相关性分数。 |
asimilarity_search_with_relevance_scores |
异步返回文档和在 `[0, 1]` 范围内的相关性分数。 |
asimilarity_search |
异步返回与查询最相似的文档。 |
asimilarity_search_by_vector |
异步返回与嵌入向量最相似的文档。 |
amax_marginal_relevance_search |
异步返回使用最大边际相关性选择的文档。 |
max_marginal_relevance_search_by_vector |
返回使用最大边际相关性选择的文档。 |
amax_marginal_relevance_search_by_vector |
异步返回使用最大边际相关性选择的文档。 |
from_documents |
返回从文档和嵌入初始化的 `VectorStore`。 |
afrom_documents |
异步返回从文档和嵌入初始化的 `VectorStore`。 |
afrom_texts |
异步返回从文本和嵌入初始化的 `VectorStore`。 |
__init__ |
使用必要组件初始化 MemoryDB 向量存储。 |
from_texts_return_keys |
从原始文档创建 InMemoryVectorStore 向量存储。 |
from_texts |
从文本列表创建 InMemoryVectorStore 向量存储。 |
from_existing_index |
连接到现有的 InMemoryVectorStore 索引。 |
write_schema |
将模式写入 yaml 文件。 |
delete |
删除一个 InMemoryVectorStore 条目。 |
drop_index |
删除 InMemoryVectorStore 搜索索引。 |
add_texts |
向 |
as_retriever |
返回从此 `VectorStore` 初始化的 `VectorStoreRetriever`。 |
similarity_search_with_score |
使用向量距离运行相似性搜索。 |
similarity_search |
运行相似性搜索 |
similarity_search_by_vector |
在查询向量和索引向量之间运行相似性搜索。 |
max_marginal_relevance_search |
返回使用最大边际相关性选择的文档。 |
get_by_ids ¶
aget_by_ids async ¶
adelete async ¶
aadd_texts async ¶
aadd_texts(
texts: Iterable[str],
metadatas: list[dict] | None = None,
*,
ids: list[str] | None = None,
**kwargs: Any,
) -> list[str]
通过嵌入异步运行更多文本并添加到 `VectorStore`。
| 参数 | 描述 |
|---|---|
texts
|
要添加到 `VectorStore` 的字符串的可迭代对象。 |
metadatas
|
与文本关联的元数据可选列表。 |
ids
|
可选列表 |
**kwargs
|
`VectorStore` 特定参数。
类型: |
| 返回 | 描述 |
|---|---|
list[str]
|
将文本添加到 `VectorStore` 后返回的 ID 列表。 |
| 引发 | 描述 |
|---|---|
ValueError
|
如果元数据的数量与文本的数量不匹配。 |
ValueError
|
如果 ID 的数量与文本的数量不匹配。 |
add_documents ¶
aadd_documents async ¶
search ¶
使用指定的搜索类型返回与查询最相似的文档。
| 参数 | 描述 |
|---|---|
query
|
输入文本。
类型: |
search_type
|
要执行的搜索类型。可以是 `'similarity'`、`'mmr'` 或 `'similarity_score_threshold'`。
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
与查询最相似的 `Document` 对象列表。 |
| 引发 | 描述 |
|---|---|
ValueError
|
如果 `search_type` 不是 `'similarity'`、`'mmr'` 或 `'similarity_score_threshold'` 之一。 |
asearch async ¶
异步返回与查询最相似的文档,使用指定的搜索类型。
| 参数 | 描述 |
|---|---|
query
|
输入文本。
类型: |
search_type
|
要执行的搜索类型。可以是 `'similarity'`、`'mmr'` 或 `'similarity_score_threshold'`。
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
与查询最相似的 `Document` 对象列表。 |
| 引发 | 描述 |
|---|---|
ValueError
|
如果 `search_type` 不是 `'similarity'`、`'mmr'` 或 `'similarity_score_threshold'` 之一。 |
asimilarity_search_with_score async ¶
similarity_search_with_relevance_scores ¶
asimilarity_search_with_relevance_scores async ¶
asimilarity_search async ¶
asimilarity_search_by_vector async ¶
amax_marginal_relevance_search async ¶
amax_marginal_relevance_search(
query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any
) -> list[Document]
异步返回使用最大边际相关性选择的文档。
最大边际相关性优化查询相似度与所选文档之间的多样性。
| 参数 | 描述 |
|---|---|
query
|
用于查找相似文档的文本。
类型: |
k
|
要返回的 `Document` 对象数量。
TYPE: |
fetch_k
|
要获取并传递给 MMR 算法的 `Document` 对象数量。
类型: |
lambda_mult
|
一个介于 `0` 和 `1` 之间的数字,决定了结果之间的多样性程度,其中 `0` 对应最大多样性,`1` 对应最小多样性。
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
通过最大边际相关性选择的 `Document` 对象列表。 |
max_marginal_relevance_search_by_vector ¶
max_marginal_relevance_search_by_vector(
embedding: list[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> list[Document]
返回使用最大边际相关性选择的文档。
最大边际相关性优化查询相似度与所选文档之间的多样性。
| 参数 | 描述 |
|---|---|
embedding
|
用于查找相似文档的嵌入。 |
k
|
要返回的 `Document` 对象数量。
TYPE: |
fetch_k
|
要获取并传递给 MMR 算法的 `Document` 对象数量。
类型: |
lambda_mult
|
一个介于 `0` 和 `1` 之间的数字,决定了结果之间的多样性程度,其中 `0` 对应最大多样性,`1` 对应最小多样性。
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
通过最大边际相关性选择的 `Document` 对象列表。 |
amax_marginal_relevance_search_by_vector async ¶
amax_marginal_relevance_search_by_vector(
embedding: list[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> list[Document]
异步返回使用最大边际相关性选择的文档。
最大边际相关性优化查询相似度与所选文档之间的多样性。
| 参数 | 描述 |
|---|---|
embedding
|
用于查找相似文档的嵌入。 |
k
|
要返回的 `Document` 对象数量。
TYPE: |
fetch_k
|
要获取并传递给 MMR 算法的 `Document` 对象数量。
类型: |
lambda_mult
|
一个介于 `0` 和 `1` 之间的数字,决定了结果之间的多样性程度,其中 `0` 对应最大多样性,`1` 对应最小多样性。
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
通过最大边际相关性选择的 `Document` 对象列表。 |
from_documents classmethod ¶
from_documents(documents: list[Document], embedding: Embeddings, **kwargs: Any) -> Self
返回从文档和嵌入初始化的 `VectorStore`。
| 参数 | 描述 |
|---|---|
documents
|
要添加到 `VectorStore` 的 `Document` 对象列表。 |
embedding
|
要使用的嵌入函数。
TYPE: |
**kwargs
|
附加的关键字参数。
类型: |
| 返回 | 描述 |
|---|---|
Self
|
从文档和嵌入初始化的 `VectorStore`。 |
afrom_documents async classmethod ¶
afrom_documents(
documents: list[Document], embedding: Embeddings, **kwargs: Any
) -> Self
异步返回从文档和嵌入初始化的 `VectorStore`。
| 参数 | 描述 |
|---|---|
documents
|
要添加到 `VectorStore` 的 `Document` 对象列表。 |
embedding
|
要使用的嵌入函数。
TYPE: |
**kwargs
|
附加的关键字参数。
类型: |
| 返回 | 描述 |
|---|---|
Self
|
从文档和嵌入初始化的 `VectorStore`。 |
afrom_texts async classmethod ¶
__init__ ¶
__init__(
redis_url: str,
index_name: str,
embedding: Embeddings,
index_schema: dict[str, ListOfDict] | str | PathLike | None = None,
vector_schema: dict[str, str | int] | None = None,
relevance_score_fn: Callable[[float], float] | None = None,
key_prefix: str | None = None,
**kwargs: Any,
)
使用必要组件初始化 MemoryDB 向量存储。
from_texts_return_keys classmethod ¶
from_texts_return_keys(
texts: list[str],
embedding: Embeddings,
metadatas: list[dict] | None = None,
index_name: str | None = None,
index_schema: dict[str, ListOfDict] | str | PathLike | None = None,
vector_schema: dict[str, str | int] | None = None,
**kwargs: Any,
) -> tuple[InMemoryVectorStore, list[str]]
从原始文档创建 InMemoryVectorStore 向量存储。
这是一个用户友好的界面,可以
- 嵌入文档。
- 如果 InMemoryVectorStore 索引不存在,则创建一个新的索引
- 将文档添加到新创建的 InMemoryVectorStore 索引中。
- 返回新创建文档存储后的键。
如果未定义 index_schema,此方法将根据传入的元数据生成模式。如果定义了 index_schema,它将与生成的模式进行比较,并在存在差异时发出警告。如果您有意为元数据定义模式,则可以忽略该警告。
要检查模式选项,请初始化此类的实例并使用 `InMemoryVectorStore.schema` 属性打印出模式。这将包括内容和 content_vector 类,它们始终存在于 langchain 模式中。
示例
| 参数 | 描述 |
|---|---|
texts
|
要添加到 |
embedding
|
用于
TYPE: |
metadatas
|
要添加到 |
index_name
|
要创建或添加到的索引的可选名称。
类型: |
index_schema
|
元数据中要索引的可选字段。覆盖生成的模式。 |
vector_schema
|
要使用的可选向量模式。 |
**kwargs
|
要传递给 Redis 客户端的附加关键字参数。
类型: |
| 返回 | 描述 |
|---|---|
tuple[InMemoryVectorStore, list[str]]
|
Tuple[InMemoryVectorStore, List[str]]:InMemoryVectorStore 实例和新创建文档键的元组。 |
| 引发 | 描述 |
|---|---|
ValueError
|
如果元数据的数量与文本的数量不匹配。 |
from_texts classmethod ¶
from_texts(
texts: list[str],
embedding: Embeddings,
metadatas: list[dict] | None = None,
index_name: str | None = None,
index_schema: dict[str, ListOfDict] | str | PathLike | None = None,
vector_schema: dict[str, str | int] | None = None,
**kwargs: Any,
) -> InMemoryVectorStore
从文本列表创建 InMemoryVectorStore 向量存储。
这是一个用户友好的界面,可以
- 嵌入文档。
- 如果 InMemoryVectorStore 索引不存在,则创建一个新的索引
- 将文档添加到新创建的 InMemoryVectorStore 索引中。
如果未定义 index_schema,此方法将根据传入的元数据生成模式。如果定义了 index_schema,它将与生成的模式进行比较,并在存在差异时发出警告。如果您有意为元数据定义模式,则可以忽略该警告。
要检查模式选项,请初始化此类的实例并使用 `InMemoryVectorStore.schema` 属性打印出模式。这将包括内容和 content_vector 类,它们始终存在于 langchain 模式中。
| 参数 | 描述 |
|---|---|
texts
|
要添加到 |
embedding
|
用于嵌入查询的嵌入模型类(例如 OpenAIEmbeddings)。
TYPE: |
metadatas
|
要添加到 |
index_name
|
要创建或添加到的索引的可选名称。
类型: |
index_schema
|
元数据中要索引的可选字段。覆盖生成的模式。 |
vector_schema
|
要使用的可选向量模式。 |
**kwargs
|
要传递给 InMemoryVectorStore 客户端的附加关键字参数。
类型: |
| 返回 | 描述 |
|---|---|
InMemoryVectorStore
|
InMemoryVectorStore VectorStore 实例。 |
| 引发 | 描述 |
|---|---|
ValueError
|
如果元数据的数量与文本的数量不匹配。 |
ImportError
|
如果未安装 redis python 包。 |
from_existing_index classmethod ¶
from_existing_index(
embedding: Embeddings,
index_name: str,
schema: dict[str, ListOfDict] | str | PathLike | dict[str, ListOfDict],
key_prefix: str | None = None,
**kwargs: Any,
) -> InMemoryVectorStore
连接到现有的 InMemoryVectorStore 索引。
示例
from langchain_aws.vectorstores import InMemoryVectorStore
embeddings = OpenAIEmbeddings()
# must pass in schema and key_prefix from another index
existing_rds = InMemoryVectorStore.from_existing_index(
embeddings,
index_name="my-index",
schema=rds.schema, # schema dumped from another index
key_prefix=rds.key_prefix, # key prefix from another index
redis_url="redis://username:password@cluster_endpoint:6379",
)
| 参数 | 描述 |
|---|---|
embedding
|
用于嵌入查询的嵌入模型类(例如 OpenAIEmbeddings)。
TYPE: |
index_name
|
要连接的索引的名称。
类型: |
模式
|
索引的模式和向量模式。可以是字典,或 yaml 文件的路径。 |
key_prefix
|
与此索引关联的 InMemoryVectorStore 中所有键的前缀。
类型: |
**kwargs
|
要传递给 Redis 客户端的附加关键字参数。
类型: |
| 返回 | 描述 |
|---|---|
InMemoryVectorStore
|
InMemoryVectorStore VectorStore 实例。 |
| 引发 | 描述 |
|---|---|
ValueError
|
如果索引不存在。 |
ImportError
|
如果未安装 redis python 包。 |
delete staticmethod ¶
删除一个 InMemoryVectorStore 条目。
| 参数 | 描述 |
|---|---|
ids
|
要删除的 ID 列表(redis 中的键)。 |
**kwargs
|
附加关键字参数。支持
类型: |
| 返回 | 描述 |
|---|---|
bool
|
删除是否成功。
类型: |
| 引发 | 描述 |
|---|---|
ValueError
|
如果未安装 redis python 包。 |
ValueError
|
如果未提供 ID(redis 中的键)。 |
drop_index staticmethod ¶
add_texts ¶
add_texts(
texts: Iterable[str],
metadatas: list[dict] | None = None,
embeddings: list[list[float]] | None = None,
batch_size: int = 1000,
clean_metadata: bool = True,
**kwargs: Any,
) -> list[str]
as_retriever ¶
as_retriever(**kwargs: Any) -> InMemoryVectorStoreRetriever
返回从此 `VectorStore` 初始化的 `VectorStoreRetriever`。
| 参数 | 描述 |
|---|---|
**kwargs
|
传递给搜索函数的关键字参数。可以包括
类型: |
| 返回 | 描述 |
|---|---|
VectorStoreRetriever
|
`VectorStore` 的检索器类。 |
示例
# Retrieve more documents with higher diversity
# Useful if your dataset has many similar documents
docsearch.as_retriever(
search_type="mmr", search_kwargs={"k": 6, "lambda_mult": 0.25}
)
# Fetch more documents for the MMR algorithm to consider
# But only return the top 5
docsearch.as_retriever(search_type="mmr", search_kwargs={"k": 5, "fetch_k": 50})
# Only retrieve documents that have a relevance score
# Above a certain threshold
docsearch.as_retriever(
search_type="similarity_score_threshold",
search_kwargs={"score_threshold": 0.8},
)
# Only get the single most similar document from the dataset
docsearch.as_retriever(search_kwargs={"k": 1})
# Use a filter to only retrieve documents from a specific paper
docsearch.as_retriever(
search_kwargs={"filter": {"paper_title": "GPT-4 Technical Report"}}
)
similarity_search_with_score ¶
similarity_search_with_score(
query: str,
k: int = 4,
filter: InMemoryDBFilterExpression | None = None,
return_metadata: bool = True,
**kwargs: Any,
) -> list[tuple[Document, float]]
使用向量距离运行相似性搜索。
此函数返回的“分数”是与查询向量的原始向量距离。对于相似度分数,请使用 similarity_search_with_relevance_scores。
| 参数 | 描述 |
|---|---|
query
|
要查找相似文档的查询文本。
类型: |
k
|
要返回的文档数。默认为 4。
TYPE: |
filter
|
可选的元数据过滤器。
类型: |
return_metadata
|
是否返回元数据。
类型: |
| 返回 | 描述 |
|---|---|
list[tuple[Document, float]]
|
List[Tuple[Document, float]]: 与查询最相似的文档列表,以及每个文档的距离。 |
similarity_search ¶
similarity_search(
query: str,
k: int = 4,
filter: InMemoryDBFilterExpression | None = None,
return_metadata: bool = True,
distance_threshold: float | None = None,
**kwargs: Any,
) -> list[Document]
运行相似性搜索
| 参数 | 描述 |
|---|---|
query
|
要查找相似文档的查询文本。
类型: |
k
|
要返回的文档数。默认为 4。
TYPE: |
filter
|
可选的元数据过滤器。
类型: |
return_metadata
|
是否返回元数据。
类型: |
distance_threshold
|
所选文档与查询向量之间的最大向量距离。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
List[Document]: 与查询文本最相似的文档列表。 |
similarity_search_by_vector ¶
similarity_search_by_vector(
embedding: list[float],
k: int = 4,
filter: InMemoryDBFilterExpression | None = None,
return_metadata: bool = True,
distance_threshold: float | None = None,
**kwargs: Any,
) -> list[Document]
在查询向量和索引向量之间运行相似性搜索。
| 参数 | 描述 |
|---|---|
embedding
|
要查找相似文档的查询向量。 |
k
|
要返回的文档数。默认为 4。
TYPE: |
filter
|
可选的元数据过滤器。
类型: |
return_metadata
|
是否返回元数据。
类型: |
distance_threshold
|
所选文档与查询向量之间的最大向量距离。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
List[Document]: 与查询文本最相似的文档列表。 |
max_marginal_relevance_search ¶
max_marginal_relevance_search(
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: InMemoryDBFilterExpression | None = None,
return_metadata: bool = True,
distance_threshold: float | None = None,
**kwargs: Any,
) -> list[Document]
返回使用最大边际相关性选择的文档。
最大边际相关性优化查询相似度与所选文档之间的多样性。
| 参数 | 描述 |
|---|---|
query
|
用于查找相似文档的文本。
类型: |
k
|
要返回的文档数量。默认为 4。
TYPE: |
fetch_k
|
要获取并传递给 MMR 算法的 `Document` 对象数量。
类型: |
lambda_mult
|
介于
类型: |
filter
|
可选的元数据过滤器。
类型: |
return_metadata
|
是否返回元数据。
类型: |
distance_threshold
|
所选文档与查询向量之间的最大向量距离。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
List[Document]: 按最大边际相关性选择的文档列表。 |
AmazonS3Vectors ¶
Bases: VectorStore
S3Vectors 是 Amazon S3 Vectors 数据库。
要使用它,您必须首先手动创建一个 S3 向量存储桶。无需创建向量索引。请参阅:https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-getting-started.html
请注意 s3 向量的限制和约束。默认情况下,s3 向量的元数据包括文档的 page_content 和元数据。请参阅:https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-limitations.html
示例
以下示例展示了在 LangChain 中使用 AmazonS3Vectors 的各种方式。
对于以下所有示例,假设我们有以下内容
```python
from langchain_aws.embeddings import BedrockEmbeddings
from langchain_aws.vectorstores.s3_vectors import AmazonS3Vectors
embedding = BedrockEmbeddings()
```
初始化,如果向量索引不存在则创建,并添加文本
```python
vector_store = AmazonS3Vectors.from_texts(
["hello", "developer", "wife"],
vector_bucket_name="<vector bucket name>",
index_name="<vector index name>",
embedding=embedding,
)
```
初始化,如果向量索引不存在则创建,并添加文档
from langchain_core.documents import Document
vector_store = AmazonS3Vectors(
vector_bucket_name="<vector bucket name>",
index_name="<vector index name>",
embedding=embedding,
)
vector_store.add_documents(
[
Document("Star Wars", id="key1", metadata={"genre": "scifi"}),
Document("Jurassic Park", id="key2", metadata={"genre": "scifi"}),
Document("Finding Nemo", id="key3", metadata={"genre": "family"}),
]
)
带分数(距离)和元数据过滤器的搜索
vector_store.similarity_search_with_score(
"adventures in space", filter={"genre": {"$eq": "family"}}
)
| 方法 | 描述 |
|---|---|
aget_by_ids |
通过 ID 异步获取文档。 |
adelete |
按向量 ID 或其他条件异步删除。 |
aadd_texts |
通过嵌入异步运行更多文本并添加到 `VectorStore`。 |
add_documents |
在 `VectorStore` 中添加或更新文档。 |
aadd_documents |
异步运行更多文档通过嵌入并添加到 `VectorStore`。 |
search |
使用指定的搜索类型返回与查询最相似的文档。 |
asearch |
异步返回与查询最相似的文档,使用指定的搜索类型。 |
asimilarity_search_with_score |
异步运行带距离的相似性搜索。 |
similarity_search_with_relevance_scores |
返回文档和在 `[0, 1]` 范围内的相关性分数。 |
asimilarity_search_with_relevance_scores |
异步返回文档和在 `[0, 1]` 范围内的相关性分数。 |
asimilarity_search |
异步返回与查询最相似的文档。 |
asimilarity_search_by_vector |
异步返回与嵌入向量最相似的文档。 |
max_marginal_relevance_search |
返回使用最大边际相关性选择的文档。 |
amax_marginal_relevance_search |
异步返回使用最大边际相关性选择的文档。 |
max_marginal_relevance_search_by_vector |
返回使用最大边际相关性选择的文档。 |
amax_marginal_relevance_search_by_vector |
异步返回使用最大边际相关性选择的文档。 |
from_documents |
返回从文档和嵌入初始化的 `VectorStore`。 |
afrom_documents |
异步返回从文档和嵌入初始化的 `VectorStore`。 |
afrom_texts |
异步返回从文本和嵌入初始化的 `VectorStore`。 |
__init__ |
创建一个 AmazonS3Vectors。 |
add_texts |
向 |
delete |
按向量 ID 删除或删除索引。 |
get_by_ids |
根据 ID 获取文档。 |
similarity_search |
返回与查询最相似的文档。 |
similarity_search_with_score |
运行带分数(距离)的相似性搜索。 |
similarity_search_by_vector |
返回与嵌入向量最相似的文档。 |
as_retriever |
返回从此 AmazonS3Vectors 初始化的 AmazonS3VectorsRetriever。 |
from_texts |
返回从文本和嵌入初始化的 AmazonS3Vectors。 |
aget_by_ids async ¶
adelete async ¶
aadd_texts async ¶
aadd_texts(
texts: Iterable[str],
metadatas: list[dict] | None = None,
*,
ids: list[str] | None = None,
**kwargs: Any,
) -> list[str]
通过嵌入异步运行更多文本并添加到 `VectorStore`。
| 参数 | 描述 |
|---|---|
texts
|
要添加到 `VectorStore` 的字符串的可迭代对象。 |
metadatas
|
与文本关联的元数据可选列表。 |
ids
|
可选列表 |
**kwargs
|
`VectorStore` 特定参数。
类型: |
| 返回 | 描述 |
|---|---|
list[str]
|
将文本添加到 `VectorStore` 后返回的 ID 列表。 |
| 引发 | 描述 |
|---|---|
ValueError
|
如果元数据的数量与文本的数量不匹配。 |
ValueError
|
如果 ID 的数量与文本的数量不匹配。 |
add_documents ¶
aadd_documents async ¶
search ¶
使用指定的搜索类型返回与查询最相似的文档。
| 参数 | 描述 |
|---|---|
query
|
输入文本。
类型: |
search_type
|
要执行的搜索类型。可以是 `'similarity'`、`'mmr'` 或 `'similarity_score_threshold'`。
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
与查询最相似的 `Document` 对象列表。 |
| 引发 | 描述 |
|---|---|
ValueError
|
如果 `search_type` 不是 `'similarity'`、`'mmr'` 或 `'similarity_score_threshold'` 之一。 |
asearch async ¶
异步返回与查询最相似的文档,使用指定的搜索类型。
| 参数 | 描述 |
|---|---|
query
|
输入文本。
类型: |
search_type
|
要执行的搜索类型。可以是 `'similarity'`、`'mmr'` 或 `'similarity_score_threshold'`。
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
与查询最相似的 `Document` 对象列表。 |
| 引发 | 描述 |
|---|---|
ValueError
|
如果 `search_type` 不是 `'similarity'`、`'mmr'` 或 `'similarity_score_threshold'` 之一。 |
asimilarity_search_with_score async ¶
similarity_search_with_relevance_scores ¶
asimilarity_search_with_relevance_scores async ¶
asimilarity_search async ¶
asimilarity_search_by_vector async ¶
max_marginal_relevance_search ¶
max_marginal_relevance_search(
query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any
) -> list[Document]
返回使用最大边际相关性选择的文档。
最大边际相关性优化查询相似度与所选文档之间的多样性。
| 参数 | 描述 |
|---|---|
query
|
用于查找相似文档的文本。
类型: |
k
|
要返回的 `Document` 对象数量。
TYPE: |
fetch_k
|
要获取并传递给 MMR 算法的 `Document` 对象数量。
类型: |
lambda_mult
|
一个介于 `0` 和 `1` 之间的数字,决定了结果之间的多样性程度,其中 `0` 对应最大多样性,`1` 对应最小多样性。
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
通过最大边际相关性选择的 `Document` 对象列表。 |
amax_marginal_relevance_search async ¶
amax_marginal_relevance_search(
query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any
) -> list[Document]
异步返回使用最大边际相关性选择的文档。
最大边际相关性优化查询相似度与所选文档之间的多样性。
| 参数 | 描述 |
|---|---|
query
|
用于查找相似文档的文本。
类型: |
k
|
要返回的 `Document` 对象数量。
TYPE: |
fetch_k
|
要获取并传递给 MMR 算法的 `Document` 对象数量。
类型: |
lambda_mult
|
一个介于 `0` 和 `1` 之间的数字,决定了结果之间的多样性程度,其中 `0` 对应最大多样性,`1` 对应最小多样性。
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
通过最大边际相关性选择的 `Document` 对象列表。 |
max_marginal_relevance_search_by_vector ¶
max_marginal_relevance_search_by_vector(
embedding: list[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> list[Document]
返回使用最大边际相关性选择的文档。
最大边际相关性优化查询相似度与所选文档之间的多样性。
| 参数 | 描述 |
|---|---|
embedding
|
用于查找相似文档的嵌入。 |
k
|
要返回的 `Document` 对象数量。
TYPE: |
fetch_k
|
要获取并传递给 MMR 算法的 `Document` 对象数量。
类型: |
lambda_mult
|
一个介于 `0` 和 `1` 之间的数字,决定了结果之间的多样性程度,其中 `0` 对应最大多样性,`1` 对应最小多样性。
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
通过最大边际相关性选择的 `Document` 对象列表。 |
amax_marginal_relevance_search_by_vector async ¶
amax_marginal_relevance_search_by_vector(
embedding: list[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> list[Document]
异步返回使用最大边际相关性选择的文档。
最大边际相关性优化查询相似度与所选文档之间的多样性。
| 参数 | 描述 |
|---|---|
embedding
|
用于查找相似文档的嵌入。 |
k
|
要返回的 `Document` 对象数量。
TYPE: |
fetch_k
|
要获取并传递给 MMR 算法的 `Document` 对象数量。
类型: |
lambda_mult
|
一个介于 `0` 和 `1` 之间的数字,决定了结果之间的多样性程度,其中 `0` 对应最大多样性,`1` 对应最小多样性。
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
通过最大边际相关性选择的 `Document` 对象列表。 |
from_documents classmethod ¶
from_documents(documents: list[Document], embedding: Embeddings, **kwargs: Any) -> Self
返回从文档和嵌入初始化的 `VectorStore`。
| 参数 | 描述 |
|---|---|
documents
|
要添加到 `VectorStore` 的 `Document` 对象列表。 |
embedding
|
要使用的嵌入函数。
TYPE: |
**kwargs
|
附加的关键字参数。
类型: |
| 返回 | 描述 |
|---|---|
Self
|
从文档和嵌入初始化的 `VectorStore`。 |
afrom_documents async classmethod ¶
afrom_documents(
documents: list[Document], embedding: Embeddings, **kwargs: Any
) -> Self
异步返回从文档和嵌入初始化的 `VectorStore`。
| 参数 | 描述 |
|---|---|
documents
|
要添加到 `VectorStore` 的 `Document` 对象列表。 |
embedding
|
要使用的嵌入函数。
TYPE: |
**kwargs
|
附加的关键字参数。
类型: |
| 返回 | 描述 |
|---|---|
Self
|
从文档和嵌入初始化的 `VectorStore`。 |
afrom_texts async classmethod ¶
__init__ ¶
__init__(
*,
vector_bucket_name: str,
index_name: str,
data_type: Literal["float32"] = "float32",
distance_metric: Literal["euclidean", "cosine"] = "cosine",
non_filterable_metadata_keys: list[str] | None = None,
page_content_metadata_key: str | None = "_page_content",
create_index_if_not_exist: bool = True,
relevance_score_fn: Callable[[float], float] | None = None,
embedding: Embeddings | None = None,
region_name: str | None = None,
credentials_profile_name: str | None = None,
aws_access_key_id: str | None = None,
aws_secret_access_key: str | None = None,
aws_session_token: str | None = None,
endpoint_url: str | None = None,
config: Any = None,
client: Any = None,
**kwargs: Any,
)
创建一个 AmazonS3Vectors。
| 参数 | 描述 |
|---|---|
vector_bucket_name
|
现有 S3 向量存储桶的名称
类型: |
index_name
|
S3 向量索引的名称。索引名称长度必须为 3 到 63 个字符,以字母或数字开头和结尾,并且只能包含小写字母、数字、连字符和点。
类型: |
data_type
|
要插入向量索引的向量的数据类型。默认为“float32”。
类型: |
distance_metric
|
用于相似性搜索的距离度量。默认为“cosine”。
类型: |
non_filterable_metadata_keys
|
不可过滤的元数据键 |
page_content_metadata_key
|
用于在文档中存储 page_content 的元数据键。如果为 None,则嵌入 page_content 但存储为空字符串。默认为
类型: |
create_index_if_not_exist
|
如果向量索引不存在,则自动创建。默认为 True。
类型: |
relevance_score_fn
|
“正确”的相关性函数。 |
embedding
|
要使用的嵌入函数。
TYPE: |
region_name
|
Sagemaker 模型部署的 AWS 区域,例如
类型: |
credentials_profile_name
|
~/.aws/credentials 或 ~/.aws/config 文件中的配置文件名称,其中指定了访问密钥或角色信息。如果未指定,将使用默认凭证配置文件,或者如果在 EC2 实例上,将使用来自 IMDS 的凭证。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
类型: |
aws_access_key_id
|
AWS 访问密钥 ID。如果提供,则还必须提供 aws_secret_access_key。如果未指定,将使用默认凭证配置文件,或者如果在 EC2 实例上,将使用来自 IMDS 的凭证。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从
类型: |
aws_secret_access_key
|
AWS 密钥。如果提供,则还必须提供 aws_access_key_id。如果未指定,将使用默认凭证配置文件,或者如果在 EC2 实例上,将使用来自 IMDS 的凭证。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从
类型: |
aws_session_token
|
AWS 会话令牌。如果提供,则还必须提供 aws_access_key_id 和 aws_secret_access_key。除非使用临时凭证,否则不需要。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从
类型: |
endpoint_url
|
如果您不想默认使用 us-east-1 端点,则需要此项。
类型: |
配置
|
一个可选的
类型: |
client
|
用于 s3vectors 的 Boto3 客户端
类型: |
kwargs
|
附加的关键字参数。
类型: |
add_texts ¶
add_texts(
texts: Iterable[str],
metadatas: list[dict] | None = None,
*,
ids: list[str] | None = None,
batch_size: int = 200,
**kwargs: Any,
) -> list[str]
delete ¶
get_by_ids ¶
similarity_search ¶
similarity_search(
query: str, k: int = 4, *, filter: dict | None = None, **kwargs: Any
) -> list[Document]
返回与查询最相似的文档。
| 参数 | 描述 |
|---|---|
query
|
输入文本。
类型: |
k
|
要返回的文档数量。默认为 4。
TYPE: |
filter
|
在查询期间应用的元数据过滤器。请参阅:https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-metadata-filtering.html
类型: |
**kwargs
|
传递给搜索方法的参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
与查询最相似的 `Document` 对象列表。 |
similarity_search_with_score ¶
similarity_search_with_score(
query: str, k: int = 4, *, filter: dict | None = None, **kwargs: Any
) -> list[tuple[Document, float]]
运行带分数(距离)的相似性搜索。
| 参数 | 描述 |
|---|---|
query
|
输入文本。
类型: |
k
|
要返回的文档数量。默认为 4。
TYPE: |
filter
|
在查询期间应用的元数据过滤器。请参阅:https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-metadata-filtering.html
类型: |
**kwargs
|
附加的关键字参数。
类型: |
| 返回 | 描述 |
|---|---|
list[tuple[Document, float]]
|
(文档,距离)元组的列表。 |
similarity_search_by_vector ¶
similarity_search_by_vector(
embedding: list[float], k: int = 4, *, filter: dict | None = None, **kwargs: Any
) -> list[Document]
返回与嵌入向量最相似的文档。
| 参数 | 描述 |
|---|---|
embedding
|
用于查找相似文档的嵌入。 |
k
|
要返回的文档数量。默认为 4。
TYPE: |
filter
|
在查询期间应用的元数据过滤器。请参阅:https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-metadata-filtering.html
类型: |
**kwargs
|
附加的关键字参数。
类型: |
| 返回 | 描述 |
|---|---|
list[Document]
|
与查询向量最相似的 `Document` 对象列表。 |
as_retriever ¶
as_retriever(**kwargs: Any) -> AmazonS3VectorsRetriever
返回从此 AmazonS3Vectors 初始化的 AmazonS3VectorsRetriever。
from_texts classmethod ¶
from_texts(
texts: list[str],
embedding: Embeddings,
metadatas: list[dict] | None = None,
*,
ids: list[str] | None = None,
vector_bucket_name: str,
index_name: str,
data_type: Literal["float32"] = "float32",
distance_metric: Literal["euclidean", "cosine"] = "cosine",
non_filterable_metadata_keys: list[str] | None = None,
page_content_metadata_key: str | None = "_page_content",
create_index_if_not_exist: bool = True,
relevance_score_fn: Callable[[float], float] | None = None,
region_name: str | None = None,
credentials_profile_name: str | None = None,
aws_access_key_id: str | None = None,
aws_secret_access_key: str | None = None,
aws_session_token: str | None = None,
endpoint_url: str | None = None,
config: Any = None,
client: Any = None,
**kwargs: Any,
) -> AmazonS3Vectors
返回从文本和嵌入初始化的 AmazonS3Vectors。
| 参数 | 描述 |
|---|---|
texts
|
要添加到 `VectorStore` 的文本。 |
embedding
|
要使用的嵌入函数。
TYPE: |
metadatas
|
与文本关联的可选元数据列表。默认为 None。 |
ids
|
与文本关联的 ID 可选列表。 |
vector_bucket_name
|
现有 S3 向量存储桶的名称
类型: |
index_name
|
S3 向量索引的名称。索引名称长度必须为 3 到 63 个字符,以字母或数字开头和结尾,并且只能包含小写字母、数字、连字符和点。
类型: |
data_type
|
要插入向量索引的向量的数据类型。默认为“float32”。
类型: |
distance_metric
|
用于相似性搜索的距离度量。默认为“cosine”。
类型: |
non_filterable_metadata_keys
|
不可过滤的元数据键 |
page_content_metadata_key
|
用于在文档中存储 page_content 的元数据键。如果为 None,则嵌入 page_content 但存储为空字符串。默认为“_page_content”。
类型: |
create_index_if_not_exist
|
如果向量索引不存在,则自动创建。默认为 True。
类型: |
relevance_score_fn
|
“正确”的相关性函数。 |
region_name
|
Sagemaker 模型部署的 AWS 区域,例如
类型: |
credentials_profile_name
|
~/.aws/credentials 或 ~/.aws/config 文件中的配置文件名称,其中指定了访问密钥或角色信息。如果未指定,将使用默认凭证配置文件,或者如果在 EC2 实例上,将使用来自 IMDS 的凭证。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
类型: |
aws_access_key_id
|
AWS 访问密钥 ID。如果提供,则还必须提供 aws_secret_access_key。如果未指定,将使用默认凭证配置文件,或者如果在 EC2 实例上,将使用来自 IMDS 的凭证。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从
类型: |
aws_secret_access_key
|
AWS 密钥。如果提供,则还必须提供 aws_access_key_id。如果未指定,将使用默认凭证配置文件,或者如果在 EC2 实例上,将使用来自 IMDS 的凭证。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从
类型: |
aws_session_token
|
AWS 会话令牌。如果提供,则还必须提供 aws_access_key_id 和 aws_secret_access_key。除非使用临时凭证,否则不需要。请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html 如果未提供,将从
类型: |
endpoint_url
|
如果您不想默认使用 us-east-1 端点,则需要此项。
类型: |
配置
|
一个可选的
类型: |
client
|
用于 s3vectors 的 Boto3 客户端
类型: |
kwargs
|
要传递给 AmazonS3Vectors 的参数。
类型: |
| 返回 | 描述 |
|---|---|
AmazonS3Vectors
|
从文本和嵌入初始化的 AmazonS3Vectors。 |
create_neptune_opencypher_qa_chain ¶
create_neptune_opencypher_qa_chain(
llm: BaseLanguageModel,
graph: BaseNeptuneGraph,
qa_prompt: BasePromptTemplate = CYPHER_QA_PROMPT,
cypher_prompt: BasePromptTemplate | None = None,
return_intermediate_steps: bool = False,
return_direct: bool = False,
extra_instructions: str | None = None,
allow_dangerous_requests: bool = False,
) -> Runnable
通过生成 openCypher 语句对 Neptune 图进行问答的链。
安全提示:请确保数据库连接使用的凭证具有严格限定的范围,仅包含必要的权限。否则可能导致数据损坏或丢失,因为调用代码可能会在适当提示下尝试执行会导致删除、篡改数据的命令,或者如果数据库中存在敏感数据,则会读取这些数据。防止此类负面结果的最佳方法是(酌情)限制授予此工具使用的凭证的权限。
See https://docs.langchain.org.cn/oss/python/security-policy for more information.
create_neptune_sparql_qa_chain ¶
create_neptune_sparql_qa_chain(
llm: BaseLanguageModel,
graph: NeptuneRdfGraph,
qa_prompt: BasePromptTemplate = SPARQL_QA_PROMPT,
sparql_prompt: BasePromptTemplate | None = None,
return_intermediate_steps: bool = False,
return_direct: bool = False,
extra_instructions: str | None = None,
allow_dangerous_requests: bool = False,
examples: str | None = None,
) -> Runnable[Any, dict]
通过生成 SPARQL 语句对 Neptune 图进行问答的链。
安全提示:请确保数据库连接使用的凭证具有严格限定的范围,仅包含必要的权限。否则可能导致数据损坏或丢失,因为调用代码可能会在适当提示下尝试执行会导致删除、篡改数据的命令,或者如果数据库中存在敏感数据,则会读取这些数据。防止此类负面结果的最佳方法是(酌情)限制授予此工具使用的凭证的权限。
See https://docs.langchain.org.cn/oss/python/security-policy for more information.