Apple Foundation Models

Apple Foundation Models: Claude 集成指南

Claude for Foundation Models is a Swift package that makes Claude available as a server-side language model in Apple’s Foundation Models framework. The package conforms Claude to the framework’s LanguageModel protocol, so you drive it with the same LanguageModelSession API you use for Apple’s on-device model: respond(to:), streaming, guided generation, and tool calling all work the same way.

Claude for Foundation Models 是一个 Swift 软件包,它使 Claude 能够作为 Apple Foundation Models 框架中的服务端语言模型使用。该软件包使 Claude 符合框架的 LanguageModel 协议,因此你可以使用与 Apple 端侧模型相同的 LanguageModelSession API 来驱动它:respond(to:)、流式传输、引导式生成和工具调用等功能的工作方式完全一致。

Requests go directly from your app to the Claude API; Apple is not in the request path and does not see prompts or responses. Usage is billed to your Anthropic account at standard API pricing. Your app decides when to use Claude and when to use Apple’s on-device model: pass whichever model you want to each session.

请求直接从你的应用程序发送到 Claude API;Apple 不在请求路径中,也无法查看提示词或响应内容。使用费用将按标准 API 定价计入你的 Anthropic 账户。你的应用程序可以决定何时使用 Claude,何时使用 Apple 的端侧模型:只需将你想要的模型传递给每个会话即可。

Beta. This package targets the Foundation Models server-side language model API introduced in the OS 27 betas. APIs may change before general availability.

测试版。此软件包针对 OS 27 测试版中引入的 Foundation Models 服务端语言模型 API。API 在正式发布前可能会有所变动。

Claude for Foundation Models is not a general-purpose Messages API client. Its public surface is the Foundation Models provider conformance plus the configuration types that reach it (ClaudeLanguageModel, ClaudeModel, AuthMode, ClaudeServerTool). For direct access to the Messages API in another language, see the Client SDKs.

Claude for Foundation Models 并非通用的 Messages API 客户端。其公开接口仅限于 Foundation Models 提供程序的一致性实现,以及与之相关的配置类型(ClaudeLanguageModelClaudeModelAuthModeClaudeServerTool)。如需在其他语言中直接访问 Messages API,请参阅客户端 SDK。

Requirements

要求

  • iOS 27, macOS 27, visionOS 27, or watchOS 27 (all in beta): the OS releases whose Foundation Models framework supports server-side language models.

  • Xcode 27 (beta).

  • A Claude API key from the Claude Console for development. See Authentication for production options.

  • iOS 27、macOS 27、visionOS 27 或 watchOS 27(均为测试版):Foundation Models 框架支持服务端语言模型的操作系统版本。

  • Xcode 27(测试版)。

  • 用于开发的 Claude API 密钥(来自 Claude Console)。生产环境的身份验证选项请参阅“身份验证”部分。

Install the package

安装软件包

Add the package to your Package.swift: 在你的 Package.swift 中添加该软件包:

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

Or in Xcode: File > Add Package Dependencies… and enter the repository URL. Then add ClaudeForFoundationModels to your target’s dependencies and import it alongside FoundationModels: 或者在 Xcode 中:选择 File > Add Package Dependencies… 并输入仓库 URL。然后将 ClaudeForFoundationModels 添加到你的目标依赖项中,并与 FoundationModels 一起导入:

import FoundationModels
import ClaudeForFoundationModels

Quick start

快速入门

ClaudeLanguageModel is the entry point. Pass it to LanguageModelSession and use the session exactly as you would with any Foundation Models provider: ClaudeLanguageModel 是入口点。将其传递给 LanguageModelSession,然后像使用任何 Foundation Models 提供程序一样使用该会话:

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)

