---
title: Apple Foundation Models
url: https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/libraries/apple-foundation-models
description: 透過 Foundation Models 框架搭配 Claude for Foundation Models Swift 套件，在 Apple 平台上使用 Claude。
---

[Claude for Foundation Models](https://github.com/anthropics/ClaudeForFoundationModels) 是一個 Swift 套件，讓 Claude 能夠在 Apple 的 [Foundation Models](https://developer.apple.com/documentation/foundationmodels) 框架中作為伺服器端語言模型使用。此套件讓 Claude 遵循該框架的 `LanguageModel` 協定，因此您可以使用與 Apple 裝置端模型相同的 `LanguageModelSession` API 來驅動它：`respond(to:)`、「streaming」（串流）、引導式生成以及工具呼叫的運作方式完全相同。

請求會直接從您的應用程式傳送至 Claude API；Apple 不在請求路徑中，也不會看到提示或回應。使用量會依[標準 API 定價](https://platform.claude.com/docs/zh-TW/about-claude/pricing)計入您的 Anthropic 帳戶，因此您的組織需要有可用的點數餘額或有效的計費方式。您的應用程式自行決定何時使用 Claude、何時使用 Apple 的裝置端模型：將您想要的模型傳入各個 session 即可。

<Note>
  **Beta。** 此套件以 OS 27 beta 版中引入的 Foundation Models 伺服器端語言模型 API 為目標。API 在 beta 期間可能會有所變動。
</Note>

<Info>
  Claude for Foundation Models **並非**通用的 Messages API 用戶端。其公開介面為 Foundation Models 提供者的協定遵循實作，以及與之相關的設定型別（`ClaudeLanguageModel`、`ClaudeModel`、`AuthMode`、`ClaudeServerTool`）。若要以其他語言直接存取 Messages API，請參閱[用戶端 SDK](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/overview#client-sdks)。
</Info>

## 需求

* iOS 27、macOS 27、visionOS 27 或 watchOS 27（皆為 beta 版）：這些是 Foundation Models 框架支援伺服器端語言模型的作業系統版本
* Xcode 27（beta 版）
* 開發時需要一組來自 [Claude Console](https://platform.claude.com/) 的 Claude「API key」（API 金鑰）。正式環境的選項請參閱[驗證](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/libraries/apple-foundation-models#authentication)。

## 安裝套件

將套件加入您的 `Package.swift`：

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

或在 Xcode 中：**File** > **Add Package Dependencies…**，然後輸入儲存庫 URL。

接著將 `ClaudeForFoundationModels` 加入您 target 的相依項目，並與 `FoundationModels` 一同匯入：

```swift
import FoundationModels
import ClaudeForFoundationModels
```

## 快速開始

`ClaudeLanguageModel` 是進入點。將它傳入 `LanguageModelSession`，然後像使用任何 Foundation Models 提供者一樣使用該 session：

```swift
import FoundationModels
import ClaudeForFoundationModels

let model = ClaudeLanguageModel(
  name: .sonnet5,
  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`（請參閱[伺服器端工具](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/libraries/apple-foundation-models#server-side-tools)）。

若需要完整可運作的程式，儲存庫中包含 [`Examples/ClaudeExample`](https://github.com/anthropics/ClaudeForFoundationModels/tree/main/Examples/ClaudeExample)，這是一個可執行的命令列 target，會將一輪對話以串流方式輸出至終端機，並提供 `--search` 旗標以在該輪對話中啟用伺服器端網頁搜尋。執行它需要 macOS 27 主機。

## 選擇模型

模型識別碼是 `ClaudeModel` 的值。您可以使用已編譯內建的常數。若 ID 尚未編譯內建，則可明確指定能力來建構一個（請參閱[能力](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/libraries/apple-foundation-models#capabilities)）：

```swift
ClaudeLanguageModel(name: .opus5_5, auth: auth)
```

常數與 API 模型 ID 相對應（`.opus5` 即 `claude-opus-5`），並帶有各模型的能力資訊。新模型會在套件的新版本中以新常數的形式推出。請在 Xcode 中查看 `ClaudeModel` 以取得目前的清單，並參閱[模型概覽](https://platform.claude.com/docs/zh-TW/models/overview)來比較各模型。

### 能力

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

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

### Effort

使用 `fixedEffort:` 為每個請求固定 Claude 的 [effort 等級](https://platform.claude.com/docs/zh-TW/build-with-claude/effort)。它的優先順序高於框架針對個別請求的推理提示。框架的具名推理等級最高只到 high；若只想為單一請求要求更高的 effort，請傳入以 Claude effort 命名的自訂推理等級（`.custom("xhigh")` 或 `.custom("max")`），它會直接對應。未傳送 effort 時，API 會使用模型的預設等級，而預設等級因模型而異（請參閱 [effort 等級](https://platform.claude.com/docs/zh-TW/build-with-claude/effort#effort-levels)）：

```swift
ClaudeLanguageModel(name: .opus5_5, auth: auth, fixedEffort: .xhigh)
```

指定的等級必須是模型接受的等級。每個 `ClaudeModel` 都會宣告其模型接受五個等級（`low`、`medium`、`high`、`xhigh`、`max`）中的哪些。有些模型完全不接受 effort。

### 何時使用 Claude、何時使用裝置端模型

Apple 的裝置端模型快速、私密且可離線使用，但其規模是為輕量任務設計的。當您需要更大的「context window」（上下文視窗）、前沿推理能力，或網頁搜尋與程式碼執行等伺服器端工具時，請升級使用 Claude。由於兩者使用相同的 `LanguageModelSession` API，您只需替換 `model:` 引數即可切換。

## 驗證

使用 `auth:` 參數設定憑證。使用 `.appAttest` 可在沒有後端的情況下發布，使用 `.proxied` 可將請求經由您自己的後端轉送，或使用 `.apiKey` 在開發期間快速迭代。

### App Attest

您應用程式的每個安裝實例都會使用 Apple 的 [App Attest](https://developer.apple.com/documentation/devicecheck/establishing-your-app-s-integrity) 服務，來證明它是您所註冊之應用程式的正版、未經修改的建置版本。接著，Anthropic 會向該裝置核發一個短效期的「access token」（存取權杖），並將使用量計費至您的工作區。應用程式中不會內含任何 API 金鑰，您也無需自行營運任何代理伺服器。

App Attest 驗證僅在您的應用程式直接呼叫 Claude API 時可用。透過 Amazon Bedrock、Google Cloud 或 Microsoft Foundry 則無法使用此功能。

若要在不執行後端的情況下發布，請使用 `.appAttest`：

```swift
ClaudeLanguageModel(
  name: .sonnet5,
  auth: .appAttest(clientID: "clid_...")
)
```

<Note>
  App Attest 需要實體裝置。模擬器以及沒有 Secure Enclave 的硬體無法執行 App Attest。在模擬器中迭代時請使用 `.apiKey`，在裝置上執行時則使用 `.appAttest`。
</Note>

若要設定 App Attest，您需要您的 Apple Developer Team ID，以及在您組織中的管理員、擁有者或主要擁有者角色。請設定您的 Xcode 專案，並在 [Claude Console](https://platform.claude.com/) 中註冊您的應用程式：

1. 在 Xcode 中，於 **Signing & Capabilities** 下為您的應用程式目標新增 **App Attest** 功能。
2. 在 Claude Console 中，前往 [App integrations](https://platform.claude.com/settings/workspaces/default/app-integrations) 頁面（`platform.claude.com/settings/workspaces/default/app-integrations`）。每個應用程式整合都屬於一個工作區。請在側邊欄的工作區選擇器中選取您要的工作區。
3. 點擊 **Create app integration**，並輸入名稱、您的 Apple Developer Team ID，以及一個或多個 bundle ID（最多 32 個）。
4. 從該整合的 **Overview** 分頁複製 client ID（`clid_...`），並將其傳入您應用程式的 Claude 設定中。

您的應用程式首次在某部裝置上使用 Claude 時，應用程式會向 Anthropic 請求一個 challenge（挑戰值），使用 Apple 的 `DCAppAttestService` 對裝置進行證明，然後以經過驗證的證明交換一個 access token（存取權杖）。Claude for Foundation Models 套件會自動執行此流程，並在權杖過期時請求新的權杖；您無需撰寫任何證明相關的程式碼。

權杖的範圍限定於您的工作區，一小時後過期，且僅授權 [Messages API](https://platform.claude.com/docs/zh-TW/api/messages/create) 呼叫。它們不帶有任何終端使用者身分：App Attest 識別的是您的應用程式，而非使用它的人，因此請在您的應用程式中處理任何與個別使用者相關的邏輯。

若要停止已遭入侵或已淘汰的應用程式，請撤銷其整合。在 Claude Console 中，前往 [App integrations](https://platform.claude.com/settings/workspaces/default/app-integrations) 頁面（`platform.claude.com/settings/workspaces/default/app-integrations`）。每個應用程式整合都屬於一個工作區。在側邊欄的工作區選擇器中，選取包含該整合的工作區。選取該整合並點擊 **Revoke**，然後確認。撤銷整合會撤銷其尚未失效的權杖，且其已註冊的裝置將無法再請求新的權杖。撤銷是永久性的，因此若要恢復存取權限，請建立新的應用程式整合。

### 代理伺服器（正式環境）

在正式環境中，請使用 `.proxied` 將請求經由您自己的後端轉送。位於 `baseURL` 的中繼伺服器會在伺服器端加上 Claude API 憑證，因此應用程式不會附帶任何金鑰。您提供的 `headers` 會隨每個請求傳送，讓您的代理伺服器能夠授權呼叫者。若不需要任何標頭，請傳入 `[:]`：

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

您的代理伺服器會收到標準的 [Messages API](https://platform.claude.com/docs/zh-TW/api/messages/create) 請求，附加 `x-api-key` 標頭後，將其轉發至 `https://api.anthropic.com`。

### API 金鑰（開發用）

開發期間可直接傳入 API 金鑰：

```swift
ClaudeLanguageModel(name: .sonnet5, auth: .apiKey("YOUR_API_KEY"))
```

<Warning>
  打包進應用程式的金鑰可從發布的二進位檔中擷取出來，任何擷取到它的人都能發出計入您帳戶的請求。`.apiKey` 僅供開發使用，請在發布前切換為 App Attest 或代理伺服器。
</Warning>

## 串流

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

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

## 結構化輸出

以 `@Generable` 標註一個型別，並使用 `generating:` 請求它。模型會透過[結構化輸出](https://platform.claude.com/docs/zh-TW/build-with-claude/structured-outputs)回傳該型別的值：

```swift
@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 進行工具使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/overview)。

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

### 伺服器端工具

[伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools)（網頁搜尋、網頁擷取與程式碼執行）在 Anthropic 的基礎設施上於單次往返內執行，框架無需在裝置上執行任何內容。使用 `serverTools:` 為各模型進行設定：

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

`.webSearch` 與 `.webFetch` 接受選用的 `allowedDomains`、`blockedDomains` 與 `maxUses`。伺服器工具的活動會以 `ClaudeServerToolSegment` 自訂區段的形式呈現在 transcript 中。

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

## 圖像

能力中包含圖像輸入的模型會宣告框架的視覺能力。透過框架的標準 session API 傳入圖像內容；套件會將其轉換為 Claude API 的圖像格式。圖像需求請參閱[視覺](https://platform.claude.com/docs/zh-TW/build-with-claude/vision)。

## 錯誤處理

套件會在有對應項目時，將 Claude API 錯誤對應至 Apple 的 `LanguageModelError` 案例：上下文視窗溢位會呈現為 `.contextSizeExceeded`，HTTP 429 呈現為 `.rateLimited`，超過設定逾時的請求呈現為 `.timeout`。沒有框架對應項目的提供者錯誤則呈現為 `ClaudeError`。請使用模式比對來驅動產品流程：

```swift
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 協定中沒有對應表示方式的功能無法透過它使用，包括：

* 「Prompt caching」（提示快取）控制項（套件會自動套用提示快取；快取 TTL 與斷點位置無法設定）
* 停止序列
* 批次處理
* Files API
* Token 計數
* Beta 標頭

## 其他資源

| 參考資料                                                                                             | 涵蓋內容                                                              |
| ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- |
| [Apple Foundation Models 文件](https://developer.apple.com/documentation/foundationmodels)         | `LanguageModelSession`、`@Generable`、`Transcript`、`Tool` 以及框架的其餘介面 |
| [GitHub 上的 `ClaudeForFoundationModels`](https://github.com/anthropics/ClaudeForFoundationModels) | 原始碼、可執行範例以及 issue 追蹤器                                             |
| [Claude API 參考文件](https://platform.claude.com/docs/zh-TW/api/overview)                           | 底層的 Messages API                                                  |

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