在 1.7.13 中,自定义传输层和完整客户端都有了公开入口。只想调整证书、连接池或请求认证,可以注入传输层;已经维护完整客户端时,则直接交给模型使用。两种方案的连接参数归属不同,选对入口才能避免配置没有生效。

先分清要接管哪一层
langchain-anthropic 1.7.13 对应的官方改动,为 ChatAnthropic 增加了 http_client、http_async_client、client 和 async_client。前两个用于 HTTP 传输,后两个用于 Anthropic SDK 客户端。以下配置适用于这个明确版本。
例如,公司需要指定可信 CA 或每次请求刷新认证信息时,HTTP 客户端通常已经足够;如果项目通过 Bedrock、Vertex 等平台接入,或希望复用现成 SDK 客户端,则应考虑第二种入口。官方参数对照如下。

按顺序检查环境和配置
- 在项目的 Python 环境安装指定版本并打印版本号。终端应显示 1.7.13;若显示其他版本,先确认安装命令和运行脚本使用同一解释器。
python -m pip install "langchain-anthropic==1.7.13"
python -c "from importlib.metadata import version; print(version('langchain-anthropic'))"
- 只接管 HTTP 层时,将同步客户端传给 http_client。下例可保存为 http_config.py;占位密钥仅用于不联网的配置检查,不能发起真实服务调用。
import anthropic
from langchain_anthropic import ChatAnthropic
# 配置检查不发送 API 请求;真实调用需有效密钥和可用模型。
with anthropic.DefaultHttpxClient() as transport:
model = ChatAnthropic(
model="claude-sonnet-5-5",
api_key="sk-local-configuration-check",
base_url="https://api.anthropic.com",
max_retries=2,
http_client=transport,
)
assert model.http_client is transport
assert "http_client" not in model.model_dump()
print("HTTP client configuration OK")
这个检查应打印 HTTP client configuration OK。模型仍负责 API 地址、密钥、超时、重试和默认请求头,传入的对象负责底层请求发送。需要企业 CA 时,可在 DefaultHttpxClient 的 verify 参数中填写真实证书文件路径,不要为了绕过证书问题关闭验证。
- 如果需要由 SDK 管理连接,单独运行以下方案。这里将完整客户端交给 client;检查结束后上下文管理器负责关闭它。
import anthropic
from langchain_anthropic import ChatAnthropic
# SDK 客户端管理连接配置;退出上下文时由调用方关闭。
with anthropic.Anthropic(
api_key="sk-local-configuration-check",
base_url="https://api.anthropic.com",
max_retries=2,
) as sdk:
model = ChatAnthropic(model="claude-sonnet-5-5", client=sdk)
assert model.client is sdk
assert "client" not in model.model_dump()
print("SDK client configuration OK")
运行应打印 SDK client configuration OK。传入完整客户端后,模型上的 api_key、base_url、default_headers、超时、重试、代理及 LangSmith gateway headers 不再用于配置这个客户端,因此应把相关设置放到 SDK 构造处。示例只验证对象配置与序列化排除,不证明真实接口、账号或模型权限可用。
同步、异步与常见冲突
同步和异步是独立通道。异步调用对应 http_async_client 或 async_client,只配置异步对象不会替同步调用替换客户端。官方同时提醒,HTTP 库要与已安装的 SDK 匹配。

- 出现 HTTP 客户端类型错误时,优先使用 anthropic.DefaultHttpxClient 或 DefaultAsyncHttpxClient。它们会匹配 SDK 所用的库,避免把 httpx 与 httpx2 混用。
- 同一通道不要同时传 client 和 http_client,异步侧也同理;需要组合时,把 HTTP 对象交给 SDK,再把 SDK 交给模型。
- 自定义 HTTP 客户端不能再搭配 anthropic_proxy。代理应配置到传入的 HTTP 客户端上。
- 模型不会关闭外部传入的客户端。长驻服务应明确资源所有者,在应用退出时关闭;短脚本可像示例一样使用上下文管理器。










