langchain.output_parsers.regex
.RegexParser¶
注意
RegexParser 实现了标准的 Runnable 接口
。 🏃
Runnable 接口
在 runnables 上有额外的方法可用,例如 with_types
, with_retry
, assign
, bind
, get_graph
, 以及更多。
- class langchain.output_parsers.regex.RegexParser[源代码]¶
基类:
BaseOutputParser
[Dict
[str
,str
]]使用正则表达式解析 LLM 调用的输出。
- 参数 default_output_key: Optional[str] = None¶
用于输出的默认键。
- 参数 output_keys: List[str] [必需]¶
用于输出的键。
- 参数 regex: str [必需]¶
用于解析输出的正则表达式。
- async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional">[Any]) List[Output] ¶
默认实现使用 asyncio.gather 并行运行 ainvoke。
batch 的默认实现对于 IO 绑定的 runnables 效果良好。
如果子类可以更有效地进行批处理,则应覆盖此方法;例如,如果底层 Runnable 使用支持批处理模式的 API。
- 参数
inputs (List[Input]) – Runnable 的输入列表。
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 调用 Runnable 时要使用的配置。 该配置支持标准键,如 ‘tags’, ‘metadata’ 用于跟踪目的, ‘max_concurrency’ 用于控制并行执行的工作量,以及其他键。 有关更多详细信息,请参阅 RunnableConfig。 默认为 None。
return_exceptions (bool) – 是否返回异常而不是引发异常。 默认为 False。
kwargs (Optional[Any]) – 传递给 Runnable 的其他关键字参数。
- 返回
来自 Runnable 的输出列表。
- 返回类型
List[Output]
- async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) AsyncIterator[Tuple[int, Union[Output, Exception]]] ¶
并行运行 ainvoke 处理输入列表,并在结果完成时产出结果。
- 参数
inputs (Sequence[Input]) – Runnable 的输入列表。
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 调用 Runnable 时要使用的配置。 该配置支持标准键,如 ‘tags’, ‘metadata’ 用于跟踪目的, ‘max_concurrency’ 用于控制并行执行的工作量,以及其他键。 有关更多详细信息,请参阅 RunnableConfig。 默认为 None。 默认为 None。
return_exceptions (bool) – 是否返回异常而不是引发异常。 默认为 False。
kwargs (Optional[Any]) – 传递给 Runnable 的其他关键字参数。
- 产出
输入索引和来自 Runnable 的输出的元组。
- 返回类型
AsyncIterator[Tuple[int, Union[Output, Exception]]]
- async ainvoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) T ¶
ainvoke 的默认实现,从线程调用 invoke。
即使 Runnable 未实现 invoke 的原生异步版本,默认实现也允许使用异步代码。
如果子类可以异步运行,则应覆盖此方法。
- 参数
input (Union[str, BaseMessage]) –
config (Optional[RunnableConfig]) –
kwargs (Optional[Any]) –
- 返回类型
T
- async aparse(text: str) T ¶
异步地将单个字符串模型输出解析为某种结构。
- 参数
text (str) – 语言模型的字符串输出。
- 返回
结构化输出。
- 返回类型
T
- async aparse_result(result: List[Generation], *, partial: bool = False) T ¶
异步地将候选模型 Generations 列表解析为特定格式。
- 返回值仅从结果中的第一个 Generation 解析,该 Generation
被假定为最高可能性的 Generation。
- 参数
result (List[Generation]) – 要解析的 Generations 列表。 Generations 被假定为单个模型输入的不同候选输出。
partial (bool) – 是否将输出解析为部分结果。 这对于可以解析部分结果的解析器很有用。 默认为 False。
- 返回
结构化输出。
- 返回类型
T
- as_tool(args_schema: Optional[Type[BaseModel]] = None, *, name: Optional[str] = None, description: Optional[str] = None, arg_types: Optional[Dict[str, Type]] = None) BaseTool ¶
Beta
此 API 处于 beta 阶段,未来可能会发生更改。
从 Runnable 创建 BaseTool。
as_tool
将从 Runnable 实例化一个具有名称、描述和args_schema
的 BaseTool。 如果可能,模式会从runnable.get_input_schema
推断。 或者(例如,如果 Runnable 接受 dict 作为输入,并且未键入特定的 dict 键),可以使用args_schema
直接指定模式。 您还可以传递arg_types
以仅指定必需的参数及其类型。- 参数
args_schema (Optional[Type[BaseModel]]) – 该工具的模式。 默认为 None。
name (Optional[str]) – 该工具的名称。 默认为 None。
description (Optional[str]) – 该工具的描述。 默认为 None。
arg_types (Optional[Dict[str, Type]]) – 参数名称到类型的字典。 默认为 None。
- 返回
一个 BaseTool 实例。
- 返回类型
类型化字典输入
from typing import List 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, Dict, List from langchain_core.pydantic_v1 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, Dict, List from langchain_core.runnables import RunnableLambda def f(x: Dict[str, Any]) -> str: return str(x["a"] * max(x["b"])) runnable = RunnableLambda(f) as_tool = runnable.as_tool(arg_types={"a": int, "b": List[int]}) as_tool.invoke({"a": 3, "b": [1, 2]})
字符串输入
from langchain_core.runnables import RunnableLambda def f(x: str) -> str: return x + "a" def g(x: str) -> str: return x + "z" runnable = RunnableLambda(f) | g as_tool = runnable.as_tool() as_tool.invoke("b")
0.2.14 版本新增功能。
- async astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) AsyncIterator">[Output] ¶
astream 的默认实现,它调用 ainvoke。 如果子类支持流式输出,则应覆盖此方法。
- 参数
input (Input) – Runnable 的输入。
config (Optional[RunnableConfig]) – 用于 Runnable 的配置。 默认为 None。
kwargs (Optional[Any]) – 传递给 Runnable 的其他关键字参数。
- 产出
Runnable 的输出。
- 返回类型
AsyncIterator[Output]
- astream_events(input: Any, config: Optional[RunnableConfig] = None, *, version: Literal['v1', 'v2'], include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Any) AsyncIterator[Union[StandardStreamEvent, CustomStreamEvent]] ¶
Beta
此 API 处于 beta 阶段,未来可能会发生更改。
生成事件流。
用于创建 StreamEvents 的迭代器,该迭代器提供有关 Runnable 进度的实时信息,包括来自中间结果的 StreamEvents。
StreamEvent 是一个字典,具有以下模式
event
: str - 事件名称的格式为:格式:on_[runnable_type]_(start|stream|end)。
name
: str - 生成事件的 Runnable 的名称。run_id
: str - 随机生成的 ID,与给定 Runnable 执行相关联,该 Runnable 发出事件。 作为父 Runnable 执行的一部分调用的子 Runnable 会被分配其自己的唯一 ID。Runnable 发出事件。 作为父 Runnable 执行的一部分调用的子 Runnable 会被分配其自己的唯一 ID。
parent_ids
: List[str] - 生成事件的父 runnables 的 ID。 根 Runnable 将具有一个空列表。 父 ID 的顺序是从根到直接父级。 仅适用于 API 的 v2 版本。 API 的 v1 版本将返回一个空列表。API 的 v1 版本将返回一个空列表。
tags
: Optional[List[str]] - 生成事件的 Runnable 的标签。事件。
metadata
: Optional[Dict[str, Any]] - 生成事件的 Runnable 的元数据。事件。
data
: Dict[str, Any]
下面是一个表格,说明了各种链可能发出的一些事件。 为了简洁起见,元数据字段已从表格中省略。 链定义已包含在表格之后。
注意 此参考表适用于模式的 V2 版本。
事件
名称
块
输入
输出
on_chat_model_start
[模型名称]
{“messages”: [[SystemMessage, HumanMessage]]}
on_chat_model_stream
[模型名称]
AIMessageChunk(content=”hello”)
on_chat_model_end
[模型名称]
{“messages”: [[SystemMessage, HumanMessage]]}
AIMessageChunk(content=”hello world”)
on_llm_start
[模型名称]
{‘input’: ‘hello’}
on_llm_stream
[模型名称]
‘Hello’
on_llm_end
[模型名称]
‘Hello human!’
on_chain_start
format_docs
on_chain_stream
format_docs
“hello world!, goodbye world!”
on_chain_end
format_docs
[Document(…)]
“hello world!, goodbye world!”
on_tool_start
some_tool
{“x”: 1, “y”: “2”}
on_tool_end
some_tool
{“x”: 1, “y”: “2”}
on_retriever_start
[检索器名称]
{“query”: “hello”}
on_retriever_end
[检索器名称]
{“query”: “hello”}
[Document(…), ..]
on_prompt_start
[模板名称]
{“question”: “hello”}
on_prompt_end
[模板名称]
{“question”: “hello”}
ChatPromptValue(messages: [SystemMessage, …])
除了标准事件之外,用户还可以调度自定义事件(请参阅下面的示例)。
自定义事件将仅在 API 的 v2 版本中显示!
自定义事件具有以下格式
属性
类型
描述
名称
str
用户定义的事件名称。
data
Any
与事件关联的数据。 这可以是任何内容,但我们建议使其可 JSON 序列化。
以下是与上面显示的标准事件关联的声明
format_docs:
def format_docs(docs: List[Document]) -> str: '''Format the docs.''' return ", ".join([doc.page_content for doc in docs]) format_docs = RunnableLambda(format_docs)
some_tool:
@tool def some_tool(x: int, y: str) -> dict: '''Some_tool.''' return {"x": x, "y": y}
prompt:
template = ChatPromptTemplate.from_messages( [("system", "You are Cat Agent 007"), ("human", "{question}")] ).with_config({"run_name": "my_template", "tags": ["my_template"]})
示例
from langchain_core.runnables import RunnableLambda async def reverse(s: str) -> str: return s[::-1] chain = RunnableLambda(func=reverse) events = [ event async for event in chain.astream_events("hello", version="v2") ] # will produce the following events (run_id, and parent_ids # has been omitted for brevity): [ { "data": {"input": "hello"}, "event": "on_chain_start", "metadata": {}, "name": "reverse", "tags": [], }, { "data": {"chunk": "olleh"}, "event": "on_chain_stream", "metadata": {}, "name": "reverse", "tags": [], }, { "data": {"output": "olleh"}, "event": "on_chain_end", "metadata": {}, "name": "reverse", "tags": [], }, ]
示例:调度自定义事件
from langchain_core.callbacks.manager import ( adispatch_custom_event, ) from langchain_core.runnables import RunnableLambda, RunnableConfig import asyncio async def slow_thing(some_input: str, config: RunnableConfig) -> str: """Do something that takes a long time.""" await asyncio.sleep(1) # Placeholder for some slow operation await adispatch_custom_event( "progress_event", {"message": "Finished step 1 of 3"}, config=config # Must be included for python < 3.10 ) await asyncio.sleep(1) # Placeholder for some slow operation await adispatch_custom_event( "progress_event", {"message": "Finished step 2 of 3"}, config=config # Must be included for python < 3.10 ) await asyncio.sleep(1) # Placeholder for some slow operation return "Done" slow_thing = RunnableLambda(slow_thing) async for event in slow_thing.astream_events("some_input", version="v2"): print(event)
- 参数
input (Any) – Runnable 的输入。
config (Optional[RunnableConfig]) – 用于 Runnable 的配置。
version (Literal['v1', 'v2']) – 要使用的模式版本, v2 或 v1。 用户应使用 v2。 v1 用于向后兼容,将在 0.4.0 中弃用。 在 API 稳定之前,不会分配默认值。 自定义事件将仅在 v2 中显示。
include_names (Optional[Sequence[str]]) – 仅包含来自具有匹配名称的 runnables 的事件。
include_types (Optional[Sequence[str]]) – Only include events from runnables with matching types.
include_tags (Optional[Sequence[str]]) – Only include events from runnables with matching tags.
exclude_names (Optional[Sequence[str]]) – Exclude events from runnables with matching names.
exclude_types (Optional[Sequence[str]]) – Exclude events from runnables with matching types.
exclude_tags (Optional[Sequence[str]]) – Exclude events from runnables with matching tags.
kwargs (Any) – Additional keyword arguments to pass to the Runnable. These will be passed to astream_log as this implementation of astream_events is built on top of astream_log.
- 产出
An async stream of StreamEvents.
- Raises
NotImplementedError – If the version is not v1 or v2.
- 返回类型
AsyncIterator[Union[StandardStreamEvent, CustomStreamEvent]]
- batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions">: bool = False, **kwargs">: Optional]Any]) List[Output] ¶
Default implementation runs invoke in parallel using a thread pool executor.
batch 的默认实现对于 IO 绑定的 runnables 效果良好。
如果子类可以更有效地进行批处理,则应覆盖此方法;例如,如果底层 Runnable 使用支持批处理模式的 API。
- 参数
inputs (List[Input]) –
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) –
return_exceptions (bool) –
kwargs (Optional[Any]) –
- 返回类型
List[Output]
- batch_as_completed(inputs: Sequence[Input], config">: Optional]Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions">: bool = False, **kwargs">: Optional]Any]) Iterator[Tuple[int, Union[Output, Exception]]] ¶
Run invoke in parallel on a list of inputs, yielding results as they complete.
- 参数
inputs (Sequence[Input]) –
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) –
return_exceptions (bool) –
kwargs (Optional[Any]) –
- 返回类型
Iterator[Tuple[int, Union[Output, Exception]]]
- configurable_alternatives(which">: ConfigurableField, *, default_key">: str = 'default', prefix_keys">: bool = False, **kwargs:]: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) RunnableSerializable[Input, Output] ¶
Configure alternatives for Runnables that can be set at runtime.
- 参数
which (ConfigurableField) – The ConfigurableField instance that will be used to select the alternative.
default_key (str) – The default key to use if no alternative is selected. Defaults to “default”.
prefix_keys (bool) – Whether to prefix the keys with the ConfigurableField id. Defaults to False.
**kwargs (Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) – A dictionary of keys to Runnable instances or callables that return Runnable instances.
- 返回
A new Runnable with the alternatives configured.
- 返回类型
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-3-sonnet-20240229" ).configurable_alternatives( ConfigurableField(id="llm"), default_key="anthropic", openai=ChatOpenAI() ) # uses the default model ChatAnthropic print(model.invoke("which organization created you?").content) # uses ChatOpenAI print( model.with_config( configurable={"llm": "openai"} ).invoke("which organization created you?").content )
- configurable_fields(**kwargs:]: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) RunnableSerializable[Input, Output] ¶
Configure particular Runnable fields at runtime.
- 参数
**kwargs (Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) – A dictionary of ConfigurableField instances to configure.
- 返回
A new Runnable with the fields configured.
- 返回类型
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 )
- get_format_instructions() str ¶
Instructions on how the LLM output should be formatted.
- 返回类型
str
- invoke(input:]: Union[str, BaseMessage], config:]: Optional[RunnableConfig] = None) T ¶
Transform a single input into an output. Override to implement.
- 参数
input (Union[str, BaseMessage]) – The input to the Runnable.
config (Optional[RunnableConfig]) – A config to use when invoking the Runnable. The config supports standard keys like ‘tags’, ‘metadata’ for tracing purposes, ‘max_concurrency’ for controlling how much work to do in parallel, and other keys. Please refer to the RunnableConfig for more details.
- 返回
Runnable 的输出。
- 返回类型
T
- parse(text:]: str) Dict[str, str] [source]¶
Parse the output of an LLM call.
- 参数
text (str) –
- 返回类型
Dict[str, str]
- parse_result(result:]: List[Generation], *, partial:]: bool = False) T ¶
Parse a list of candidate model Generations into a specific format.
- 返回值仅从结果中的第一个 Generation 解析,该 Generation
被假定为最高可能性的 Generation。
- 参数
result (List[Generation]) – 要解析的 Generations 列表。 Generations 被假定为单个模型输入的不同候选输出。
partial (bool) – 是否将输出解析为部分结果。 这对于可以解析部分结果的解析器很有用。 默认为 False。
- 返回
结构化输出。
- 返回类型
T
- parse_with_prompt(completion:]: str, prompt:]: PromptValue) Any ¶
Parse the output of an LLM call with the input prompt for context.
The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so.
- 参数
completion (str) – String output of a language model.
prompt (PromptValue) – Input PromptValue.
- 返回
结构化输出。
- 返回类型
Any
- stream(input:]: Input, config:]: Optional[RunnableConfig] = None, **kwargs:]: Optional[Any]) Iterator[Output] ¶
Default implementation of stream, which calls invoke. Subclasses should override this method if they support streaming output.
- 参数
input (Input) – Runnable 的输入。
config (Optional[RunnableConfig]) – 用于 Runnable 的配置。 默认为 None。
kwargs (Optional[Any]) – 传递给 Runnable 的其他关键字参数。
- 产出
Runnable 的输出。
- 返回类型
Iterator[Output]
- to_json() Union[SerializedConstructor, SerializedNotImplemented] ¶
Serialize the Runnable to JSON.
- 返回
A JSON-serializable representation of the Runnable.
- 返回类型