langchain_community.chat_models.anthropic.ChatAnthropic

注意

ChatAnthropic 实现了标准的 Runnable 接口。🏃

Runnable 接口 在可运行对象上还有其他可用方法,例如 with_types, with_retry, assign, bind, get_graph 等。

class langchain_community.chat_models.anthropic.ChatAnthropic[源代码]

基类: BaseChatModel, _AnthropicCommon

0.0.28 版本后已弃用: 请使用 langchain_anthropic.ChatAnthropic 代替。

Anthropic 聊天大语言模型。

要使用此模型,您应该安装 anthropic Python 包,并将环境变量 ANTHROPIC_API_KEY 设置为您的 API 密钥,或者将其作为命名参数传递给构造函数。

示例

import anthropic
from langchain_community.chat_models import ChatAnthropic
model = ChatAnthropic(model="<model_name>", anthropic_api_key="my-api-key")
param AI_PROMPT: Optional[str] = None
param HUMAN_PROMPT: Optional[str] = None
param anthropic_api_key: Optional[SecretStr] = None
约束
  • 类型 = 字符串

  • writeOnly = True

  • 格式 = 密码

param anthropic_api_url: Optional[str] = None
param cache: Union[BaseCache, bool, None] = None

是否缓存响应。

  • 如果为 true,将使用全局缓存。

  • 如果为 false,将不使用缓存。

  • 如果为 None,如果已设置全局缓存,则使用全局缓存,否则不使用缓存。

  • 如果是 BaseCache 的实例,将使用提供的缓存。

模型流式处理方法目前不支持缓存。

param callback_manager: Optional[BaseCallbackManager] = None

[已弃用] 要添加到运行轨迹的回调管理器。

param callbacks: Callbacks = None

要添加到运行轨迹的回调。

param count_tokens: Optional[Callable[[str], int]] = None
param custom_get_token_ids: Optional[Callable[[str], List[int]]] = None

用于计算 token 的可选编码器。

param default_request_timeout: Optional[float] = None

到 Anthropic Completion API 的请求超时时间。默认为 600 秒。

param max_retries: int = 2

发送到 Anthropic Completion API 的请求允许的最大重试次数。

param max_tokens_to_sample: int = 256 (别名 'max_tokens')

表示每次生成要预测的 token 数量。

param metadata: Optional[Dict[str, Any]] = None

要添加到运行轨迹的元数据。

param model: str = 'claude-2' (别名 'model_name')

要使用的模型名称。

param model_kwargs: Dict[str, Any] [可选]
param rate_limiter: Optional[BaseRateLimiter] = None

可选的速率限制器,用于限制请求数量。

param streaming: bool = False

是否流式传输结果。

param tags: Optional[List[str]] = None

要添加到运行轨迹的标签。

param temperature: Optional[float] = None

一个非负浮点数,用于调整生成中的随机程度。

param top_k: Optional[int] = None

每一步要考虑的最有可能的 token 数量。

param top_p: Optional[float] = None

每一步要考虑的 token 的总概率质量。

param verbose: bool [可选]

是否打印响应文本。

__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) BaseMessage

自 langchain-core==0.1.7 版本后已弃用: 请使用 invoke 代替。

参数
返回类型

BaseMessage

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 的其他关键字参数。

产生

输入索引和来自 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 的模型进行的批量调用。

当您想要执行以下操作时,请使用此方法
  1. 利用批量调用,

  2. 需要比模型仅生成的最佳值更多的输出,

  3. 正在构建对底层语言模型不可知的链

    类型(例如,纯文本补全模型与聊天模型)。

参数
  • messages (List[List[BaseMessage]]) – 消息列表 (List[List[BaseMessage]]) – 消息的列表的列表。

  • stop (Optional[List[str]]) – stop (Optional[List[str]]) – 生成时使用的停止词。模型输出将在首次出现任何这些子字符串时被截断。

  • callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 要传递的回调函数。用于在整个生成过程中执行额外的功能,例如日志记录或流式传输。

  • **kwargs (Any) – **kwargs (Any) – 任意额外的关键字参数。这些通常会传递给模型提供商 API 调用。

  • tags (Optional[List[str]]) – 标签 (Optional[List[str]]) –

  • metadata (Optional[Dict[str, Any]]) – 元数据 (Optional[Dict[str, Any]]) –

  • run_name (Optional[str]) – 运行名称 (Optional[str]) –

  • run_id (Optional[UUID]) – 运行 ID (Optional[UUID]) –

  • **kwargs – **kwargs –

返回

An LLMResult, which contains a list of candidate Generations for each input

prompt and additional model provider-specific output.

返回类型

LLMResult

async agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) LLMResult

Asynchronously pass a sequence of prompts and return model generations.

此方法应利用为公开批量 API 的模型进行的批量调用。

