apple-foundation-models
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOperating Rules
操作规则
- Consult at the start of every task to navigate the framework's capabilities.
references/_index.md - Always check model availability () before attempting to initialize a session; gracefully handle unsupported hardware or missing downloads.
SystemLanguageModel.default.availability - Strictly adhere to Swift 6 concurrency rules: must be explicitly isolated (
LanguageModelSession,@State, or@MainActor), andactorconformances must beTool.Sendable - Respect the strict 4 096-token context limit per session; design proactive recovery strategies for long conversations.
- Prefer for structured output instead of asking the model to write raw JSON.
@Generable - Never use the model for real-time data retrieval without injecting capabilities, and avoid using it for complex mathematical reasoning or authoritative world-knowledge.
Tool - Focus on hardware performance: use intelligently during idle time to minimize first-token latency.
prewarm()
- 每项任务开始时,请查阅以了解框架的功能范围。
references/_index.md - 在尝试初始化会话前,务必检查模型可用性();优雅处理不支持的硬件或缺失的下载情况。
SystemLanguageModel.default.availability - 严格遵守Swift 6并发规则:必须显式隔离(使用
LanguageModelSession、@State或@MainActor),且actor协议实现必须符合Tool要求。Sendable - 遵守每个会话严格的4096-token上下文限制;为长对话设计主动恢复策略。
- 对于结构化输出,优先使用而非要求模型生成原始JSON。
@Generable - 若未注入能力,切勿使用模型进行实时数据检索;避免将其用于复杂数学推理或权威世界知识查询。
Tool - 关注硬件性能:在空闲时段智能调用以最小化首token延迟。
prewarm()
Task Workflow
任务工作流
Review existing AI integration code
评审现有AI集成代码
- Read the code under review and identify which topics apply.
- Flag any missing availability checks before instantiation.
LanguageModelSession - Validate that is explicitly caught and handled.
.exceededContextWindowSize - Ensure is not declared locally inside a function or
LanguageModelSession(which breaks statefulness).Task - Check implementations to ensure errors are propagated (
Tool) and not silenced withthrows.try?
- 阅读待评审代码并确定适用的主题。
- 标记实例化前缺失的可用性检查。
LanguageModelSession - 验证是否显式捕获并处理错误。
.exceededContextWindowSize - 确保未在函数或
LanguageModelSession内部本地声明(这会破坏状态性)。Task - 检查实现,确保错误被传播(使用
Tool)而非通过throws静默处理。try?
Implement new Foundation Models feature
实现新的Foundation Models功能
- Determine the correct model adapter: for conversational prose,
.defaultfor classification/extraction..contentTagging - Design data flow: choose between monolithic or real-time
respond(to:).streamResponse(to:) - Define structs for structured data extraction, utilizing
@Generableto strictly constrain output token by token.@Guide - Build instructions safely, keeping them developer-controlled and strictly separated from user input.
- 确定正确的模型适配器:用于对话式文本,
.default用于分类/提取任务。.contentTagging - 设计数据流:选择整体式或实时
respond(to:)。streamResponse(to:) - 为结构化数据提取定义结构体,利用
@Generable逐token严格约束输出。@Guide - 安全构建指令,确保指令由开发者控制,并与用户输入严格分离。
Implement Tool Calling
实现工具调用
- Define the protocol conformance, ensuring a clear, concise
Toolfor the model.description - Define using
Argumentstypes.@Generable - Implement the method, ensuring network calls or database queries are properly awaited and errors are correctly thrown back to the model.
call(arguments:)
- 定义协议实现,为模型提供清晰简洁的
Tool。description - 使用类型定义
@Generable。Arguments - 实现方法,确保网络调用或数据库查询被正确等待,且错误被正确抛回给模型。
call(arguments:)
Topic Router
主题路由
Consult the reference file for each topic relevant to the current task:
| Topic | Reference |
|---|---|
| Core Models & Availability | |
| Session & Transcript Lifecycle | |
Structured Output & | |
Expanding capabilities ( | |
| Temperature & Token Limits | |
| Real-time UI & Streams | |
| Context Overflow & Fallbacks | |
| Actor Isolation & Sendable | |
| Memory, Prewarming & Optimization | |
| Framework Terminology | |
针对当前任务的相关主题,查阅对应的参考文件:
| 主题 | 参考文件 |
|---|---|
| 核心模型与可用性 | |
| 会话与记录生命周期 | |
结构化输出与 | |
扩展能力( | |
| 温度与Token限制 | |
| 实时UI与流处理 | |
| 上下文溢出与回退 | |
| Actor隔离与Sendable | |
| 内存、预加载与优化 | |
| 框架术语 | |
Correctness Checklist
正确性检查清单
These are hard rules — violations will cause runtime crashes, deadlocks, or broken state:
- is checked before creating any session.
SystemLanguageModel.default.availability - is explicitly owned by
LanguageModelSessionor an@State(never instantiated locally inside a function).actor - is explicitly caught in all
LanguageModelSession.GenerationError.exceededContextWindowSizeblocks interacting with the session.do/catch - A session is never reused after throwing an error (a fresh instance must be created).
.exceededContextWindowSize - is called during idle time (e.g., view
prewarm()), never immediately preceding a.taskcall.respond(to:) - Errors inside are explicitly thrown and never silenced with
Tool.call(arguments:).try? - Instructions strings are strictly hardcoded or developer-controlled, never built directly from user input.
- properties are ordered logically top-to-bottom, with summary/dependent properties placed last.
@Generable - types are never instantiated manually, only consumed from
PartiallyGenerated.streamResponse
以下为硬性规则——违反将导致运行时崩溃、死锁或状态损坏:
- 创建任何会话前必须检查。
SystemLanguageModel.default.availability - 必须由
LanguageModelSession或@State显式持有(绝不能在函数内部本地实例化)。actor - 在所有与会话交互的块中,必须显式捕获
do/catch错误。LanguageModelSession.GenerationError.exceededContextWindowSize - 会话抛出错误后绝不能复用,必须创建新实例。
.exceededContextWindowSize - 需在空闲时段调用(例如视图的
prewarm()),绝不能在.task调用前立即执行。respond(to:) - 内部的错误必须显式抛出,绝不能通过
Tool.call(arguments:)静默处理。try? - 指令字符串必须严格硬编码或由开发者控制,绝不能直接从用户输入构建。
- 属性需按逻辑从上到下排序,汇总/依赖属性放在最后。
@Generable - 类型绝不能手动实例化,只能从
PartiallyGenerated中获取。streamResponse
References
参考文件
- — Read first for quick navigation. Index of all documentation.
references/_index.md - — Availability states, adapter types (
references/system-language-model.md,.default), and hardware requirements..contentTagging - — Initialization, system instructions, transcript management, and statefulness.
references/session-lifecycle.md - —
references/guided-generation.mdmacros,@Generabletoken constraints, and dynamic schema building.@Guide - —
references/tool-calling.mdprotocol design,Toolconformance, andSendable.ToolExecutionDelegate - — Temperature tuning,
references/generation-options.mdvs.greedysampling, and response token capping..random - —
references/streaming.mdlogic,streamResponse(to:)handling for SwiftUI incremental updates.PartiallyGenerated - — Mandatory recovery strategies for context overflow and unsupported locales.
references/error-handling.md - — Strict Swift 6 isolation invariants,
references/concurrency.mdUI patterns, and cross-actor session usage.@MainActor - — KV-cache limits, 4096-token budgets, 1.2 GB RAM footprint, and latency reduction via
references/performance.md.prewarm() - — Canonical definitions for terms like "LoRA", "adapter", and "transcript".
references/glossary.md
- — 首先阅读以快速导航。所有文档的索引。
references/_index.md - — 可用性状态、适配器类型(
references/system-language-model.md、.default)及硬件要求。.contentTagging - — 初始化、系统指令、记录管理及状态性。
references/session-lifecycle.md - —
references/guided-generation.md宏、@Generabletoken约束及动态架构构建。@Guide - —
references/tool-calling.md协议设计、Tool一致性及Sendable。ToolExecutionDelegate - — 温度调优、
references/generation-options.md与.greedy采样对比及响应token上限设置。.random - —
references/streaming.md逻辑、SwiftUI增量更新的streamResponse(to:)处理。PartiallyGenerated - — 上下文溢出和不支持区域设置的强制恢复策略。
references/error-handling.md - — Swift 6严格隔离不变量、
references/concurrency.mdUI模式及跨actor会话使用。@MainActor - — KV缓存限制、4096-token预算、1.2 GB内存占用及通过
references/performance.md降低延迟。prewarm() - — 术语的标准定义,如"LoRA"、"adapter"和"transcript"。
references/glossary.md