The initializer also accepts baseURL (default https://api.anthropic.com), timeout, and serverTools (see Server-side tools). For a complete working program, the repository includes Examples/ClaudeExample, a runnable command-line target that streams a chat turn to the terminal, with a --search flag that enables server-side web search for the turn. Running it requires a macOS 27 host.

初始化器还接受 baseURL(默认为 https://api.anthropic.com)、timeoutserverTools(请参阅“服务端工具”)。为了提供一个完整的可运行程序,仓库中包含了 Examples/ClaudeExample,这是一个可运行的命令行目标,可以将聊天内容流式传输到终端,并带有 --search 标志,可为该轮对话启用服务端网页搜索。运行此程序需要 macOS 27 主机。

Choosing a model

选择模型

Model identifiers are values of ClaudeModel. Use a compiled-in constant, or construct one with explicit capabilities for an ID that isn’t compiled in yet (see Capabilities): 模型标识符是 ClaudeModel 的值。你可以使用内置常量,或者为尚未编译进来的 ID 构建一个具有明确功能(Capabilities)的模型(请参阅“功能”部分):

ClaudeLanguageModel(name: .opus4_8, auth: auth)

Constants mirror API model IDs (.opus4_8 is claude-opus-4-8) and carry each model’s capabilities. New models ship as new constants in package releases; check ClaudeModel in Xcode for the current list, and the Models overview to compare models.

常量对应 API 模型 ID(.opus4_8claude-opus-4-8)并携带每个模型的功能。新模型会作为新常量随软件包发布;请在 Xcode 中查看 ClaudeModel 以获取当前列表,并参考模型概览进行对比。

Capabilities

功能

Each ClaudeModel declares what it accepts: sampling parameters, effort levels, adaptive thinking, structured output, and image input. The package uses this to decide which request fields to send, because sending a field a model rejects is a hard error. The constants carry the right capabilities. For an ID that isn’t compiled in, declare what the model accepts (there is deliberately no shorthand that guesses):

每个 ClaudeModel 都会声明它接受的内容:采样参数、努力程度(effort levels)、自适应思维、结构化输出和图像输入。软件包利用这些信息来决定发送哪些请求字段,因为发送模型不支持的字段会导致严重错误。内置常量已携带正确的功能配置。对于尚未编译进来的 ID,请手动声明模型接受的内容(特意没有提供猜测功能的简写):

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

Effort

努力程度 (Effort)

Pin a Claude effort level for every request with fixedEffort:. It takes precedence over the framework’s per-request reasoning hints, and it’s the only way to request .xhigh or .max, because the framework’s reasoning levels stop at high. The API defaults to high when no effort is sent:

使用 fixedEffort: 为每个请求固定 Claude 的努力程度。它优先于框架的每请求推理提示,并且这是请求 .xhigh.max 的唯一方式,因为框架的推理级别最高仅到 high。当未发送努力程度时,API 默认为 high

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

The level must be one the model accepts. Each ClaudeModel declares which of the five levels (low, medium, high, xhigh, max) its model takes, if any: some models don’t accept effort at all.

该级别必须是模型所接受的。每个 ClaudeModel 都会声明其模型支持的五个级别(low, medium, high, xhigh, max)中的哪一个(如果有):有些模型根本不支持努力程度设置。

When to use Claude versus the on-device model

何时使用 Claude 与端侧模型

Apple’s on-device model is fast, private, and works offline, but it is sized for lightweight tasks. Escalate to Claude when you need larger context, frontier reasoning, or server-side tools such as web search and code execution. Because both use the same LanguageModelSession API, you can switch by swapping the model: argument.

Apple 的端侧模型速度快、隐私性高且可离线工作,但其规模仅适用于轻量级任务。当你需要更大的上下文、前沿推理能力或服务端工具(如网页搜索和代码执行)时,请切换到 Claude。由于两者都使用相同的 LanguageModelSession API,你可以通过替换 model: 参数来轻松切换。

Authentication

身份验证

Set the credential with the auth: parameter. 使用 auth: 参数设置凭据。

API key (development)

API 密钥(开发环境)

Pass an API key directly while developing: 在开发过程中直接传递 API 密钥:

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

A key bundled into an app is extractable from the shipping binary, and anyone who extracts it can make requests billed to your account. Use .apiKey for development only, and switch to a proxy before release.

打包在应用程序中的密钥可以从发布版本中提取,任何提取它的人都可以发起计入你账户的请求。.apiKey 仅供开发使用,发布前请切换到代理模式。

Proxy (production)

代理(生产环境)

For production, route requests through your own back end with .proxied. The relay at baseURL adds the Claude API credential server-side, so the app ships no key. The headers you provide are sent on every request so your proxy can authorize the caller. Pass [:] if it needs none:

在生产环境中,请使用 .proxied 通过你自己的后端路由请求。baseURL 处的转发器会在服务端添加 Claude API 凭据,因此应用程序无需携带密钥。你提供的标头会随每个请求发送,以便你的代理可以授权调用者。如果不需要标头,请传递 [:]

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

Your proxy receives standard Messages API requests, attaches the x-api-key header, and forwards them to https://api.anthropic.com.

你的代理接收标准的 Messages API 请求,附加 x-api-key 标头,并将它们转发到 https://api.anthropic.com

Streaming

流式传输

streamResponse(to:) returns the response incrementally. Each element is a cumulative… streamResponse(to:) 会增量返回响应。每个元素都是一个累积的……