当您想要执行以下操作时,请使用此方法
  1. 利用批量调用,

  2. 需要比模型仅生成的最佳值更多的输出,

  3. 正在构建对底层语言模型不可知的链

    类型(例如,纯文本补全模型与聊天模型)。

参数
  • prompts (List[PromptValue]) – prompts (List[PromptValue]) – PromptValue 的列表。PromptValue 是一个可以转换为匹配任何语言模型格式的对象(纯文本生成模型的字符串和聊天模型中的 BaseMessages)。

  • stop (Optional[List[str]]) – stop (Optional[List[str]]) – 生成时使用的停止词。模型输出将在首次出现任何这些子字符串时被截断。

  • callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 要传递的回调函数。用于在整个生成过程中执行额外的功能,例如日志记录或流式传输。

  • **kwargs (Any) – **kwargs (Any) – 任意额外的关键字参数。这些通常会传递给模型提供商 API 调用。

返回

An LLMResult, which contains a list of candidate Generations for each input

prompt and additional model provider-specific output.

返回类型

LLMResult

async ainvoke(input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) BaseMessage

ainvoke 的默认实现,从线程调用 invoke。

即使 Runnable 没有实现 invoke 的原生异步版本,默认实现也允许使用异步代码。

如果子类可以异步运行,则应覆盖此方法。

参数
  • input (LanguageModelInput) – input (LanguageModelInput) –

  • config (Optional[RunnableConfig]) – config (Optional[RunnableConfig]) –

  • stop (Optional[List[str]]) –

  • kwargs (Any) –

返回类型

BaseMessage

async apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) str

Deprecated since version langchain-core==0.1.7: 请使用 ainvoke 代替。

参数
  • text (str) – text (str) –

  • stop (Optional[Sequence[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]]) – stop (Optional[Sequence[str]]) –

  • kwargs (Any) –

返回类型

BaseMessage

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

This API is in beta and may change in the future.

Create a BaseTool from a Runnable.

as_tool will instantiate a BaseTool with a name, description, and args_schema from a Runnable. Where possible, schemas are inferred from runnable.get_input_schema. Alternatively (e.g., if the Runnable takes a dict as input and the specific dict keys are not typed), the schema can be specified directly with args_schema. You can also pass arg_types to just specify the required arguments and their types.

参数
  • args_schema (Optional[Type[BaseModel]]) – args_schema (Optional[Type[BaseModel]]) – 工具的模式。默认为 None。

  • name (Optional[str]) – name (Optional[str]) – 工具的名称。默认为 None。

  • description (Optional[str]) – description (Optional[str]) – 工具的描述。默认为 None。

  • arg_types (Optional[Dict[str, Type]]) – arg_types (Optional[Dict[str, Type]]) – 参数名称到类型的字典。默认为 None。

返回

A BaseTool instance.

返回类型

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 input, specifying schema via 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 input, specifying schema via 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: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) AsyncIterator[BaseMessageChunk]

Default implementation of astream, which calls ainvoke. Subclasses should override this method if they support streaming output.

参数
  • 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

This API is in beta and may change in the future.

Generate a stream of events.

Use to create an iterator over StreamEvents that provide real-time information about the progress of the Runnable, including StreamEvents from intermediate results.

A StreamEvent is a dictionary with the following schema

  • event: str - Event names are of the

    format: on_[runnable_type]_(start|stream|end).

  • name: str - The name of the Runnable that generated the event.

  • run_id: str - randomly generated ID associated with the given execution of

    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] - The IDs of the parent runnables that

    generated the event. The root Runnable will have an empty list. The order of the parent IDs is from the root to the immediate parent. Only available for v2 version of the API. The v1 version of the API will return an empty list.

  • tags: Optional[List[str]] - The tags of the Runnable that generated

    the event.

  • metadata: Optional[Dict[str, Any]] - The metadata of the Runnable

    that generated the event.

  • data: Dict[str, Any]

Below is a table that illustrates some evens that might be emitted by various chains. Metadata fields have been omitted from the table for brevity. Chain definitions have been included after the table.

ATTENTION This reference table is for the V2 version of the schema.

event

name

chunk

input

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]

‘Hello’

on_llm_end

[model name]

‘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

[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, …])

In addition to the standard events, users can also dispatch custom events (see example below).

Custom events will be only be surfaced with in the v2 version of the API!

A custom event has following format

Attribute

Type

Description

name

str

A user defined name for the event.

data

Any

The data associated with the event. This can be anything, though we suggest making it JSON serializable.

Here are declarations associated with the standard events shown above

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": [],
    },
]

