• 消息
  • 托管智能体
  • 管理
Search...
⌘K
CLI、SDK 和库
概览
ant CLI
快速入门身份验证选项使用 CLI脚本与自动化
客户端 SDK
中间件PythonTypeScriptC#GoJavaPHPRuby
库与集成
Apple Foundation ModelsOpenAI SDK 兼容性
Log in
中间件
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
CLI、SDK 和库/客户端 SDK

SDK 中间件

在 Anthropic SDK 中拦截和修改请求与响应。

Anthropic SDK 提供了一个 "middleware"(中间件,或称拦截器)钩子,允许您在请求发送之前和响应接收之后运行代码。中间件适用于处理横切关注点,例如日志记录、自定义重试、请求注解以及拒绝回退处理。

每个中间件都可以在调用 next() 之前检查或替换请求,并在 next() 返回之后检查或替换响应。

注册中间件

每个中间件都是一个函数,它接收传出的请求和一个 next 可调用对象。调用 next 可将请求转发到链中的其余部分(如果这是最后一个中间件,则直接转发到 SDK 核心),并返回其响应。在 next 调用之前的任何代码都会在请求发出时运行;之后的任何代码都会在响应返回时运行。

中间件顺序

当您注册多个中间件时,它们会按照给定的顺序应用:第一个中间件的"前置"代码最先运行,而其"后置"代码最后运行。在客户端上注册的中间件会先于作为单次请求选项传入的中间件运行。

在 Go SDK 中,重复调用 option.WithMiddleware 会进行拼接(先客户端,后方法)。在其他 SDK 中,传入一个数组;后面的条目会包裹在内层。

替换 HTTP 客户端

每个 SDK 还接受自定义 HTTP 客户端(用于代理配置、自定义 TLS 或连接池)。每个 SDK 客户端只使用一个 HTTP 客户端;设置它会替换默认客户端。自定义 HTTP 客户端会在所有中间件运行完毕后接收请求。

内置中间件

SDK 附带了一个拒绝回退中间件,当 Claude Fable 5 拒绝请求时,该中间件会自动在回退模型上重试请求。有关设置和各语言示例,请参阅在回退模型上检测并重试。

Was this page helpful?

  • 注册中间件
  • 中间件顺序
  • 替换 HTTP 客户端
  • 内置中间件