langchain_anthropic.chat_models.ChatAnthropicMessages¶
注意
ChatAnthropicMessages实现了标准Runnable 接口。🏃
Runnable 接口具有在可运行对象上可用的额外方法,例如with_types、with_retry、assign、bind、get_graph等。
- class langchain_anthropic.chat_models.ChatAnthropicMessages[source]¶
- 
自版本0.1.0以来已弃用: 请使用 ChatAnthropic。- param anthropic_api_key: Optional[SecretStr]= None (别名 'api_key')¶
- 如果未提供,则自动从环境变量ANTHROPIC_API_KEY中读取。 - 约束
- 类型 = 字符串 
- 只写 = True 
- 格式 = 密码 
 
 
 - param anthropic_api_url: Optional[str] = None (别名 'base_url')¶
- API请求的基准URL。只有在使用代理或服务模拟器时才指定。 - 如果没有传递值,且已设置环境变量 ANTHROPIC_BASE_URL,则将从该变量读取值。 
 - param cache: Union[BaseCache, bool, None] = None¶
- 是否缓存响应。 - 如果为真,将使用全局缓存。 
- 如果为假,将不使用缓存。 
- 如果为None,则会根据是否存在全局缓存来使用缓存,否则不使用缓存。 
- 如果为BaseCache的实例,将使用提供的缓存。 
 - 目前不支持为模型的流方法提供缓存。 
 - param callback_manager: Optional[BaseCallbackManager] = None¶
- (弃用)添加到运行跟踪的回调管理器。 
 - param callbacks :Callbacks = None¶
- 添加到运行跟踪的回调。 
 - param custom_get_token_ids :Optional[Callable[[str],List[int]]] = None¶
- 用于计数的可选编码器。 
 - param default_headers: Optional[Mapping[str, str]] = None¶
- 传递给Anthropic客户端的头部信息,将用于每个API调用。 
 - param default_request_timeout: Optional[float] = None (alias 'timeout')¶
- Anthropic Completion API请求的超时时间。 
 - param max_retries: int = 2¶
- 允许对发送给Anthropic Completion API的请求进行重试的次数。 
 - param max_tokens: int = 1024 (alias 'max_tokens_to_sample')¶
- 表示每次生成预测的单词数量。 
 - param metadata: Optional[Dict[str, Any]] = None¶
- 添加到运行跟踪的元数据。 
 - param model: str [Required] (alias 'model_name')¶
- 要使用的模型名称。 
 - param model_kwargs: Dict[str, Any] [Optional]¶
 - param rate_limiter: Optional[BaseRateLimiter] = None¶
- 可选的速率限制器,用于限制请求数量。 
 - param stop_sequences: Optional[List[str]] = None (alias 'stop')¶
- 默认停止序列。 
 - param stream_usage: bool = True¶
- 是否在流式输出中包含使用元数据。如果为真,流过程中将生成包含使用元数据的额外消息块。 
 - param streaming: bool = False¶
- 是否使用流功能。 
 - param tags: Optional[List[str]] = None¶
- 添加到运行跟踪的标签。 
 - param temperature: Optional[float] = None¶
- 一个非负浮点数,用于调整生成过程中的随机程度。 
 - param top_k: Optional[int] = None¶
- 在每一步中考虑的最可能令牌的数量。 
 - 参数top_p: 可选 [float ] = None¶
- 每一步考虑的令牌的总概率质量。 
 - 参数verbose: bool [可选]¶
- 是否打印输出响应文本。 
 - __call__(messages: List[BaseMessage], stop: 可选[List[str]], callbacks: 可选[联合[BaseCallbackHandler], BaseCallbackManager] = None**kwargs: Any) BaseMessage¶
- 已废弃(自langchain-core==0.1.7版本以来): 请使用 - invoke代替。- 参数
- messages (列表[BaseMessage]) – 
- stop (可选[列表[str]]) – 
- callbacks (可选[联合[BaseCallbackHandler], BaseCallbackManager]]) – 
- kwargs (任何) – 
 
- 返回类型
 
 - async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) List[Output]¶
