langchain_aws.chat_models.bedrock
.ChatBedrock¶
注意
ChatBedrock 实现了标准的 Runnable 接口
。🏃
Runnable 接口
在 runnables 上有额外的方法可用,例如 with_types
, with_retry
, assign
, bind
, get_graph
, 以及更多。
- class langchain_aws.chat_models.bedrock.ChatBedrock[源代码]¶
基类:
BaseChatModel
,BedrockBase
一个使用 Bedrock API 的聊天模型。
- param beta_use_converse_api: bool = False¶
使用新的 Bedrock
converse
API,它为所有 Bedrock 模型提供了一个标准化的接口。支持仍在 beta 阶段。有关更多信息,请参阅 ChatBedrockConverse 文档。
- param cache: Union[BaseCache, bool, None] = None¶
是否缓存响应。
如果为 true,将使用全局缓存。
如果为 false,将不使用缓存
如果为 None,如果设置了全局缓存,则使用全局缓存,否则不使用缓存。
如果是 BaseCache 的实例,将使用提供的缓存。
模型流式处理方法目前不支持缓存。
- param callback_manager: Optional:[BaseCallbackManager] = None¶
[已弃用] 要添加到运行轨迹的回调管理器。
- param callbacks: Callbacks = None¶
要添加到运行轨迹的回调。
- param config: Any = None¶
一个可选的 botocore.config.Config 实例,用于传递给客户端。
- param credentials_profile_name: Optional:[str] = None¶
~/.aws/credentials 或 ~/.aws/config 文件中配置文件的名称,其中指定了访问密钥或角色信息。如果未指定,将使用默认凭证配置文件,或者如果在 EC2 实例上,则将使用来自 IMDS 的凭证。请参阅: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
- param custom_get_token_ids: Optional:[Callable[[str], List:[int]]] = None¶
用于计算 token 的可选编码器。
- param endpoint_url: Optional:[str] = None¶
如果您不想默认为 us-east-1 端点,则需要此参数
- param guardrails: Optional:[Mapping:[str, Any]] = {'guardrailIdentifier': None, 'guardrailVersion': None, 'trace': None}¶
一个可选的字典,用于配置 Bedrock 的护栏。
此字段 'guardrails' 包含两个键:'id' 和 'version',它们应该是字符串,但初始化为 None。它用于确定是否启用并正确设置了特定的护栏。
- 类型
Optional[Mapping[str, str]]: 具有 'id' 和 'version' 键的映射。
示例: llm = Bedrock(model_id=”<model_id>”, client=<bedrock_client>,
model_kwargs={}, guardrails={
“id”: “<guardrail_id>”, “version”: “<guardrail_version>”})
要启用护栏的跟踪,请将 'trace' 键设置为 True,并将回调处理程序传递给 'generate'、'_call' 方法的 'run_manager' 参数。
示例: llm = Bedrock(model_id=”<model_id>”, client=<bedrock_client>,
model_kwargs={}, guardrails={
“id”: “<guardrail_id>”, “version”: “<guardrail_version>”, “trace”: True},
callbacks=[BedrockAsyncCallbackHandler()])
[https://python.langchain.ac.cn/docs/modules/callbacks/] 有关回调处理程序的更多信息。
- class BedrockAsyncCallbackHandler(AsyncCallbackHandler)
- async def on_llm_error(
self, error: BaseException, **kwargs: Any,
- ) -> Any
reason = kwargs.get(“reason”) if reason == “GUARDRAIL_INTERVENED”
...处理护栏干预的逻辑...
- param metadata: Optional:[Dict:[str, Any]] = None¶
要添加到运行轨迹的元数据。
- param model_id: str [必填]¶
要调用的模型的 ID,例如,amazon.titan-text-express-v1,这等同于 list-foundation-models api 中的 modelId 属性。对于自定义模型和预置模型,应使用 ARN 值。
- param model_kwargs: Optional:[Dict:[str, Any]] = None¶
要传递给模型的关键字参数。
- param provider: Optional:[str] = None¶
模型提供商,例如,amazon、cohere、ai21 等。如果未提供,则从 model_id 的第一部分提取提供商,例如 'amazon.titan-text-express-v1' 中的 'amazon'。对于模型 ID 中没有提供商的模型(例如,与其关联的 ARN 的自定义模型和预置模型),应提供此值。
- param provider_stop_reason_key_map: Mapping:[str, str] = {'ai21': 'finishReason', 'amazon': 'completionReason', 'anthropic': 'stop_reason', 'cohere': 'finish_reason', 'mistral': 'stop_reason'}¶
- param provider_stop_sequence_key_name_map: Mapping:[str, str] = {'ai21': 'stop_sequences', 'amazon': 'stopSequences', 'anthropic': 'stop_sequences', 'cohere': 'stop_sequences', 'mistral': 'stop_sequences'}¶
- param rate_limiter: Optional:[BaseRateLimiter] = None¶
一个可选的速率限制器,用于限制请求的数量。
- param region_name: Optional:[str] = None¶
aws 区域,例如 us-west-2。如果此处未提供,则回退到 AWS_DEFAULT_REGION 环境变量或 ~/.aws/config 中指定的区域。
- param streaming: bool = False¶
是否流式传输结果。
- param system_prompt_with_tools: str = ''¶
- param tags: Optional:[List:[str]] = None¶
要添加到运行轨迹的标签。
- param verbose: bool [可选]¶
是否打印输出响应文本。
- __call__(messages: List:[BaseMessage], stop: Optional:[List:[str]] = None, callbacks: Optional:[Union:[List:[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) BaseMessage ¶
Deprecated since version langchain-core==0.1.7: 请使用
invoke
代替。- 参数
messages (List[BaseMessage]) –
stop (Optional[List[str]]) –
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) –
kwargs (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 绑定的 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 agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, run_id: Optional[UUID] = None, **kwargs: Any) LLMResult ¶
异步地将一系列提示传递给模型并返回生成结果。
此方法应利用批量调用,以用于公开批量 API 的模型。
- 当您想要以下操作时,请使用此方法:
利用批量调用的优势,
需要从模型获得比仅仅是最佳生成值更多的输出,
- 构建与底层语言模型无关的链
类型(例如,纯文本补全模型与聊天模型)。
- 参数
messages (List[List[BaseMessage]]) – 消息列表的列表。
stop (Optional[List[str]]) – 生成时使用的停止词。模型输出在首次出现任何这些子字符串时被截断。
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 要传递的回调。用于在整个生成过程中执行额外的功能,例如日志记录或流式传输。
**kwargs (Any) – 任意附加关键字参数。这些通常传递给模型提供商 API 调用。
tags (Optional[List[str]]) –
metadata (Optional[Dict[str, Any]]) –
run_name (Optional[str]) –
run_id (Optional[UUID]) –
**kwargs –
- 返回值
- 一个 LLMResult,其中包含每个输入的候选 Generation 列表
提示以及其他模型提供商特定的输出。
- 返回类型
- async agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) LLMResult ¶
异步地传递一系列提示并返回模型生成结果。
此方法应利用批量调用,以用于公开批量 API 的模型。
- 当您想要以下操作时,请使用此方法:
利用批量调用的优势,
需要从模型获得比仅仅是最佳生成值更多的输出,
- 构建与底层语言模型无关的链
类型(例如,纯文本补全模型与聊天模型)。
- 参数
prompts (List[PromptValue]) – PromptValue 列表。PromptValue 是一个可以转换为匹配任何语言模型格式的对象(纯文本生成模型的字符串和聊天模型的 BaseMessages)。
stop (Optional[List[str]]) – 生成时使用的停止词。模型输出在首次出现任何这些子字符串时被截断。
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 要传递的回调。用于在整个生成过程中执行额外的功能,例如日志记录或流式传输。
**kwargs (Any) – 任意附加关键字参数。这些通常传递给模型提供商 API 调用。
- 返回值
- 一个 LLMResult,其中包含每个输入的候选 Generation 列表
提示以及其他模型提供商特定的输出。
- 返回类型
- async ainvoke(input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) BaseMessage ¶
ainvoke
的默认实现,从线程中调用 invoke。即使 Runnable 没有实现 invoke 的原生异步版本,默认实现也允许使用异步代码。
如果子类可以异步运行,则应重写此方法。
- 参数
input (LanguageModelInput) –
config (Optional[RunnableConfig]) –
stop (Optional[List[str]]) –
kwargs (Any) –
- 返回类型
- async apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) str ¶
Deprecated since version langchain-core==0.1.7: 请使用
ainvoke
代替。- 参数
text (str) –
stop (Optional[Sequence[str]]) –
kwargs (Any) –
- 返回类型
str
- async apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) BaseMessage ¶
Deprecated since version langchain-core==0.1.7: 请使用
ainvoke
代替。- 参数
messages (List[BaseMessage]) –
stop (Optional[Sequence[str]]) –
kwargs (Any) –
- 返回类型
- 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 实例。
- 返回类型
类型化的 dict 输入
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: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) AsyncIterator[BaseMessageChunk] ¶
astream
的默认实现,它调用ainvoke
。如果子类支持流式输出,则应重写此方法。- 参数
input (LanguageModelInput) – Runnable 的输入。
config (Optional[RunnableConfig]) – 用于 Runnable 的配置。默认为 None。
kwargs (Any) – 要传递给 Runnable 的其他关键字参数。
stop (Optional[List[str]]) –
- 产生
Runnable 的输出。
- 返回类型
AsyncIterator[BaseMessageChunk]
- 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 被分配其自己唯一的 ID。the Runnable that emitted the event. A child Runnable that gets invoked as part of the execution of a parent Runnable is assigned its own unique ID.
parent_ids
: List[str] - 生成事件的父 runnables 的 ID 列表。根 Runnable 将有一个空列表。父 ID 的顺序是从根到直接父级。仅适用于 API 的 v2 版本。API 的 v1 版本将返回一个空列表。
tags
: Optional[List[str]] - 生成事件的 Runnable 的标签。the event.
metadata
: Optional[Dict[str, Any]] - Runnable 的元数据生成事件的 Runnable 的元数据。
data
: Dict[str, Any]
下面是一个表格,说明了各种链可能发出的一些事件。为了简洁起见,元数据字段已从表格中省略。链定义已包含在表格之后。
注意 此参考表适用于模式的 V2 版本。
event
name
chunk
input
output
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 版本中显示!
自定义事件具有以下格式
Attribute
类型
Description
name
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"]})
Example
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 之上。
- 产生
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 绑定的 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]]] ¶
并行运行 invoke 于输入列表,并在结果完成时产出结果。
- 参数
inputs (Sequence[Input]) –
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) –
return_exceptions (bool) –
kwargs (Optional[Any]) –
- 返回类型
Iterator[Tuple[int, Union[Output, Exception]]]
- bind_tools(tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]], *, tool_choice: Optional[Union[dict, str, Literal['auto', 'none'], bool]] = None, **kwargs: Any) Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List, Tuple, str, Dict]]], BaseMessage] [source]¶
将类似工具的对象绑定到此聊天模型。
假设模型具有工具调用 API。
- 参数
tools (Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]]) – 要绑定到此聊天模型的工具定义列表。可以是字典、pydantic 模型、可调用对象或 BaseTool。Pydantic 模型、可调用对象和 BaseTool 将自动转换为其模式字典表示形式。
tool_choice (Optional[Union[dict, str, Literal['auto', 'none'], bool]]) – 需要模型调用的工具。必须是单个提供的函数的名称,或 “auto” 以自动确定要调用的函数(如果有),或字典形式:{“type”: “function”, “function”: {“name”: <<tool_name>>}}。
**kwargs (Any) – 传递给
Runnable
构造函数的任何其他参数。
- 返回类型
Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], BaseMessage]
- call_as_llm(message: str, stop: Optional[List]] = None, **kwargs: Any) str ¶
Deprecated since version langchain-core==0.1.7: 请使用
invoke
代替。- 参数
message (str) –
stop (Optional[List[str]]) –
kwargs (Any) –
- 返回类型
str
- configurable_alternatives(which: ConfigurableField, *, default_key: str = 'default', prefix_keys: bool = False, **kwargs: Union[Runnable, Callable[[], Runnable]]]) RunnableSerializable, 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, 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 )
- generate(messages: List[List[BaseMessage]], stop: Optional[List]] = None, callbacks: Optional[Union[List, BaseCallbackManager]] = None, *, tags: Optional] = None, metadata: Optional] = None, run_name: Optional] = None, run_id: Optional] = None, **kwargs: Any) LLMResult ¶
将一系列提示传递给模型并返回模型生成结果。
此方法应利用批量调用,以用于公开批量 API 的模型。
- 当您想要以下操作时,请使用此方法:
利用批量调用的优势,
需要从模型获得比仅仅是最佳生成值更多的输出,
- 构建与底层语言模型无关的链
类型(例如,纯文本补全模型与聊天模型)。
- 参数
messages (List[List[BaseMessage]]) – 消息列表的列表。
stop (Optional[List[str]]) – 生成时使用的停止词。模型输出在首次出现任何这些子字符串时被截断。
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 要传递的回调。用于在整个生成过程中执行额外的功能,例如日志记录或流式传输。
**kwargs (Any) – 任意附加关键字参数。这些通常传递给模型提供商 API 调用。
tags (Optional[List[str]]) –
metadata (Optional[Dict[str, Any]]) –
run_name (Optional[str]) –
run_id (Optional[UUID]) –
**kwargs –
- 返回值
- 一个 LLMResult,其中包含每个输入的候选 Generation 列表
提示以及其他模型提供商特定的输出。
- 返回类型
- generate_prompt(prompts: List[PromptValue], stop: Optional[List]] = None, callbacks: Optional[Union, BaseCallbackManager]] = None, **kwargs: Any) LLMResult ¶
将一系列提示传递给模型并返回模型生成结果。
此方法应利用批量调用,以用于公开批量 API 的模型。
- 当您想要以下操作时,请使用此方法:
利用批量调用的优势,
需要从模型获得比仅仅是最佳生成值更多的输出,
- 构建与底层语言模型无关的链
类型(例如,纯文本补全模型与聊天模型)。
- 参数
prompts (List[PromptValue]) – PromptValue 列表。PromptValue 是一个可以转换为匹配任何语言模型格式的对象(纯文本生成模型的字符串和聊天模型的 BaseMessages)。
stop (Optional[List[str]]) – 生成时使用的停止词。模型输出在首次出现任何这些子字符串时被截断。
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 要传递的回调。用于在整个生成过程中执行额外的功能,例如日志记录或流式传输。
**kwargs (Any) – 任意附加关键字参数。这些通常传递给模型提供商 API 调用。
- 返回值
- 一个 LLMResult,其中包含每个输入的候选 Generation 列表
提示以及其他模型提供商特定的输出。
- 返回类型
- get_num_tokens(text: str) int [source]¶
获取文本中存在的 token 数量。
用于检查输入是否适合模型的上下文窗口。
- 参数
text (str) – 要标记化的字符串输入。
- 返回值
文本中 token 的整数数量。
- 返回类型
int
- get_num_tokens_from_messages(messages: List[BaseMessage]) int ¶
获取消息中的 token 数量。
用于检查输入是否适合模型的上下文窗口。
- 参数
messages (List[BaseMessage]) – 要标记化的消息输入。
- 返回值
消息中 token 数量的总和。
- 返回类型
int
- get_token_ids(text: str) List] [source]¶
返回文本中 token 的有序 ID。
- 参数
text (str) – 要标记化的字符串输入。
- 返回值
- 与文本中的 token 对应的 ID 列表,按照它们在文本中出现的顺序排列。
在文本中。
- 返回类型
List[int]
- invoke(input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List]] = None, **kwargs: Any) BaseMessage ¶
将单个输入转换为输出。覆盖以实现。
- 参数
input (LanguageModelInput) – Runnable 的输入。
config (Optional[RunnableConfig]) – 调用 Runnable 时使用的配置。该配置支持标准键,例如用于跟踪目的的 ‘tags’、‘metadata’,用于控制并行执行量的 ‘max_concurrency’ 以及其他键。请参阅 RunnableConfig 以获取更多详细信息。
stop (Optional[List[str]]) –
kwargs (Any) –
- 返回值
Runnable 的输出。
- 返回类型
- predict(text: str, *, stop: Optional[Sequence] = None, **kwargs: Any) str ¶
Deprecated since version langchain-core==0.1.7: 请使用
invoke
代替。- 参数
text (str) –
stop (Optional[Sequence[str]]) –
kwargs (Any) –
- 返回类型
str
- predict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence] = None, **kwargs: Any) BaseMessage ¶
Deprecated since version langchain-core==0.1.7: 请使用
invoke
代替。- 参数
messages (List[BaseMessage]) –
stop (Optional[Sequence[str]]) –
kwargs (Any) –
- 返回类型
- set_system_prompt_with_tools(xml_tools_system_prompt: str) None [source]¶
绑定工具的解决方法。设置带有工具的系统提示
- 参数
xml_tools_system_prompt (str) –
- 返回类型
None
- stream(input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) Iterator[BaseMessageChunk] ¶
stream 的默认实现,它调用 invoke。如果子类支持流式输出,则应该重写此方法。
- 参数
input (LanguageModelInput) – Runnable 的输入。
config (Optional[RunnableConfig]) – 用于 Runnable 的配置。默认为 None。
kwargs (Any) – 要传递给 Runnable 的其他关键字参数。
stop (Optional[List[str]]) –
- 产生
Runnable 的输出。
- 返回类型
Iterator[BaseMessageChunk]
- to_json() Union[SerializedConstructor, SerializedNotImplemented] ¶
将 Runnable 序列化为 JSON。
- 返回值
Runnable 的 JSON 可序列化表示。
- 返回类型
- with_structured_output(schema: Union[Dict, Type[BaseModel]], *, include_raw: bool = False, **kwargs: Any) Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], Union[Dict, BaseModel]] [source]¶
模型包装器,返回的输出格式与给定的模式匹配。
- 参数
schema (Union[Dict, Type[BaseModel]]) – 输出模式,可以是 dict 或 Pydantic 类。如果是 Pydantic 类,则模型输出将是该类的对象。如果是 dict,则模型输出将是 dict。 使用 Pydantic 类,返回的属性将被验证,而使用 dict 则不会。
include_raw (bool) – 如果为 False,则仅返回已解析的结构化输出。如果在模型输出解析期间发生错误,则会引发错误。 如果为 True,则将返回原始模型响应 (BaseMessage) 和已解析的模型响应。如果在输出解析期间发生错误,则会捕获该错误并返回。最终输出始终是一个带有键 “raw”、“parsed” 和 “parsing_error” 的 dict。
kwargs (Any) –
- 返回值
一个 Runnable,它接受任何 ChatModel 输入。输出类型取决于 include_raw 和 schema。
- 如果 include_raw 为 True,则输出是一个带有键的 dict
raw: BaseMessage, parsed: Optional[_DictOrPydantic], parsing_error: Optional[BaseException],
如果 include_raw 为 False 且 schema 是 Dict,则 runnable 输出一个 Dict。如果 include_raw 为 False 且 schema 是 Type[BaseModel],则 runnable 输出一个 BaseModel。
- 返回类型
Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], Union[Dict, BaseModel]]
- 示例:Pydantic 模式 (include_raw=False)
from langchain_aws.chat_models.bedrock import ChatBedrock from langchain_core.pydantic_v1 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_llm = llm.with_structured_output(AnswerWithJustification) structured_llm.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 langchain_core.pydantic_v1 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_llm = llm.with_structured_output(AnswerWithJustification, include_raw=True) structured_llm.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 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"] } } llm =ChatBedrock( model_id="anthropic.claude-3-sonnet-20240229-v1:0", model_kwargs={"temperature": 0.001}, ) # type: ignore[call-arg] structured_llm = llm.with_structured_output(schema) structured_llm.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.' # }