[已弃用] 实验性 Anthropic 工具包装器
warning
Anthropic API 已正式支持工具调用,因此不再需要此变通方法。请使用 langchain-anthropic>=0.1.15 的 ChatAnthropic。
本笔记本展示了如何使用围绕 Anthropic 的实验性包装器,为其提供工具调用和结构化输出功能。它遵循 Anthropic 的指南 此处。
该包装器可从 langchain-anthropic 包获得,还需要可选的依赖项 defusedxml 来解析来自 llm 的 XML 输出。
注意:这是一个 beta 功能,将被 Anthropic 对工具调用的正式实现所取代,但在此期间可用于测试和实验。
%pip install -qU langchain-anthropic defusedxml
from langchain_anthropic.experimental import ChatAnthropicTools
API Reference:ChatAnthropicTools
工具绑定
ChatAnthropicTools 提供了一个 bind_tools 方法,允许您将 Pydantic 模型或 BaseTools 传递给 LLM。
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
model = ChatAnthropicTools(model="claude-3-opus-20240229").bind_tools(tools=[Person])
model.invoke("I am a 27 year old named Erick")
AIMessage(content='', additional_kwargs={'tool_calls': [{'function': {'name': 'Person', 'arguments': '{"name": "Erick", "age": "27"}'}, 'type': 'function'}]})
结构化输出
ChatAnthropicTools 还实现了 with_structured_output 规范 来提取值。注意:这可能不如提供显式工具调用模型的稳定性好。
chain = ChatAnthropicTools(model="claude-3-opus-20240229").with_structured_output(
Person
)
chain.invoke("I am a 27 year old named Erick")
Person(name='Erick', age=27)
Related
- Chat model conceptual guide
- Chat model how-to guides