- 默认实现通过asyncio.gather并行运行runnable.invoke。 - 默认的批量实现对I/O密集型runnable运行效果良好。 - 如果子类能够更有效地批量处理,则应覆盖此方法;例如,如果底层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]]]¶
- 并行地在输入列表上运行发出,并按完成顺序产生结果。 - 参数
- inputs (Sequence[Input]) – Runnable的输入列表。 
- config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 在调用Runnable时使用的配置。配置支持如’tags’、‘metadata’(用于跟踪目的)、‘max_concurrency’(用于控制并行工作多少)等标准键。请参阅RunnableConfig获取更多详细信息。默认为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的模型以使用批量调用。 - 以下情况下使用此方法:
- 利用批量调用, 
- 从模型获取的输出不仅仅是最顶尖的生成值。 
- 正在构建不依赖于底层语言模型的通用链
- 类型(例如,纯文本完成模型与聊天模型)。 
 
 
 - 参数
- 消息(列表[列表[BaseMessage]]) - 消息的列表。 
- stop(可选[列表[str]]) - 在生成时使用的停用词。模型输出在第一次出现这些子串之一时被截断。 
- callbacks(可选[Union[列表[BaseCallbackHandler], BaseCallbackManager]]) - 需要传递的回调函数。用于在生成过程中执行附加功能,如日志记录或流输出。 
- **kwargs(任意) - 任意额外的关键字参数。这些通常传递给模型提供者的API调用。 
- tags(可选[列表[str]]) - 
- metadata(可选[Dict[str, Any]]) - 
- run_name(可选[str]) - 
- run_id(可选[UUID]) - 
- **kwargs - 
 
- 返回
- 一个LLMResult对象,包含每个输入的候选生成列表以及附加的模型提供者特定的输出。
- 提示和额外模型提供者特定的输出。 
 
- 返回类型
 
 - async agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) LLMResult¶
- 异步传递一系列提示并返回模型生成结果。 - 此方法应适用于公开批量API的模型以使用批量调用。 - 以下情况下使用此方法:
- 利用批量调用, 
- 从模型获取的输出不仅仅是最顶尖的生成值。 
- 正在构建不依赖于底层语言模型的通用链
- 类型(例如,纯文本完成模型与聊天模型)。 
 
 
 - 参数
- 提示 (列表[PromptValue]) – PromptValues 的列表。PromptValue 是一个可以转换为与任何语言模型格式相匹配的对象(纯文本生成模型使用字符串,聊天模型使用 BaseMessages)。 
- stop(可选[列表[str]]) - 在生成时使用的停用词。模型输出在第一次出现这些子串之一时被截断。 
- callbacks(可选[Union[列表[BaseCallbackHandler], BaseCallbackManager]]) - 需要传递的回调函数。用于在生成过程中执行附加功能,如日志记录或流输出。 
- **kwargs(任意) - 任意额外的关键字参数。这些通常传递给模型提供者的API调用。 
 
- 返回
- 一个LLMResult对象,包含每个输入的候选生成列表以及附加的模型提供者特定的输出。
- 提示和额外模型提供者特定的输出。 
 
- 返回类型
 
 - 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 (可选[列表[str]]) – 
- kwargs (任何) – 
 
- 返回类型
 
 - async apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) str¶
- 自 langchain-core==0.1.7 版本以来已弃用: 请使用 - ainvoke。- 参数
- text (str) – 
- stop (Optional[Sequence[str]]) – 
- kwargs (任何) – 
 
- 返回类型
- str 
 
 - async apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, *, kwargs: Any) BaseMessage¶
- 自 langchain-core==0.1.7 版本以来已弃用: 请使用 - ainvoke。- 参数
- messages (列表[BaseMessage]) – 
- stop (Optional[Sequence[str]]) – 
- kwargs (任何) – 
 
