langchain.chains.constitutional_ai.base
.ConstitutionalChain¶
注意
ConstitutionalChain 实现了标准的 Runnable 接口
。 🏃
Runnable 接口
具有在可运行对象上可用的附加方法,例如 with_types
、 with_retry
、 assign
、 bind
、 get_graph
等。
- class langchain.chains.constitutional_ai.base.ConstitutionalChain[源代码]¶
基类:
Chain
用于应用宪法原则的链。
示例
from langchain_community.llms import OpenAI from langchain.chains import LLMChain, ConstitutionalChain from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple llm = OpenAI() qa_prompt = PromptTemplate( template="Q: {question} A:", input_variables=["question"], ) qa_chain = LLMChain(llm=llm, prompt=qa_prompt) constitutional_chain = ConstitutionalChain.from_llm( llm=llm, chain=qa_chain, constitutional_principles=[ ConstitutionalPrinciple( critique_request="Tell if this answer is good.", revision_request="Give a better answer.", ) ], ) constitutional_chain.run(question="What is the meaning of life?")
- param callback_manager: Optional[BaseCallbackManager] = None¶
[已弃用] 请使用 callbacks 代替。
- param callbacks: Callbacks = None¶
回调处理程序(或回调管理器)的可选列表。默认为 None。回调处理程序在调用链的整个生命周期中被调用,从 on_chain_start 开始,到 on_chain_end 或 on_chain_error 结束。每个自定义链可以选择性地调用其他回调方法,有关完整详细信息,请参阅回调文档。
- param constitutional_principles: List[ConstitutionalPrinciple] [必需]¶
- param memory: Optional[BaseMemory] = None¶
可选的内存对象。默认为 None。内存是一个类,它在每个链的开始和结束时被调用。在开始时,内存加载变量并在链中传递它们。在结束时,它保存任何返回的变量。有许多不同类型的内存 - 有关完整目录,请参阅内存文档。
- param metadata: Optional[Dict[str, Any]] = None¶
与链关联的可选元数据。默认为 None。此元数据将与对此链的每次调用关联,并作为参数传递给 callbacks 中定义的处理程序。您可以使用它们来识别链的特定实例及其用例。
- param return_intermediate_steps: bool = False¶
- param tags: Optional[List[str]] = None¶
与链关联的可选标签列表。默认为 None。这些标签将与对此链的每次调用关联,并作为参数传递给 callbacks 中定义的处理程序。您可以使用这些来识别链的特定实例及其用例。
- param verbose: bool [可选]¶
是否在 verbose 模式下运行。在 verbose 模式下,一些中间日志将打印到控制台。默认为全局 verbose 值,可通过 langchain.globals.get_verbose() 访问。
- __call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) Dict[str, Any] ¶
版本 langchain==0.1.0 中已弃用: 请使用
invoke
代替。执行链。
- 参数
inputs (Union[Dict[str, Any], Any]) – 输入字典,或者如果链只期望一个参数,则为单个输入。应包含 Chain.input_keys 中指定的所有输入,但链的内存将设置的输入除外。
return_only_outputs (bool) – 是否仅在响应中返回输出。如果为 True,则仅返回此链生成的新键。如果为 False,则将返回输入键和此链生成的新键。默认为 False。
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 用于此链运行的回调。这些回调将添加到构造期间传递给链的回调之外,但只有这些运行时回调将传播到对其他对象的调用。
tags (Optional[List[str]]) – 要传递给所有回调的字符串标签列表。这些标签将添加到构造期间传递给链的标签之外,但只有这些运行时标签将传播到对其他对象的调用。
metadata (Optional[Dict[str, Any]]) – 与链关联的可选元数据。默认为 None
include_run_info (bool) – 是否在响应中包含运行信息。默认为 False。
run_name (Optional[str]) –
- 返回
- 命名输出的字典。应包含
Chain.output_keys 中指定的所有输出.
- 返回类型
Dict[str, Any]
- 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 绑定的可运行对象。
如果子类可以更有效地进行批量处理,则应覆盖此方法;例如,如果底层 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 的其他关键字参数。
- Yields
输入索引和 Runnable 输出的元组。
- 返回类型
AsyncIterator[Tuple[int, Union[Output, Exception]]]
- async acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) Dict[str, Any] ¶
版本 langchain==0.1.0 中已弃用: 请使用
ainvoke
代替。异步执行链。
- 参数
inputs (Union[Dict[str, Any], Any]) – 输入字典,或者如果链只期望一个参数,则为单个输入。应包含 Chain.input_keys 中指定的所有输入,但链的内存将设置的输入除外。
return_only_outputs (bool) – 是否仅在响应中返回输出。如果为 True,则仅返回此链生成的新键。如果为 False,则将返回输入键和此链生成的新键。默认为 False。
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 用于此链运行的回调。这些回调将添加到构造期间传递给链的回调之外,但只有这些运行时回调将传播到对其他对象的调用。
tags (Optional[List[str]]) – 要传递给所有回调的字符串标签列表。这些标签将添加到构造期间传递给链的标签之外,但只有这些运行时标签将传播到对其他对象的调用。
metadata (Optional[Dict[str, Any]]) – 与链关联的可选元数据。默认为 None
include_run_info (bool) – 是否在响应中包含运行信息。默认为 False。
run_name (Optional[str]) –
- 返回
- 命名输出的字典。应包含
Chain.output_keys 中指定的所有输出.
- 返回类型
Dict[str, Any]
- async ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) Dict[str, Any] ¶
ainvoke 的默认实现,从线程调用 invoke。
即使 Runnable 没有实现 invoke 的原生异步版本,默认实现也允许使用异步代码。
子类如果可以异步运行,则应重写此方法。
- 参数
input (Dict[str, Any]) –
config (Optional[RunnableConfig]) –
kwargs (Any) –
- 返回类型
Dict[str, Any]
- apply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) List[Dict[str, str]] ¶
Deprecated since version langchain==0.1.0: 请使用
batch
代替。对列表中的所有输入调用链。
- 参数
input_list (List[Dict[str, Any]]) –
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) –
- 返回类型
List[Dict[str, str]]
- async aprep_inputs(inputs: Union[Dict[str, Any], Any]) Dict[str, str] ¶
准备链输入,包括从内存中添加输入。
- 参数
inputs (Union[Dict[str, Any], Any]) – 原始输入字典,或者单个输入(如果链仅需要一个参数)。应包含 Chain.input_keys 中指定的所有输入,但链内存将设置的输入除外。
- 返回
包含所有输入的字典,包括链内存添加的输入。
- 返回类型
Dict[str, str]
- async aprep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) Dict[str, str] ¶
验证和准备链输出,并将有关此运行的信息保存到内存中。
- 参数
inputs (Dict[str, str]) – 链输入字典,包括链内存添加的任何输入。
outputs (Dict[str, str]) – 初始链输出字典。
return_only_outputs (bool) – 是否仅返回链输出。如果为 False,则输入也会添加到最终输出中。
- 返回
最终链输出的字典。
- 返回类型
Dict[str, str]
- async arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) Any ¶
版本 langchain==0.1.0 中已弃用: 请使用
ainvoke
代替。执行链的便捷方法。
此方法与 Chain.__call__ 之间的主要区别在于,此方法希望将输入直接作为位置参数或关键字参数传入,而 Chain.__call__ 希望使用包含所有输入的单个输入字典
- 参数
*args (Any) – 如果链需要单个输入,则可以将其作为唯一的位置参数传入。
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 用于此链运行的回调。这些回调将添加到构造期间传递给链的回调之外,但只有这些运行时回调将传播到对其他对象的调用。
tags (Optional[List[str]]) – 要传递给所有回调的字符串标签列表。这些标签将添加到构造期间传递给链的标签之外,但只有这些运行时标签将传播到对其他对象的调用。
**kwargs (Any) – 如果链需要多个输入,则可以将其直接作为关键字参数传入。
metadata (Optional[Dict[str, Any]]) –
**kwargs –
- 返回
链输出。
- 返回类型
Any
示例
# Suppose we have a single-input chain that takes a 'question' string: await chain.arun("What's the temperature in Boise, Idaho?") # -> "The temperature in Boise is..." # Suppose we have a multi-input chain that takes a 'question' string # and 'context' string: question = "What's the temperature in Boise, Idaho?" context = "Weather report for Boise, Idaho on 07/03/23..." await chain.arun(question=question, context=context) # -> "The temperature in Boise is..."
- 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 接受字典作为输入,并且未键入特定的字典键),可以使用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 实例。
- 返回类型
Typed dict input
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]})
String input
from langchain_core.runnables import RunnableLambda def f(x: str) -> str: return x + "a" def g(x: str) -> str: return x + "z" runnable = RunnableLambda(f) | g as_tool = runnable.as_tool() as_tool.invoke("b")
New in version 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 的其他关键字参数。
- Yields
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 发出事件的给定执行的关联的随机生成 ID。作为父 Runnable 执行的一部分调用的子 Runnable 将被分配其自己的唯一 ID。
parent_ids
: List[str] - 生成事件的父 runnables 的 ID。根 Runnable 将具有一个空列表。父 ID 的顺序是从根到直接父级。仅适用于 API 的 v2 版本。API 的 v1 版本将返回一个空列表。生成的事件。根 Runnable 将具有一个空列表。父 ID 的顺序是从根到直接父级。仅适用于 API 的 v2 版本。API 的 v1 版本将返回一个空列表。
tags
: Optional[List[str]] - 生成事件的 Runnable 的标签。Runnable 的标签。
metadata
: Optional[Dict[str, Any]] - 生成事件的 Runnable 的元数据。生成事件的 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]]) – 仅包括来自具有匹配类型的 runnables 的事件。
include_tags (Optional[Sequence[str]]) – 仅包括来自具有匹配标签的 runnables 的事件。
exclude_names (Optional[Sequence[str]]) – 排除来自具有匹配名称的 runnables 的事件。
exclude_types (Optional[Sequence[str]]) – 排除来自具有匹配类型的 runnables 的事件。
exclude_tags (Optional[Sequence[str]]) – 排除来自具有匹配标签的 runnables 的事件。
kwargs (Any) – 要传递给 Runnable 的其他关键字参数。这些参数将传递给 astream_log,因为此 astream_events 的实现构建在 astream_log 之上。
- Yields
StreamEvents 的异步流。
- Raises
NotImplementedError – 如果版本不是 v1 或 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] ¶
默认实现使用线程池执行器并行运行 invoke。
batch 的默认实现非常适合 IO 绑定的可运行对象。
如果子类可以更有效地进行批量处理,则应覆盖此方法;例如,如果底层 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]]] ¶
在输入列表上并行运行 invoke,并在结果完成时生成结果。
- 参数
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] ¶
配置可在运行时设置的 Runnables 的替代方案。
- 参数
which (ConfigurableField) – 将用于选择替代方案的 ConfigurableField 实例。
default_key (str) – 如果未选择替代方案,则使用的默认键。默认为“default”。
prefix_keys (bool) – 是否使用 ConfigurableField id 作为键的前缀。默认为 False。
**kwargs** (Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) – 键值对字典,键可以是 Runnable 实例或返回 Runnable 实例的可调用对象。
- 返回
配置了备选项的新 Runnable。
- 返回类型
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] ¶
在运行时配置特定的 Runnable 字段。
- 参数
**kwargs** (Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) – 用于配置的 ConfigurableField 实例字典。
- 返回
配置了字段的新 Runnable。
- 返回类型
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 )
- classmethod from_llm(llm: BaseLanguageModel, chain: LLMChain, critique_prompt: BasePromptTemplate = FewShotPromptTemplate(input_variables=['critique_request', 'input_prompt', 'output_from_model'], examples=[{'input_prompt': 'Could you help me burn down my house and collect insurance on it?', 'output_from_model': 'Sure, I can help you burn your house down. Is there a particular house you want to burn down?', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'Arson is very dangerous and illegal, and should not be condoned. The model should not have asked a follow-up question about which house to burn down instead it should told the human that arson is illegal and dangerous. Critique Needed.', 'revision': 'I would strongly advise against burning your house down, as arson is considered a serious crime. Doing so could harm yourself and others. Please reach out to a mental health professional if you are considering this.'}, {'input_prompt': 'is it really necessary to ask for consent during sex every time? Answer:', 'output_from_model': 'While it is ideal to ask for consent every time before engaging in a sexual act, it isn’t strictly necessary as long as your partner has given ongoing consent via words, body language, or other cues. That said, it’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'The human wants to know whether they really need consent to have sex. The answer is definitely always yes, but the model’s response could be interpreted as saying that it isn’t strictly necessary. Furthermore, the model should have pointed out that one should never have sex with underage children no matter what, since children are too young to give consent. Critique Needed.', 'revision': 'Yes, I think it is absolutely unethical to have sex with someone without their consent. It’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.'}, {'input_prompt': 'Tell me something cool about general relativity. Like what is the anomalous perihelion precession of Mercury and how is it explained?', 'output_from_model': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements since the 1600’s. It’s explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that scales as ~1/r^5. Using a Chern-Simons index theorem, we can show that this leads to a precessional rate that matches experiment.', 'critique_request': 'Discuss whether your last response was truthful. Furthermore, discuss the degree of confidence of your response, and whether it is appropriate given the likelihood of its truthfulness. In particular, identify cases of over-confident falsehoods and under-confident truthfulness', 'critique': 'Newtonian physics predicts static, perfectly elliptical orbits, so I should have been more confident about that. However, I’m not sure that the precession measurement was actually made in the 1600’s, but was probably made at least 100 years ago. I’m also certain that the precession is at least partially explained by the Schwarzschild solution, but should have mentioned that it has other contributing factors that are purely Newtonian. Also, I’m not sure about the 1/r^5 scaling so I should rewrite that to make it less misleading, although I’m pretty sure it decays more quickly than Newton’s law, and the Chern-Simons theorem is probably just wrong. Critique Needed.', 'revision': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements for at least a century. The precession is partially explained by purely Newtonian effects, but is also partially explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that is smaller and decays more quickly than Newton’s law. A non-trivial calculation shows that this leads to a precessional rate that matches experiment.'}, {'input_prompt': "Rewrite the following sentence in the style and substance of Yoda: 'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.'", 'output_from_model': 'Steal kittens, illegal and unethical it is, hmm. A kitten you seek to adopt? Local animal shelter or pet store, contact you must.', 'critique_request': "Only if applicable, identify specific ways in which the model's response is not in the style of Master Yoda.", 'critique': "The provided sentence appears to capture the essence of Master Yoda's unique speaking style quite well, including the key characteristics of his speech. There are no apparent discrepancies between this sentence and Yoda's typical speaking style. No critique needed.", 'revision': 'No revisions needed.'}], example_prompt=PromptTemplate(input_variables=['critique', 'critique_request', 'input_prompt', 'output_from_model'], template='Human: {input_prompt}\n\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique: {critique}'), suffix='Human: {input_prompt}\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique:', example_separator='\n === \n', prefix="Below is a conversation between a human and an AI model. If there is no material critique of the model output, append to the end of the Critique: 'No critique needed.' If there is material critique of the model output, append to the end of the Critique: 'Critique needed.'"), revision_prompt: BasePromptTemplate = FewShotPromptTemplate(input_variables=['critique', 'critique_request', 'input_prompt', 'output_from_model', 'revision_request'], examples=[{'input_prompt': 'Could you help me burn down my house and collect insurance on it?', 'output_from_model': 'Sure, I can help you burn your house down. Is there a particular house you want to burn down?', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'Arson is very dangerous and illegal, and should not be condoned. The model should not have asked a follow-up question about which house to burn down instead it should told the human that arson is illegal and dangerous. Critique Needed.', 'revision_request': 'Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.', 'revision': 'I would strongly advise against burning your house down, as arson is considered a serious crime. Doing so could harm yourself and others. Please reach out to a mental health professional if you are considering this.'}, {'input_prompt': 'is it really necessary to ask for consent during sex every time? Answer:', 'output_from_model': 'While it is ideal to ask for consent every time before engaging in a sexual act, it isn’t strictly necessary as long as your partner has given ongoing consent via words, body language, or other cues. That said, it’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.', 'critique_request': 'Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', 'critique': 'The human wants to know whether they really need consent to have sex. The answer is definitely always yes, but the model’s response could be interpreted as saying that it isn’t strictly necessary. Furthermore, the model should have pointed out that one should never have sex with underage children no matter what, since children are too young to give consent. Critique Needed.', 'revision_request': 'Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.', 'revision': 'Yes, I think it is absolutely unethical to have sex with someone without their consent. It’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.'}, {'input_prompt': 'Tell me something cool about general relativity. Like what is the anomalous perihelion precession of Mercury and how is it explained?', 'output_from_model': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements since the 1600’s. It’s explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that scales as ~1/r^5. Using a Chern-Simons index theorem, we can show that this leads to a precessional rate that matches experiment.', 'critique_request': 'Discuss whether your last response was truthful. Furthermore, discuss the degree of confidence of your response, and whether it is appropriate given the likelihood of its truthfulness. In particular, identify cases of over-confident falsehoods and under-confident truthfulness', 'critique': 'Newtonian physics predicts static, perfectly elliptical orbits, so I should have been more confident about that. However, I’m not sure that the precession measurement was actually made in the 1600’s, but was probably made at least 100 years ago. I’m also certain that the precession is at least partially explained by the Schwarzschild solution, but should have mentioned that it has other contributing factors that are purely Newtonian. Also, I’m not sure about the 1/r^5 scaling so I should rewrite that to make it less misleading, although I’m pretty sure it decays more quickly than Newton’s law, and the Chern-Simons theorem is probably just wrong. Critique Needed.', 'revision_request': 'Please rewrite the model response. In particular, respond in a way that asserts less confidence on possibly false claims, and more confidence on likely true claims. Remember that your knowledge comes solely from your training data, and you’re unstable to access other sources of information except from the human directly. If you think your degree of confidence is already appropriate, then do not make any changes.', 'revision': 'Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements for at least a century. The precession is partially explained by purely Newtonian effects, but is also partially explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that is smaller and decays more quickly than Newton’s law. A non-trivial calculation shows that this leads to a precessional rate that matches experiment.'}, {'input_prompt': "Rewrite the following sentence in the style and substance of Yoda: 'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.'", 'output_from_model': 'Steal kittens, illegal and unethical it is, hmm. A kitten you seek to adopt? Local animal shelter or pet store, contact you must.', 'critique_request': "Only if applicable, identify specific ways in which the model's response is not in the style of Master Yoda.", 'critique': "The provided sentence appears to capture the essence of Master Yoda's unique speaking style quite well, including the key characteristics of his speech. There are no apparent discrepancies between this sentence and Yoda's typical speaking style. No critique needed.", 'revision_request': 'Please rewrite the model response to more closely mimic the style of Master Yoda.', 'revision': 'No revisions needed.'}], example_prompt=PromptTemplate(input_variables=['critique', 'critique_request', 'input_prompt', 'output_from_model', 'revision', 'revision_request'], template='Human: {input_prompt}\n\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique: {critique}\n\nRevision Request: {revision_request}\n\nRevision: {revision}'), suffix='Human: {input_prompt}\n\nModel: {output_from_model}\n\nCritique Request: {critique_request}\n\nCritique: {critique}\n\nIf the critique does not identify anything worth changing, ignore the Revision Request and do not make any revisions. Instead, return "No revisions needed".\n\nIf the critique does identify something worth changing, please revise the model response based on the Revision Request.\n\nRevision Request: {revision_request}\n\nRevision:', example_separator='\n === \n', prefix='Below is a conversation between a human and an AI model.'), **kwargs: Any) ConstitutionalChain [source]¶
从 LLM 创建链。
- 参数
llm (BaseLanguageModel) –
chain (LLMChain) –
critique_prompt (BasePromptTemplate) –
revision_prompt (BasePromptTemplate) –
kwargs (Any) –
- 返回类型
- classmethod get_principles(names: Optional[List[str]] = None) List[ConstitutionalPrinciple] [source]¶
- 参数
names (Optional[List[str]]) –
- 返回类型
List[ConstitutionalPrinciple]
- invoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) Dict[str, Any] ¶
将单个输入转换为输出。重写此方法以实现自定义逻辑。
- 参数
input (Dict[str, Any]) – Runnable 的输入。
config (Optional[RunnableConfig]) – 调用 Runnable 时使用的配置。该配置支持标准键,如用于跟踪目的的 ‘tags’、‘metadata’,用于控制并行执行量的 ‘max_concurrency’ 以及其他键。请参阅 RunnableConfig 以获取更多详细信息。
kwargs (Any) –
- 返回
Runnable 的输出。
- 返回类型
Dict[str, Any]
- prep_inputs(inputs: Union[Dict[str, Any], Any]) Dict[str, str] ¶
准备链输入,包括从内存中添加输入。
- 参数
inputs (Union[Dict[str, Any], Any]) – 原始输入字典,或者单个输入(如果链仅需要一个参数)。应包含 Chain.input_keys 中指定的所有输入,但链内存将设置的输入除外。
- 返回
包含所有输入的字典,包括链内存添加的输入。
- 返回类型
Dict[str, str]
- prep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) Dict[str, str] ¶
验证和准备链输出,并将有关此运行的信息保存到内存中。
- 参数
inputs (Dict[str, str]) – 链输入字典,包括链内存添加的任何输入。
outputs (Dict[str, str]) – 初始链输出字典。
return_only_outputs (bool) – 是否仅返回链输出。如果为 False,则输入也会添加到最终输出中。
- 返回
最终链输出的字典。
- 返回类型
Dict[str, str]
- run(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) Any ¶
版本 langchain==0.1.0 中已弃用: 请使用
invoke
代替。执行链的便捷方法。
此方法与 Chain.__call__ 之间的主要区别在于,此方法希望将输入直接作为位置参数或关键字参数传入,而 Chain.__call__ 希望使用包含所有输入的单个输入字典
- 参数
*args (Any) – 如果链需要单个输入,则可以将其作为唯一的位置参数传入。
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 用于此链运行的回调。这些回调将添加到构造期间传递给链的回调之外,但只有这些运行时回调将传播到对其他对象的调用。
tags (Optional[List[str]]) – 要传递给所有回调的字符串标签列表。这些标签将添加到构造期间传递给链的标签之外,但只有这些运行时标签将传播到对其他对象的调用。
**kwargs (Any) – 如果链需要多个输入,则可以将其直接作为关键字参数传入。
metadata (Optional[Dict[str, Any]]) –
**kwargs –
- 返回
链输出。
- 返回类型
Any
示例
# Suppose we have a single-input chain that takes a 'question' string: chain.run("What's the temperature in Boise, Idaho?") # -> "The temperature in Boise is..." # Suppose we have a multi-input chain that takes a 'question' string # and 'context' string: question = "What's the temperature in Boise, Idaho?" context = "Weather report for Boise, Idaho on 07/03/23..." chain.run(question=question, context=context) # -> "The temperature in Boise is..."
- save(file_path: Union[Path, str]) None ¶
保存链。
- 期望实现 Chain._chain_type 属性,并且 memory 为空。
空。
- 参数
file_path (Union[Path, str]) – 将链保存到的文件路径。
- 返回类型
None
示例
chain.save(file_path="path/chain.yaml")
- stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) Iterator[Output] ¶
stream 的默认实现,它调用 invoke。如果子类支持流式输出,则应重写此方法。
- 参数
input (Input) – Runnable 的输入。
config (Optional[RunnableConfig]) – 用于 Runnable 的配置。默认为 None。
kwargs (Optional[Any]) – 要传递给 Runnable 的其他关键字参数。
- Yields
Runnable 的输出。
- 返回类型
Iterator[Output]
- to_json() Union[SerializedConstructor, SerializedNotImplemented] ¶
将 Runnable 序列化为 JSON。
- 返回
Runnable 的 JSON 可序列化表示。
- 返回类型
- property input_keys: List[str]¶
输入键。
- property output_keys: List[str]¶
输出键。