• 訊息
  • 託管代理
  • 管理
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 用戶端
  • 內建中介軟體