- 返回类型
 
 - as_tool(args_schema: Optional[Type[BaseModel] = None, *, name: Optional[str] = None, description: Optional[str] = None, arg_types: Optional[Dict[str, Type]] = None) BaseTool¶
- 测试版 - 此API处于测试版,未来可能会有所变化。 - 从可运行对象创建BaseTool。 - as_tool将从Runnable中创建一个具有名称、描述和- args_schema的BaseTool实例。尽可能地,从- runnable.get_input_schema推断出模式。作为替代(例如,如果Runnable接受一个字典作为输入且特定的字典键未指定类型),则可以直接使用- args_schema指定模式。您还可以传递- arg_types来仅指定所需参数及其类型。- 参数
- args_schema (可选[类型[BaseModel]]) – 工具的规范。默认为None。 
- name (可选[字符串]) – 工具的名称。默认为None。 
- description (可选[字符串]) – 工具的描述。默认为None。 
- arg_types (可选[字典[字符串, 类型]]) – 字典参数名到类型的映射。默认为None。 
 
- 返回
- BaseTool实例。 
- 返回类型
 - 类型化字典输入 - from typing import List from typing_extensions import TypedDict from langchain_core.runnables import RunnableLambda class Args(TypedDict): a: int b: List[int] def f(x: Args) -> str: return str(x["a"] * max(x["b"])) runnable = RunnableLambda(f) as_tool = runnable.as_tool() as_tool.invoke({"a": 3, "b": [1, 2]}) - dict输入,通过- args_schema指定架构- from typing import Any, Dict, List from langchain_core.pydantic_v1 import BaseModel, Field from langchain_core.runnables import RunnableLambda def f(x: Dict[str, Any]) -> str: return str(x["a"] * max(x["b"])) class FSchema(BaseModel): """Apply a function to an integer and list of integers.""" a: int = Field(..., description="Integer") b: List[int] = Field(..., description="List of ints") runnable = RunnableLambda(f) as_tool = runnable.as_tool(FSchema) as_tool.invoke({"a": 3, "b": [1, 2]}) - dict输入,通过- arg_types指定架构- from typing import Any, Dict, List from langchain_core.runnables import RunnableLambda def f(x: Dict[str, Any]) -> str: return str(x["a"] * max(x["b"])) runnable = RunnableLambda(f) as_tool = runnable.as_tool(arg_types={"a": int, "b": List[int]}) as_tool.invoke({"a": 3, "b": [1, 2]}) - 字符串输入 - from langchain_core.runnables import RunnableLambda def f(x: str) -> str: return x + "a" def g(x: str) -> str: return x + "z" runnable = RunnableLambda(f) | g as_tool = runnable.as_tool() as_tool.invoke("b") - 新版本0.2.14中引入。 
 - async astream(input: LanguageModelInput, config: Optional[RunnableConfig] = None, **kwargs: Any) AsyncIterator[BaseMessageChunk]
- astream的默认实现,调用ainvoke。子类应覆盖此方法以支持流式输出。 - 参数
- input (LanguageModelInput) – Runnable的输入。 
- config (可选[RunnableConfig]) – 用于Runnable的配置。默认为None。 
- kwargs (任何类型) – 传递给Runnable的额外关键字参数。 
- stop (可选[列表[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]]¶
- 测试版 - 此API处于测试版,未来可能会有所变化。 - 生成事件流。 - 用于创建一个迭代器,遍历StreamEvents,这些事件提供了关于Runnable进度(包括中间结果的事件)的实时信息。 - StreamEvent是一个包含以下结构的字典 - event: str - 事件名称的格式为
- 格式:on_[runnable_type]_(start|stream|end)。 
 
- name: str - 触发事件的Runnable的名称。
- run_id: str - 与触发事件的Runnable的给定执行相关联的随机生成的ID。
- 作为父Runnable执行部分调用而被调用的子Runnable将分配其自己的唯一ID。 
 
- parent_ids: List[str] - 生成该事件的所有父Runnable的ID。
- 根Runnable将有一个空列表。父ID的顺序是从根到直接父级。仅适用于API的v2版本。API的v1版本将返回一个空列表。 
 
- tags: Optional[List[str]] - 触发事件的Runnable的标签。
 
- metadata: Optional[Dict[str, Any]] - 触发事件的Runnable的元数据。
 
- data: Dict[str, Any]
 - 下面是一个表格,说明了可能由各种链发射的一些事件。为了简洁,省略了元数据字段。表格之后包含了链定义。 - 注意 此参考表是针对模式V2版本的。 - 事件 - 名称 - 块 - 输入 - 输出 - on_chat_model_start - [模型名称] - {“messages”: [[系统消息,人类消息]]} - on_chat_model_stream - [模型名称] - AIMessageChunk(content=”hello”) - on_chat_model_end - [模型名称] - {“messages”: [[系统消息,人类消息]]} - 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 - [文档(…)] - “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”} - [文档(…), ..] - on_prompt_start - [模板名称] - {“question”: “hello”} - on_prompt_end - [模板名称] - {“question”: “hello”} - ChatPromptValue(messages: [系统消息, …]) - 除了标准事件之外,用户还可以调度自定义事件(请参见下面的示例)。 - 自定义事件仅在API的v2版本中公开! - 自定义事件的以下格式 - 属性 - 类型 - 描述 - 名称 - str - 事件的用户定义名称。 - 数据 - 任何 - 与事件关联的数据。这可以是一切,尽管我们建议使其可序列化为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} - 提示: - 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 (可选[元组[str]]) – 仅包括具有匹配名称的可执行组件的事件。 