Example: Dispatch Custom Event

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']) – 要使用的模式版本,可以是 v2v1。用户应使用 v2v1是为了向后兼容,将在 0.4.0 版本中弃用。在 API 稳定之前,不会分配默认值。自定义事件仅在 v2 中显示。

  • include_names (Optional[Sequence[str]]) – include_names (Optional[Sequence[str]]) – 仅包含来自具有匹配名称的 runnables 的事件。

  • include_types (Optional[Sequence[str]]) – include_types (Optional[Sequence[str]]) – 仅包含来自具有匹配类型的 runnables 的事件。

  • include_tags (Optional[Sequence[str]]) – include_tags (Optional[Sequence[str]]) – 仅包含来自具有匹配标签的 runnables 的事件。

  • exclude_names (Optional[Sequence[str]]) – exclude_names (Optional[Sequence[str]]) – 排除来自具有匹配名称的 runnables 的事件。

  • exclude_types (Optional[Sequence[str]]) – exclude_types (Optional[Sequence[str]]) – 排除来自具有匹配类型的 runnables 的事件。

  • exclude_tags (Optional[Sequence[str]]) – exclude_tags (Optional[Sequence[str]]) – 排除来自具有匹配标签的 runnables 的事件。

  • 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.

产生

StreamEvents 的异步流。

Raises

NotImplementedError – 如果版本不是 v1v2,则引发此错误。

返回类型

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 绑定的可运行对象效果良好。

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

参数
  • inputs (List[Input]) – inputs (List[Input]) –

  • config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) –

  • return_exceptions (bool) – return_exceptions (bool) –

  • kwargs (Optional[Any]) – 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]) – inputs (Sequence[Input]) –

  • config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) –

  • return_exceptions (bool) – return_exceptions (bool) –

  • kwargs (Optional[Any]) – kwargs (Optional[Any]) –

返回类型

Iterator[Tuple[int, Union[Output, Exception]]]

bind_tools(tools: Sequence[Union[Dict[str, Any], Type, Callable, BaseTool]], **kwargs: Any) Runnable[LanguageModelInput, BaseMessage]
参数
  • tools (Sequence[Union[Dict[str, Any], Type, Callable, BaseTool]]) – tools (Sequence[Union[Dict[str, Any], Type, Callable, BaseTool]]) –

  • kwargs (Any) –

返回类型

Runnable[LanguageModelInput, BaseMessage]

call_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) str

自 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[Input, Output], Callable[[], Runnable[Input, Output]]]) RunnableSerializable[Input, Output]

配置可在运行时设置的 Runnable 的备选项。

参数
  • 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
)
convert_prompt(prompt: PromptValue) str[source]
参数

prompt (PromptValue) –

返回类型

str

generate(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 的模型进行的批量调用。

当您想要执行以下操作时,请使用此方法
  1. 利用批量调用,

  2. 需要比模型仅生成的最佳值更多的输出,

  3. 正在构建对底层语言模型不可知的链

    类型(例如,纯文本补全模型与聊天模型)。

参数
  • messages (List[List[BaseMessage]]) – 消息列表 (List[List[BaseMessage]]) – 消息的列表的列表。

  • stop (Optional[List[str]]) – stop (Optional[List[str]]) – 生成时使用的停止词。模型输出将在首次出现任何这些子字符串时被截断。

  • callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 要传递的回调函数。用于在整个生成过程中执行额外的功能,例如日志记录或流式传输。

  • **kwargs (Any) – **kwargs (Any) – 任意额外的关键字参数。这些通常会传递给模型提供商 API 调用。

  • tags (Optional[List[str]]) – 标签 (Optional[List[str]]) –

  • metadata (Optional[Dict[str, Any]]) – 元数据 (Optional[Dict[str, Any]]) –

  • run_name (Optional[str]) – 运行名称 (Optional[str]) –

  • run_id (Optional[UUID]) – 运行 ID (Optional[UUID]) –

  • **kwargs – **kwargs –

返回

An LLMResult, which contains a list of candidate Generations for each input

prompt and additional model provider-specific output.

返回类型

LLMResult

generate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) LLMResult

将一系列提示传递给模型并返回模型生成结果。

此方法应利用为公开批量 API 的模型进行的批量调用。

当您想要执行以下操作时,请使用此方法
  1. 利用批量调用,

  2. 需要比模型仅生成的最佳值更多的输出,

  3. 正在构建对底层语言模型不可知的链

    类型(例如,纯文本补全模型与聊天模型)。

参数
  • prompts (List[PromptValue]) – prompts (List[PromptValue]) – PromptValue 的列表。PromptValue 是一个可以转换为匹配任何语言模型格式的对象(纯文本生成模型的字符串和聊天模型中的 BaseMessages)。

  • stop (Optional[List[str]]) – stop (Optional[List[str]]) – 生成时使用的停止词。模型输出将在首次出现任何这些子字符串时被截断。

  • callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 要传递的回调函数。用于在整个生成过程中执行额外的功能,例如日志记录或流式传输。

  • **kwargs (Any) – **kwargs (Any) – 任意额外的关键字参数。这些通常会传递给模型提供商 API 调用。

