• 訊息
  • 託管代理
  • 管理
Search...
⌘K
CLI、SDK 與函式庫
概覽
ant CLI
快速入門驗證選項使用 CLI指令碼與自動化
用戶端 SDK
中介軟體PythonTypeScriptC#GoJavaPHPRuby
函式庫與整合
Apple Foundation ModelsOpenAI SDK 相容性
Log in
Apple Foundation Models
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 與函式庫/函式庫與整合

Apple Foundation Models

透過 Foundation Models 框架與 Claude for Foundation Models Swift 套件,在 Apple 平台上使用 Claude。

Claude for Foundation Models 是一個 Swift 套件,可讓 Claude 作為 Apple Foundation Models 框架中的伺服器端語言模型使用。此套件使 Claude 符合該框架的 LanguageModel 協定,因此您可以使用與 Apple 裝置端模型相同的 LanguageModelSession API 來驅動它:respond(to:)、串流、引導式生成以及工具呼叫的運作方式都完全相同。

請求會直接從您的應用程式傳送至 Claude API;Apple 不在請求路徑中,也不會看到提示或回應。使用量會依照標準 API 定價計入您的 Anthropic 帳戶。您的應用程式可自行決定何時使用 Claude、何時使用 Apple 的裝置端模型:只需將您想要的模型傳遞給各個 session 即可。

Beta 版。 此套件針對 OS 27 beta 版中引入的 Foundation Models 伺服器端語言模型 API。在正式發布前,API 可能會有所變更。

Claude for Foundation Models 並非通用的 Messages API 用戶端。其公開介面僅限於 Foundation Models 提供者的協定實作,以及用於存取它的設定型別(ClaudeLanguageModel、ClaudeModel、AuthMode、ClaudeServerTool)。若要以其他語言直接存取 Messages API,請參閱 Client SDK。

系統需求

  • iOS 27、macOS 27、visionOS 27 或 watchOS 27(皆為 beta 版):這些作業系統版本的 Foundation Models 框架支援伺服器端語言模型
  • Xcode 27(beta 版)
  • 從 Claude Console 取得的 Claude API 金鑰,供開發使用。生產環境的選項請參閱驗證。

安裝套件

將套件新增至您的 Package.swift:

dependencies: [
  .package(url: "https://github.com/anthropics/ClaudeForFoundationModels.git", from: "0.1.0")
]

或在 Xcode 中:File > Add Package Dependencies… 並輸入儲存庫 URL。

接著將 ClaudeForFoundationModels 新增至您目標的相依性,並與 FoundationModels 一併匯入:

import FoundationModels
import ClaudeForFoundationModels

快速入門

ClaudeLanguageModel 是進入點。將它傳遞給 LanguageModelSession,並以與任何 Foundation Models 提供者完全相同的方式使用該 session:

import FoundationModels
import ClaudeForFoundationModels

let model = ClaudeLanguageModel(
  name: .sonnet4_6,
  auth: .apiKey(ProcessInfo.processInfo.environment["ANTHROPIC_API_KEY"] ?? "")
)

let session = LanguageModelSession(model: model)
let response = try await session.respond(to: "Plan a 4-day trip to Buenos Aires.")
print(response.content)