- include_types (可选[元组[str]]) – 仅包括具有匹配类型的可执行组件的事件。 
- include_tags (可选[元组[str]]) – 仅包括具有匹配标签的可执行组件的事件。 
- exclude_names (可选[元组[str]]) – 排除具有匹配名称的可执行组件的事件。 
- exclude_types (可选[元组[str]]) – 排除具有匹配类型的可执行组件的事件。 
- exclude_tags (可选[元组[str]]) – 排除具有匹配标签的可执行组件的事件。 
- kwargs (任意) – 传递给 Runnable 的额外关键字参数。这些将通过 astream_log 传递,因为 astream_events 的实现基于 astream_log。 
 
- 产生结果
- 异步流式传输的 StreamEvents。 
- 抛出异常
- NotImplementedError – 如果版本不是 v1 或 v2。 
- 返回类型
- AsyncIterator[Union[langchain_core.runnables.schema.StandardStreamEvent, langchain_core.runnables.schema.CustomStreamEvent]] 
 
 - batch(inputs: List[Input], config: Optional[Union[langchain_core.runnables.config.RunnableConfig, List[langchain_core.runnables.config.RunnableConfig]]] = None, *, return_exceptions: bool = False, *kwargs: Optional[Any]) List[Output]¶
- 默认实现在并行中运行 invoke 使用线程池执行程序。 - 默认的批量实现对I/O密集型runnable运行效果良好。 - 如果子类能够更有效地批量处理,则应覆盖此方法;例如,如果底层Runnable使用支持批量模式的API。 - 参数
- inputs (列表[输入]) – 
- config (可选[Unionlangchain_core.runnables.config.RunnableConfig], 列表[langchain_core.runnables.config.RunnableConfig]]]) – 
- return_exceptions (布尔值) – 
- kwargs (可选任意]) – 
 
- 返回类型
- 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]]]¶
- 在输入列表上并行运行调用,按完成顺序生成结果。 - 参数
- inputs (Sequence[Input]) – 
- config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 
- return_exceptions (布尔值) – 
- kwargs (可选任意]) – 
 
- 返回类型
- Iterator[Tuple[int, Union[Output, Exception]]] 
 
 - bind_tools(tools: Sequence[Union[Dict[str, Any], Type, Callable, BaseTool]], *, tool_choice: Optional[Union[Dict[str, str], Literal['any', 'auto'], str]] = None, **kwargs: Any) Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]], BaseMessage]¶