返回

An LLMResult, which contains a list of candidate Generations for each input

prompt and additional model provider-specific output.

返回类型

LLMResult

get_num_tokens(text: str) int[source]

计算 token 数量。

参数

text (str) – text (str) –

返回类型

int

get_num_tokens_from_messages(messages: List[BaseMessage]) int

获取消息中的 token 数量。

用于检查输入是否适合模型的上下文窗口。

参数

messages (List[BaseMessage]) – 要进行 token 化的消息输入。

返回

消息中 token 数量的总和。

返回类型

int

get_token_ids(text: str) List[int]

返回文本中 token 的有序 ID 列表。

参数

text (str) – 要进行 token 化的字符串输入。

返回

文本中 token 对应的 ID 列表,按照它们在文本中出现的顺序排列。

在文本中。

返回类型

List[int]

invoke(input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) BaseMessage

将单个输入转换为输出。覆盖此方法以实现自定义逻辑。

参数
  • input (LanguageModelInput) – Runnable 的输入。

  • config (Optional[RunnableConfig]) – 调用 Runnable 时使用的配置。该配置支持标准键,如用于跟踪目的的 ‘tags’、‘metadata’,用于控制并行工作量的 ‘max_concurrency’,以及其他键。请参阅 RunnableConfig 以了解更多详细信息。

  • stop (Optional[List[str]]) –

  • kwargs (Any) –

返回

Runnable 的输出。

返回类型

BaseMessage

predict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) str

自 langchain-core==0.1.7 版本后已弃用: 请使用 invoke 代替。

参数
  • text (str) – text (str) –

  • stop (Optional[Sequence[str]]) – stop (Optional[Sequence[str]]) –

  • kwargs (Any) –

返回类型

str

predict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) BaseMessage

自 langchain-core==0.1.7 版本后已弃用: 请使用 invoke 代替。

参数
  • messages (List[BaseMessage]) –

  • stop (Optional[Sequence[str]]) – stop (Optional[Sequence[str]]) –

  • kwargs (Any) –

返回类型

BaseMessage

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 可序列化表示形式。

返回类型

Union[SerializedConstructor, SerializedNotImplemented]

with_structured_output(schema: Union[Dict, Type], *, include_raw: bool = False, **kwargs: Any) Runnable[LanguageModelInput, Union[Dict, BaseModel]]

模型包装器,返回格式化为匹配给定模式的输出。

参数
  • schema (Union[Dict, Type]) –

    输出模式。可以作为以下内容传入:
    • OpenAI 函数/工具模式,

    • JSON Schema,

    • TypedDict 类(在 0.2.26 版本中添加了支持),

    • 或 Pydantic 类。

    如果 schema 是 Pydantic 类,则模型输出将是该类的 Pydantic 实例,并且模型生成的字段将由 Pydantic 类进行验证。 否则,模型输出将是一个 dict,并且不会被验证。 有关如何正确指定模式字段的类型和描述的更多信息,请参阅 langchain_core.utils.function_calling.convert_to_openai_tool()

    在 0.2.26 版本中变更: 添加了对 TypedDict 类的支持。

  • include_raw (bool) – 如果为 False,则仅返回解析后的结构化输出。 如果在模型输出解析期间发生错误,将引发该错误。 如果为 True,则将返回原始模型响应 (BaseMessage) 和解析后的模型响应。 如果在输出解析期间发生错误,它将被捕获并返回。 最终输出始终是一个带有键 “raw”、“parsed” 和 “parsing_error” 的 dict。

  • kwargs (Any) –

返回

一个 Runnable,它接受与 langchain_core.language_models.chat.BaseChatModel 相同的输入。

如果 include_raw 为 False 且 schema 是 Pydantic 类,则 Runnable 输出 schema 的实例(即 Pydantic 对象)。

否则,如果 include_raw 为 False,则 Runnable 输出一个 dict。

如果 include_raw 为 True,则 Runnable 输出一个带有以下键的 dict:
  • "raw": BaseMessage

  • "parsed": 如果存在解析错误,则为 None,否则类型取决于上面描述的 schema

  • "parsing_error": Optional[BaseException]

返回类型

Runnable[LanguageModelInput, Union[Dict, BaseModel]]

示例:Pydantic 模式 (include_raw=False)
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 = ChatModel(model="model-name", temperature=0)
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_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 = ChatModel(model="model-name", temperature=0)
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_core.pydantic_v1 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)
llm = ChatModel(model="model-name", temperature=0)
structured_llm = llm.with_structured_output(dict_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.'
# }

使用 ChatAnthropic 的示例