初始化器也接受 baseURL(預設為 https://api.anthropic.com)、timeout 以及 serverTools(請參閱伺服器端工具)。

如需完整的可運作程式,儲存庫中包含 Examples/ClaudeExample,這是一個可執行的命令列目標,會將一輪對話以串流方式輸出至終端機,並提供 --search 旗標以在該輪對話中啟用伺服器端網頁搜尋。執行此範例需要 macOS 27 主機。

選擇模型

模型識別碼是 ClaudeModel 的值。您可以使用編譯內建的常數,或針對尚未編譯內建的 ID 以明確的能力建構一個(請參閱能力):

ClaudeLanguageModel(name: .opus4_8, auth: auth)

常數對應於 API 模型 ID(.opus4_8 即為 claude-opus-4-8),並帶有各模型的能力。新模型會以新常數的形式隨套件版本發布;請在 Xcode 中查看 ClaudeModel 以取得目前的清單,並參閱模型總覽以比較各模型。

能力

每個 ClaudeModel 都會宣告其接受的內容:取樣參數、effort 等級、自適應思考、結構化輸出以及影像輸入。套件會據此決定要傳送哪些請求欄位,因為傳送模型拒絕的欄位會導致硬性錯誤。內建常數已帶有正確的能力。對於尚未編譯內建的 ID,請宣告該模型接受的內容(刻意不提供會自行猜測的簡寫方式):

let model = ClaudeModel(
  id: "claude-experimental-x",
  capabilities: .init(samplingParams: false, effortLevels: [.low, .high])
)
ClaudeLanguageModel(name: model, auth: auth)

Effort

使用 fixedEffort: 為每個請求固定一個 Claude effort 等級。它的優先順序高於框架的每請求推理提示,而且這是請求 .xhigh 或 .max 的唯一方式,因為框架的推理等級最高只到 high。若未傳送 effort,API 預設為 high:

ClaudeLanguageModel(name: .opus4_8, auth: auth, fixedEffort: .xhigh)

該等級必須是模型所接受的。每個 ClaudeModel 都會宣告其模型接受五個等級(low、medium、high、xhigh、max)中的哪些(如果有的話):有些模型完全不接受 effort。

何時使用 Claude 而非裝置端模型

Apple 的裝置端模型速度快、注重隱私且可離線運作,但其規模僅適用於輕量級任務。當您需要更大的上下文、前沿推理能力,或網頁搜尋與程式碼執行等伺服器端工具時,請升級使用 Claude。由於兩者使用相同的 LanguageModelSession API,您只需更換 model: 引數即可切換。

驗證

使用 auth: 參數設定憑證。

API 金鑰(開發環境)

開發時可直接傳遞 API 金鑰:

ClaudeLanguageModel(name: .sonnet4_6, auth: .apiKey("YOUR_API_KEY"))

打包進應用程式的金鑰可從發布的二進位檔中擷取出來,任何擷取到金鑰的人都能發出計入您帳戶的請求。請僅在開發時使用 .apiKey,並在發布前切換至代理伺服器。

代理伺服器(生產環境)

在生產環境中,請使用 .proxied 將請求透過您自己的後端轉送。位於 baseURL 的中繼伺服器會在伺服器端加上 Claude API 憑證,因此應用程式不會內含任何金鑰。您提供的 headers 會隨每個請求傳送,以便您的代理伺服器授權呼叫者。若不需要任何標頭,請傳遞 [:]:

ClaudeLanguageModel(
  name: .sonnet4_6,
  auth: .proxied(headers: ["X-App-Token": "..."]),
  baseURL: URL(string: "https://api.yourapp.com/claude")!
)

您的代理伺服器會接收標準的 Messages API 請求,附加 x-api-key 標頭,並將其轉送至 https://api.anthropic.com。

串流

streamResponse(to:) 會以增量方式傳回回應。每個元素都是截至目前為止回應的累積快照,而非差異內容:

let stream = session.streamResponse(to: "Summarize today's top science stories.")
for try await partial in stream {
  print(partial.content)
}

結構化輸出

使用 @Generable 標註型別,並透過 generating: 請求它。模型會透過結構化輸出傳回該型別的值:

@Generable
struct Trip {
  @Guide(description: "Destination city") var destination: String
  @Guide(description: "Length in days") var days: Int
}

let response = try await session.respond(to: "Plan a trip to Tokyo.", generating: Trip.self)
print(response.content.destination)

結構化輸出需要能力中包含此功能的模型(所有編譯內建的常數皆支援)。若所選模型不支援,套件會擲回 LanguageModelError.unsupportedGenerationGuide,而非悄悄降級。

工具使用

用戶端工具

框架的 tools: 陣列可原樣使用。讓您的型別符合 Tool 協定,將它們傳遞給 LanguageModelSession,當 Claude 呼叫這些工具時,框架會在裝置上調用它們。請參閱 Claude 的工具使用。

let session = LanguageModelSession(model: model, tools: [FindRestaurantsTool()])

伺服器端工具

伺服器工具(網頁搜尋、網頁擷取與程式碼執行)在 Anthropic 的基礎設施上於單次往返中執行,框架無需在裝置上調用任何內容。請透過 serverTools: 針對每個模型進行設定:

let model = ClaudeLanguageModel(
  name: .sonnet4_6,
  auth: auth,
  serverTools: [
    .webSearch(maxUses: 5),
    .codeExecution,
  ]
)

.webSearch 與 .webFetch 接受選用的 allowedDomains、blockedDomains 以及 maxUses。伺服器工具的活動會以 ClaudeServerToolSegment 自訂區段的形式出現在對話記錄中。

serverTools 是在 ClaudeLanguageModel 上設定,而非在 LanguageModelSession 上,因為 session 型別屬於 Apple。若要在不同對話中使用不同的伺服器工具組合,請建構多個 ClaudeLanguageModel 實例。

影像

能力中包含影像輸入的模型會宣告框架的視覺能力。請透過框架的標準 session API 傳遞影像內容;套件會將其轉換為 Claude API 的影像格式。影像需求請參閱視覺。

錯誤處理

套件會將 Claude API 錯誤對應至 Apple 的 LanguageModelError 案例(若有相符者):上下文視窗溢位會顯示為 .contextSizeExceeded、HTTP 429 顯示為 .rateLimited、超過設定逾時的請求顯示為 .timeout。沒有對應框架案例的提供者錯誤會顯示為 ClaudeError。請使用模式比對來驅動產品流程:

do {
  let response = try await session.respond(to: prompt)
  print(response.content)
} catch ClaudeError.missingCredential {
  // 提示輸入 API 金鑰。
} catch let error as LanguageModelError {
  // 框架層級的錯誤(速率限制、防護機制、上下文長度、解碼)。
} catch {
  // 傳輸錯誤。
}

常見的模式是捕捉 .rateLimited,並在該輪對話中退回使用 SystemLanguageModel、將請求排入佇列,或顯示重試選項。

功能支援

此套件呈現 Foundation Models 提供者協定所能表達的 Messages API 功能。在 Apple 協定中沒有對應表示方式的功能無法透過此套件使用,包括:

  • 提示快取控制(套件會自動套用提示快取;快取 TTL 與斷點位置無法設定)
  • 停止序列
  • 批次處理
  • Files API
  • Token 計數
  • Beta 標頭

其他資源

參考資料涵蓋內容
Apple Foundation Models 文件LanguageModelSession、@Generable、Transcript、Tool 以及框架的其餘介面
GitHub 上的 ClaudeForFoundationModels原始碼、可執行的範例以及問題追蹤器
Claude API 參考底層的 Messages API

此套件採用 Apache 2.0 授權。歡迎透過 GitHub issues 回報錯誤。Beta 期間不接受外部的 pull request。

Was this page helpful?

  • 系統需求
  • 安裝套件
  • 快速入門
  • 選擇模型
  • 能力
  • Effort
  • 何時使用 Claude 而非裝置端模型
  • 驗證
  • API 金鑰(開發環境)
  • 代理伺服器(生產環境)
  • 串流
  • 結構化輸出
  • 工具使用
  • 用戶端工具
  • 伺服器端工具
  • 影像
  • 錯誤處理
  • 功能支援
  • 其他資源