langchain-anthropic 1.7.13 如何复用自定义客户端并避免配置冲突?
langchain-anthropic 1.7.13 可用http_client复用传输层,或用client复用完整SDK;按连接参数归属选择,并由调用方负责关闭外部客户端。
langchain-anthropic 1.7.13 允许直接复用自定义传输层或完整客户端。前者保留模型侧连接设置,后者由客户端决定认证、地址和重试;先选清配置层级,再核对同步与异步参数,可以避免重复配置和资源未关闭的问题。

什么时候用传输层,什么时候用完整客户端
1.7.13 的这项改动面向 ChatAnthropic,提供 http_client、http_async_client、client、async_client 四个参数。它适合已经有网络策略或 SDK 对象的 Python 项目,以下配置适用于这个明确版本。
自定义 TLS、企业 CA、transport 和逐请求认证,通常使用 HTTP 层即可;跨平台访问或需要让 SDK 自己管理凭据时,完整 SDK 更合适。两者的关键区别是模型连接设置是否继续生效,而不只是参数名称不同。

先验证配置,再准备真实调用
- 在项目环境安装指定版本并读取包版本。结果应为 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_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 后,可确认对象已交给模型,且不会进入模型的序列化结果。使用这个入口时,模型侧密钥、接口地址、请求头、超时和重试仍适用。若需要指定 CA,应在 HTTP 客户端中配置真实证书文件。
- 若已有完整 SDK 客户端,改用下面的独立配置,将连接设置集中放在 SDK 对象上。
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 表示本地配置检查通过,不代表网络、账号权限和模型调用已经成功。传入完整 SDK 后,模型侧连接设置以及 LangSmith gateway headers 不会应用到它;真实请求需要在 SDK 侧补齐有效配置。
复用客户端时的四个检查点
异步调用使用 http_async_client 或 async_client,不能拿同步对象替代。只设置异步一侧时,同步调用仍沿用默认构造路径。官方对 HTTP 库匹配还有如下提醒。

- 类型不兼容时,优先采用 anthropic.DefaultHttpxClient 或 DefaultAsyncHttpxClient。SDK 使用 httpx2 还是 httpx,决定了可接受的客户端类型。
- 同一侧不能同时指定 client 与 http_client,异步侧同理。如确实需要定制两层,应在 SDK 构造时传入 HTTP 对象。
- 自定义 HTTP 对象与 anthropic_proxy 会冲突。将代理设置移到 HTTP 客户端,避免在模型上重复声明。
- 外部传入的对象不会被模型关闭。短脚本可使用上下文管理器,长期服务应在退出阶段统一关闭,避免把关闭责任交给无关请求。






