- 将工具类对象绑定到当前聊天模型。 - 参数
- tools: 一组用于绑定到当前聊天模型的工具定义列表。
- 支持Anthropic格式工具模式以及任何由 - langchain_core.utils.function_calling.convert_to_openai_tool()处理工具定义。
- tool_choice: 必须要求模型调用的工具。
- 选项包括
- 工具名称(字符串):调用对应工具; 
- code class="docutils literal notranslate">"auto"或None:自动选择工具(包括没有工具); 
- code class="docutils literal notranslate">"any":强制至少调用一个工具; 
- 或者形式为
- code class="docutils literal notranslate">{"type": "tool", "name": "tool_name"},或 - {"type: "any"},或- {"type: "auto"};
 
 
 
- kwargs: 将任何额外的参数直接传递到
- self.bind(**kwargs).
 
- 示例
- from langchain_anthropic import ChatAnthropic from langchain_core.pydantic_v1 import BaseModel, Field class GetWeather(BaseModel): '''Get the current weather in a given location''' location: str = Field(..., description="The city and state, e.g. San Francisco, CA") class GetPrice(BaseModel): '''Get the price of a specific product.''' product: str = Field(..., description="The product to look up.") llm = ChatAnthropic(model="claude-3-opus-20240229", temperature=0) llm_with_tools = llm.bind_tools([GetWeather, GetPrice]) llm_with_tools.invoke("what is the weather like in San Francisco",) # -> AIMessage( # content=[ # {'text': '<thinking> 
 - 根据用户的问题,需要调用的相关函数是GetWeather,这需要“location”参数。 - 用户直接指定地点为“旧金山”。由于旧金山是一个知名城市,我可以合理推断他们指的是旧金山,CA,无需指定州。 - 提供了所有必需的参数,因此我可以继续进行API调用。 </thinking>’,‘type’: ‘text’}, - # {‘text’: None,‘type’: ‘tool_use’,‘id’: ‘toolu_01SCgExKzQ7eqSkMHfygvYuu’,‘name’: ‘GetWeather’,‘input’: {‘location’: ‘San Francisco, CA’}} # ], # response_metadata={‘id’: ‘msg_01GM3zQtoFv8jGQMW7abLnhi’,‘model’: ‘claude-3-opus-20240229’,‘stop_reason’: ‘tool_use’,‘stop_sequence’: None,‘usage’: {‘input_tokens’: 487,‘output_tokens’: 145}}, # id=’run-87b1331e-9251-4a68-acef-f0a018b639cc-0’ # ) - 示例 — 使用tool_choice ‘any’强制工具调用
- from langchain_anthropic import ChatAnthropic from langchain_core.pydantic_v1 import BaseModel, Field class GetWeather(BaseModel): '''Get the current weather in a given location''' location: str = Field(..., description="The city and state, e.g. San Francisco, CA") class GetPrice(BaseModel): '''Get the price of a specific product.''' product: str = Field(..., description="The product to look up.") llm = ChatAnthropic(model="claude-3-opus-20240229", temperature=0) llm_with_tools = llm.bind_tools([GetWeather, GetPrice], tool_choice="any") llm_with_tools.invoke("what is the weather like in San Francisco",) 
- 示例 — 使用tool_choice ‘<name_of_tool>’强制调用特定工具
- from langchain_anthropic import ChatAnthropic from langchain_core.pydantic_v1 import BaseModel, Field class GetWeather(BaseModel): '''Get the current weather in a given location''' location: str = Field(..., description="The city and state, e.g. San Francisco, CA") class GetPrice(BaseModel): '''Get the price of a specific product.''' product: str = Field(..., description="The product to look up.") llm = ChatAnthropic(model="claude-3-opus-20240229", temperature=0) llm_with_tools = llm.bind_tools([GetWeather, GetPrice], tool_choice="GetWeather") llm_with_tools.invoke("what is the weather like in San Francisco",) 
 - 参数
- tools (序列[并集[字典[字符串,任何],类型,可调用,BaseTool]]) – 
- tool_choice (可选[并集[字典[字符串,字符串],字面量['any','auto'],字符串]]) – 
- kwargs (任何) – 
 
- 返回类型
- Runnable [ 并集 [ PromptValue , 字符串 , 序列 [ 并集 [ BaseMessage , 列表 [ 字符串 ] , 元组 [ 字符串 , 字符串 ] , 字符串 , 字典 [ 字符串 , 任何 ] ] ] ] , BaseMessage ] ] 
 
 - call_as_llm(message: str,stop: Optional[List[str]] = None,**kwargs: Any) str¶
- 已废弃(自langchain-core==0.1.7版本以来): 请使用 - invoke代替。- 参数
- message (字符串) – 
- stop (可选[列表[str]]) – 
- kwargs (任何) – 
 
- 返回类型
- 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]¶
- 配置支持在运行时设置的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]¶
- 在运行时配置特定的可运行对象字段。 - 参数
- **kwargs (Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) – 要配置的 ConfigurableField 实例的字典。 
- 返回
- 配置了字段的新的可运行对象。 
- 返回类型
- 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[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的模型以使用批量调用。 - 以下情况下使用此方法:
- 利用批量调用, 
- 从模型获取的输出不仅仅是最顶尖的生成值。 
- 正在构建不依赖于底层语言模型的通用链
- 类型(例如,纯文本完成模型与聊天模型)。 
 
 
 - 参数
- 消息(列表[列表[BaseMessage]]) - 消息的列表。 
- stop(可选[列表[str]]) - 在生成时使用的停用词。模型输出在第一次出现这些子串之一时被截断。 
- callbacks(可选[Union[列表[BaseCallbackHandler], BaseCallbackManager]]) - 需要传递的回调函数。用于在生成过程中执行附加功能,如日志记录或流输出。 
- **kwargs(任意) - 任意额外的关键字参数。这些通常传递给模型提供者的API调用。 
- tags(可选[列表[str]]) - 
- metadata(可选[Dict[str, Any]]) - 
- run_name(可选[str]) - 
- run_id(可选[UUID]) - 
- **kwargs - 
 
- 返回
- 一个LLMResult对象,包含每个输入的候选生成列表以及附加的模型提供者特定的输出。
- 提示和额外模型提供者特定的输出。 
 
- 返回类型
 
 - generate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) LLMResult¶
- 将一串提示传递给模型并返回模型生成的内容。 - 此方法应适用于公开批量API的模型以使用批量调用。 - 以下情况下使用此方法:
- 利用批量调用, 
- 从模型获取的输出不仅仅是最顶尖的生成值。 
- 正在构建不依赖于底层语言模型的通用链
- 类型(例如,纯文本完成模型与聊天模型)。 
 
 
 - 参数
- 提示 (列表[PromptValue]) – PromptValues 的列表。PromptValue 是一个可以转换为与任何语言模型格式相匹配的对象(纯文本生成模型使用字符串,聊天模型使用 BaseMessages)。 
- stop(可选[列表[str]]) - 在生成时使用的停用词。模型输出在第一次出现这些子串之一时被截断。 
- callbacks(可选[Union[列表[BaseCallbackHandler], BaseCallbackManager]]) - 需要传递的回调函数。用于在生成过程中执行附加功能,如日志记录或流输出。 
- **kwargs(任意) - 任意额外的关键字参数。这些通常传递给模型提供者的API调用。 
 
- 返回
- 一个LLMResult对象,包含每个输入的候选生成列表以及附加的模型提供者特定的输出。
- 提示和额外模型提供者特定的输出。 
 
- 返回类型
 
 - get_num_tokens(text: str) int¶
- 获取文本中存在的标记数量。 - 用于检查输入是否适合模型的上下文窗口。 - 参数
- text (str) – 要分词的字符串输入。 
- 返回
- 文本中的标记数量。 
- 返回类型
- 整型 
 
 - get_num_tokens_from_messages(messages: List[BaseMessage]) int¶
- 获取消息中的标记数量。 - 用于检查输入是否适合模型的上下文窗口。 - 参数
- messages (List[BaseMessage]) – 要分词的消息输入。 
- 返回
- 消息中标记数量的总和。 
- 返回类型
- 整型 
 
 - get_token_ids(text: str) List[int]¶
- 返回文本中标记的有序ID。 - 参数
- text (str) – 要分词的字符串输入。 
- 返回
- 按照在文本中出现的顺序,返回与文本中的标记对应的一组ID。
- 的列表。 
 
- 返回类型
- 列表[int] 
 
 - invoke(input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) BaseMessage¶
- 将单个输入转换为输出。覆盖以实现。 - 参数
- input (LanguageModelInput) – Runnable的输入。 
- config (可选[RunnableConfig]) – 在调用可运行时使用的配置。配置支持像‘tags’、‘metadata’这样的标准键,用于跟踪目的,以及像‘max_concurrency’这样的键,用于控制并行工作的数量,以及其他键。有关更多详细信息,请参阅RunnableConfig。 
- stop (可选[列表[str]]) – 
- kwargs (任何) – 
 
- 返回
- Runnable的输出。 
- 返回类型
 
 - predict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) str¶
- 已废弃(自langchain-core==0.1.7版本以来): 请使用 - invoke代替。- 参数
- text (str) – 
- stop (Optional[Sequence[str]]) – 
- kwargs (任何) – 
 
- 返回类型
- str 
 
 - predict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) BaseMessage
- 已废弃(自langchain-core==0.1.7版本以来): 请使用 - invoke代替。- 参数
- messages (列表[BaseMessage]) – 
- stop (Optional[Sequence[str]]) – 
- kwargs (任何) – 
 
- 返回类型
 
 - stream(input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) Iterator[BaseMessageChunk]
- stream的默认实现,调用invoke。如果子类支持流式输出,应覆盖此方法。 - 参数
- input (LanguageModelInput) – Runnable的输入。 
- config (可选[RunnableConfig]) – 用于Runnable的配置。默认为None。 
- kwargs (任何类型) – 传递给Runnable的额外关键字参数。 
- stop (可选[列表[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]]¶
- 返回符合给定架构的输出的模型包装器。 - 参数
- 架构 (Union[Dict, Type[BaseModel]]) – - 输出架构。可以传入以下类型:
- Anthropic 工具架构, 
- OpenAI 函数/工具架构, 
- JSON 架构, 
- TypedDict 类(自 0.1.22 版本支持), 
- 或 Pydantic 类。 
 
 - 如果 - 架构是 Pydantic 类,则模型输出将为此类的一个 Pydantic 实例,并且模型生成的字段将由 Pydantic 类进行验证。否则,模型输出将是一个 dict,并且不会进行验证。有关如何为 Pydantic 或 TypedDict 类指定类型和架构字段描述的更多信息,请参阅- langchain_core.utils.function_calling.convert_to_openai_tool()。- 变更于版本 0.1.22: 添加了对 TypedDict 类的支持。 
- include_raw (bool) – 如果为 False,则只返回解析后的结构化输出。如果模型输出解析过程中发生错误,则将引发错误。如果为 True,则同时返回原始模型响应(BaseMessage)和解析后的模型响应。如果输出解析过程中发生错误,则将捕获并返回该错误。最终输出始终是一个具有“raw”,“parsed”和“parsing_error”键的 dict。 
- kwargs (任何) – 
 
- 返回
- 一个接受与 - langchain_core.language_models.chat.BaseChatModel相同输入的可运行对象。- 如果 - include_raw为 False 且- 架构是 Pydantic 类,则 Runnable 的输出为- 架构的一个实例(即 Pydantic 对象)。- 否则,如果 - include_raw为 False,则 Runnable 的输出是一个 dict。- 如果 include_raw为 True,则 Runnable 的输出是一个具有以下键的 dict
- "raw": BaseMessage
- "parsed": 如果发生解析错误,则为 None,否则类型依赖于- 架构,如上所述。
- "parsing_error": Optional[BaseException]
 
 
- 如果 
- 返回类型
- 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_anthropic import ChatAnthropic 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 = ChatAnthropic(model="claude-3-opus-20240229", 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_anthropic import ChatAnthropic 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 = ChatAnthropic(model="claude-3-opus-20240229", 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_anthropic import ChatAnthropic 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 = ChatAnthropic(model="claude-3-opus-20240229", temperature=0) 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.' # }