ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

RunAnywhere Swift SDK 完整指南:iOS/macOS 端侧 AI 的统一入口与全模态调用

RunAnywhere Swift SDK 完整指南:iOS/macOS 端侧 AI 的统一入口与全模态调用 AI模型推理服务推理引擎本地部署多模态【免费下载链接】runanywhere-sdksProduction ready toolkit to run AI locally项目地址https://gitcode.com/gh_mirrors/ru/runanywhere-sdks点击查看免费下载RunAnywhere Swift SDK 是面向 iOS 17.5 / macOS 14.5 的本地 AI 运行时封装以enum RunAnywhere作为唯一入口将 LLM 文本生成、结构化输出、工具调用、STT/TTS/VAD、视觉理解VLM、图像生成Diffusion、RAG、LoRA 与语音 Agent 等能力收敛为同一套 async/await 公共 API。本文以官方文档 core/docs/md/swift.md 为骨架结合仓库中 Swift 绑定源码bindings/swift/Sources/RunAnywhere/Public展开帮助你掌握从两阶段初始化、模型生命周期到各模态调用的完整实战路径并理解其在底层如何通过 C 桥接与 proto 协议落地。快速导读RunAnywhere 是生产就绪的端侧 AI 工具包其 Swift SDK 是所有其他 SDKKotlin、TypeScript、Python、Flutter镜像的规范公共面canonical surface。结构化类型均为指向生成式 proto 的类型别名RA*前缀。阅读完本文你将能完成两阶段初始化并理解 Phase 1/Phase 2 各自负责的工作管理模型注册表注册、下载、加载、卸载、删除并掌握生成调用自动加载模型的行为调用 LLM 流式生成、结构化输出validation/repair 两种模式、工具调用与内置 Web 搜索工具使用 STT/TTS/VAD、VLM、Diffusion、RAG、LoRA 与语音 Agent 的完整 API并通过 Combine/回调订阅 SDK 事件。环境要求与 SDK 定位文档明确SDK 适用于iOS 17.5 / macOS 14.5入口点是enum RunAnywhere所有功能以public extension块中的static方法暴露。底层实际链接的运行时包括LlamaCPPRuntime、ONNXRuntime与MLXRuntime见 bindings/swift/Sources 目录结构并通过 Foundation/Bridge/CppBridge.swift 桥接到仓库core/中的 C commons 实现。值得注意的是RunAnywhere.capabilities()定义于 Public/RunAnywhere.swift会如实报告当前构建支持与不支持的能力例如backend.litert、backend.qhexrtQualcomm Hexagon NPU、wakeword、realtime、agents均明确标记为不可用并给出原因generateStructured.constrained标注为引擎级约束解码尚未接入请使用.validationOnly或.repairloadOptions.contextLength / threads / accelerator也因原生加载 ABI 尚未承载而不可用。这种失败优先fail fast的能力自省设计帮助调用方在运行前就发现能力缺口。初始化两阶段模型文档给出的初始化骨架如下import RunAnywhere // Phase 1 — synchronous try RunAnywhere.initialize( apiKey: ra_..., // optional in development baseURL: nil, environment: .development ) // Phase 2 — async services try await RunAnywhere.completeServicesInitialization() // State RunAnywhere.isInitialized RunAnywhere.areServicesReady RunAnywhere.version let id try RunAnywhere.deviceId // throwing property RunAnywhere.isAuthenticated结合 Public/RunAnywhere.swift 的实现两阶段的实际分工是Phase 1同步initialize通过CppBridge.initialize拉起 C 桥接层与平台适配器解析持久化设备身份CppBridge.Device.persistentId调用rac_sdk_init_phase1_proto完成校验与状态初始化并把模型路径基目录指向应用的 Documents 目录initialize返回时本地推理即可用。Phase 2异步completeServicesInitialization执行认证/刷新、设备注册、模型分配拉取、遥测刷新、已下载模型发现并在最后通过BackgroundDownloadCoordinator.shared.restoreInterruptedTransfers()恢复上次运行遗留的后台下载。源码层面的几个关键细节新版initialize已默认在后台自动启动 Phase 2从源码看initialize会在 Phase 1 成功后Task.detached启动 Phase 2因此文档中的completeServicesInitialization()已被标记为available(*, deprecated, message: initialize() now owns both phases; this call is no longer needed)。文中代码仍然有效但新项目可以省略第二次显式调用。状态属性已演进isInitialized已重命名为isReadyareServicesReady被标记为 deprecated网络就绪属于 SDK 内部关注点请使用isReadyisActive同样 deprecated。文档中deviceId写为 throwing property而当前源码public static var deviceId: String是非抛出的内部用try?解析不可用时返回空串这是一个值得注意的版本差异。离线本地模式通过环境变量RUNANYWHERE_SWIFT_LOCAL_ONLY1/true/yes可跳过 Phase 2 的网络步骤仅保留本地推理。幂等与并发安全Phase 2 任务被去重共享多次调用completeServicesInitialization不会重复执行SDKLifetimeGate以代数generation机制防止旧的 reset 完成事件复活新的 SDK 生命周期。reset()是 async 方法会卸载模型、关闭会话、清空状态并线性化与同步 Phase 1 的竞争。环境SDKEnvironmentSDKEnvironment是 proto 生成类型RASDKEnvironment的 typealias见 Public/Configuration/SDKEnvironment.swift目前可部署环境为.development与.productiondevelopmentAPI key 可选可传空串baseURL 使用占位符developmentPlaceholderURL本地分析默认日志级别.debug不要求认证production必须提供有效的 API key 与 baseURL默认日志级别.warning发送遥测且只允许在 Release 构建中使用DEBUG 构建下isCompatibleWithCurrentBuild返回false参数校验rac_validate_api_key/rac_validate_base_url由 C 侧统一完成保证各 SDK 行为一致SDKEnvironment的 Codable 遵循wire 格式为小写的映射wireString/from(wireString:)由 codegen 从idl/model_types.proto的rac_wire_string注解生成。模型管理注册、下载、加载与生命周期文档中的示例let models await RunAnywhere.listModels() let downloaded await RunAnywhere.downloadedModels() let one await RunAnywhere.getModel(RAModelGetRequest(id: qwen2.5-0.5b)) let info try await RunAnywhere.registerModel( name: Qwen2.5 0.5B, url: https://huggingface.co/.../model.gguf, framework: .llamaCpp ) try await RunAnywhere.downloadModel(info) { progress in print(progress.percentage) } _ await RunAnywhere.loadModel(RAModelLoadRequest(modelID: info.id)) for await progress in RunAnywhere.downloadModelStream(info) { print(progress.state) }当前源码Public/API/Namespaces/ModelsNamespace.swift将模型能力收敛到RunAnywhere.models命名空间文档中的平铺动词对应演进为models.list(filter:)/models.get(id:)列出/获取注册表条目list支持按类别过滤如category: .languageget返回nil表示未知 idmodels.register(_:)注册支持URL、归档archive、多文件multiFile三种载荷多文件注册必须显式提供 id可附带框架、模态类别、内存需求、contextLength、thinking/LoRA 支持等元数据models.download(id:)返回AsyncThrowingStreamDownloadEvent, Error事件流保证以completed/failed/cancelled之一终止progress.percent0–100每个事件携带同一operationIdsequence单调递增models.isResumable(id:)从磁盘而非会话状态判断是否存在可续传字节启动下载本身就是续传见idl/download_service.proto用于 UI 诚实地标注 Resume/Getmodels.load(id:options:)显式加载生成动词会自动加载因此load仅用于希望自行决定何时付出加载成本的人注意LoadOptions目前只有backendPreferences.first能被原生加载 ABI 承载设置contextLength、threads、accelerator或多个有序 backendPreferences 会直接抛错而非静默丢弃models.unload(id:)幂等/models.unloadAll(category:)释放常驻模型models.delete(id:)删除已下载文件并重置注册表路径models.unregister(id:)仅移除注册元数据若模型仍加载或仍有本地文件会抛错models.state()报告每个类别的常驻模型与设备/应用/模型的存储占用models.refresh(rescanLocal:includeRemoteCatalog:pruneOrphans:)重扫托管目录并协调下载状态。关键的自动加载逻辑在ensureLoaded(modelId:category:fallbackCategories:downloadIfNeeded:loadOptions:)ModelsNamespace.swift当调用方指定了一个尚未下载的 modelId 时会先执行performDownload再加载modelId为 nil 时复用当前已加载的同类别模型。类别.unspecified会被当作.language处理defaultLoadCategory。LLM文本生成、流式与取消文档骨架let result try await RunAnywhere.generate(prompt: Explain vector databases in one line.) print(result.text) for await event in try await RunAnywhere.generateStream(prompt: Write a haiku.) { if let token event.token { print(token, terminator: ) } } await RunAnywhere.cancelGeneration()源码Public/API/Namespaces/LLMNamespace.swift中对应的是RunAnywhere.llm命名空间llm.generate(prompt:options:)/llm.generate(messages:options:)消息形式会把 system 轮折叠为options.systemPrompt末尾必须是 user 轮否则抛invalidInputllm.generateStream(prompt:options:)/llm.generateStream(messages:options:)返回AsyncThrowingStreamGenerationEvent, Error取消GenerationEvent流支持cancelled事件底层CppBridge.LLM.shared.cancelProto()在流终止时被触发onTermination回调。GenerationEvent见 Public/API/Events.swift的事件语法为统一的started→ 增量textDelta/reasoningDelta/toolCallAdded等→completed错误通过抛出而非负载字段传递。一个值得强调的实现细节流式结束绝不会伪造completed——若生产者未报告终止事件SDK 会以cancelled调用方主动取消或failed无终止事件收尾mapGenerationStream中sawTerminal检查。结构化输出let structured try await RunAnywhere.generateStructured(prompt: Extract fields, schema: schema) let extracted try RunAnywhere.extractStructuredOutput(text: raw, schema: schema)源码LLMNamespace.swift中generateStructured(prompt:schema:mode:options:)的mode决定约束方式.validationOnly默认自由生成后校验.repair校验失败后用一条包含原 prompt、无效输出与 schema 的修复提示structuredRepairPrompt见 LLMNamespace.swift重试一次.constrained引擎级约束解码——当前未接入调用直接抛notSupported异常。解析路径最终落到CppBridge.StructuredOutput.parseschema 采用JsonSchema类型。工具调用与内置 Web 搜索await RunAnywhere.registerTool(toolDefinition) { args in [result: RAToolValue(ok)] } let toolResult try await RunAnywhere.generateWithTools(prompt: Weather in Pune?) // Built-in web search tool (DuckDuckGo, over URLSession) await RunAnywhere.registerWebSearchTool() let def RunAnywhere.webSearchToolDefinition源码中工具收敛为RunAnywhere.llm.toolsLLMNamespace.swifttools.register(_:executor:)、tools.unregister(name:)、tools.list()、tools.clear()。生成时若注册表非空且toolChoice非.none则走generateWithTools工具调用循环。能力自省显示tools: .init(registry: true, parallel: false, cancellation: false)——即当前支持工具注册表但并行工具调用与工具取消尚不支持。内置 Web 搜索工具基于 DuckDuckGo、经由 URLSession 传输见 Public/Extensions/LLM/RunAnywhereWebSearchTool.swift。STT / TTS / VAD语音三件套文档骨架let transcript try await RunAnywhere.transcribe(audio: data) for await partial in RunAnywhere.transcribeStream(audio: audioStream) { print(partial.text) } let audio try await RunAnywhere.synthesize(Hello there) _ try await RunAnywhere.speak(Spoken aloud) await RunAnywhere.stopSpeaking() let vad try await RunAnywhere.detectVoiceActivity(data) for await r in RunAnywhere.streamVAD(audio: audioStream) { print(r.isSpeech) } try await RunAnywhere.resetVAD()源码Public/API/Namespaces/STTNamespace.swift中stt.transcribe(_:options:)一次转录输入为AudioInput支持 PCM/WAV见capabilities().audioFormats [.pcm, .wav]stt.openStream(format:options:)实时流式转录格式一次性确定必须为 raw PCM如pcmS16Le/pcmF32Le容器格式会被拒之后通过push逐帧喂入、finish结束TranscriptionEvent的transcriptFinal表示一个话语utterance结束而非会话结束——commons 在约 800ms 尾部静默后发布 FINAL但会话保持打开等待下一句stt.transcribeStream(_:options:)已标记 deprecated改用openStreamAsyncStreamAudioInput版本要求所有块共享同一AudioFormatSpec终端事件同样严格遵守completed/failed/cancelled语法pumpTranscriptionEvents中sawTerminal检查。TTS 与 VAD 分别位于 Public/Extensions/TTS/RunAnywhereTTS.swift 与 Public/Extensions/VAD/RunAnywhereVAD.swift对应命名空间为RunAnywhere.tts与RunAnywhere.vad。VLM视觉语言理解let out try await RunAnywhere.processImage(image, options: .defaults()) for await event in try await RunAnywhere.processImageStream(image, prompt: Describe this.) { print(event) } await RunAnywhere.cancelVLMGeneration()源码Public/API/Namespaces/VLMNamespace.swift中对应RunAnywhere.vlmvlm.generate(image:prompt:options:)图片 prompt 生成模型加载类别为.multimodal、回退.visionvlm.generateStream(image:prompt:options:)流式版本事件语法与llm.generateStream完全一致取消通过流的onTermination触发CppBridge.VLM.shared.cancel()。VLM 使用与 LLM 相同的LlmOptions/GenerationResultprompt 是参数而非 options 字段ImageInput支持文件、字节等输入形式相关 helper 见 Public/Extensions/VLM/RAVLMImageHelpers.swift。Diffusion图像生成Apple / CoreML 专属let image try await RunAnywhere.generateImage(options) for await event in try await RunAnywhere.generateImageStream(options) { print(event) } await RunAnywhere.cancelImageGeneration()文档特别注明Diffusion 仅限 Apple / CoreMLfacade 上没有inpaint便捷方法请使用generateImage。当前源码中这些平铺动词已标记 deprecated迁移目标为RunAnywhere.images命名空间见 Public/Extensions/Diffusion/RunAnywhereDiffusion.swiftimages.generate(prompt:options:)/images.generateStream(prompt:options:)取消方式改为取消消费该流stream的 Task。底层由CppBridge.Diffusion桥接 CoreML 运行时。RAG检索增强生成try await RunAnywhere.ragCreatePipeline(embeddingModel: emb, llmModel: llm) try await RunAnywhere.ragIngest(document) let answer try await RunAnywhere.ragQuery(question: What about pricing?) for await event in try await RunAnywhere.ragQueryStream(question: Summarize) { print(event) } await RunAnywhere.ragCancelQuery() // session-scoped cancel源码Public/API/Rag/RagNamespace.swift将其收敛为一次open 会话对象let session try await RunAnywhere.rag.open(embeddingModel: minilm, llmModel: qwen) try await session.ingest(document: RagDocument(text: notes))rag.open(embeddingModel:llmModel:config:)llmModel传nil可打开**仅检索retrieval-only**会话打开时自动ensureLoaded嵌入模型类别.embedding与 LLM类别.language再经CppBridge.RAG.shared.createPipeline创建原生索引RagSession提供ingest、query、流式查询与会话级取消能力自省显示rag: .init(multiSession: true, persistent: true)即支持多会话且持久化Public/API/Rag/RagSession.swift。LoRA 适配器try await RunAnywhere.lora.apply(catalogEntry, scale: 1.0) try await RunAnywhere.lora.applyCatalogAdapter(catalogEntry) let state try await RunAnywhere.lora.list() _ try await RunAnywhere.lora.download(catalogEntry) { p in print(p.percentage) }LoRA 由 Public/Extensions/LLM/RunAnywhereLoRA.swift 与 RunAnywhereLoRADownload.swift 提供应用适配器可指定scale、列出已加载 LoRA、下载目录条目并报告进度。语音 Agent端到端语音会话try await RunAnywhere.initializeVoiceAgentWithLoadedModels() for await event in RunAnywhere.streamVoiceAgent() { print(event) } let turn try await RunAnywhere.processVoiceTurn(data) await RunAnywhere.cleanupVoiceAgent()语音 Agent 由 Public/Extensions/VoiceAgent/RunAnywhereVoiceAgent.swift 与 VoiceAgentTypes.swift 承载。VoiceEvent的语法见 Public/API/Events.swift包含userTranscribed、agentStateChanged(.listening/.thinking/.speaking)、agentResponse等逐轮事件。事件订阅Combine 与回调RunAnywhere.events.llmEvents.sink { print($0) }.store(in: cancellables) RunAnywhere.events.modelLoaded.sink { print(loaded \($0.modelId)) }.store(in: cancellables) let id RunAnywhere.subscribeSDKEvents { event in print(event) } RunAnywhere.unsubscribeSDKEvents(id)事件系统位于 Public/API/Events.swift 与 Public/Events/EventBus.swiftCombine 发布者RunAnywhere.events暴露llmEvents、modelLoaded等发布者配合sink与AnyCancellable使用回调订阅subscribeSDKEvents { event in ... }返回订阅 id可用unsubscribeSDKEvents(id)退订模型生命周期事件另有 Public/Extensions/Events/EventBusModelLifecycle.swift 与 RunAnywhereSDKEvents.swift。使用注意事项文档 Notes 的源码印证文档在结尾列出四条注意事项全部可以在源码中找到印证推理调用为async部分throws流式返回AsyncStream源码中非流式调用返回async throws结果类型流式返回AsyncThrowingStreamEvent, Error事件语法统一为started → deltas → completed失败以抛出形式进入消费方绝不以负载字段夹带见 Events.swift。deviceId是 throwing computed property当前版本已演化为非抛出的String内部try?不可用时为空串且通过设备身份链解析安全存储 → vendor ID → 新合成 UUID。Diffusion 仅限 Apple/CoreMLfacade 无inpaint使用generateImage现为images.generate并注意runanywhere_mlx等 Apple 专属运行时仅在苹果平台打包。事件使用 Combine 发布者RunAnywhere.events.*系列即 Combine 发布者回调订阅为补充通道。进一步阅读官方 API 文档骨架core/docs/md/swift.mdSwift SDK 架构说明bindings/swift/ARCHITECTURE.md 与 bindings/swift/CLAUDE.md公共入口与初始化bindings/swift/Sources/RunAnywhere/Public/RunAnywhere.swift、环境类型 Public/Configuration/SDKEnvironment.swift各模态命名空间Public/API/Namespaces、扩展实现 Public/Extensions底层 C commons 初始化协议core/include/rac 中的rac_sdk_init.hproto 定义见 idl/sdk_init.proto 与 idl/llm_service.proto官方公开 API 对照参考各语言一致表面core/docs/PublicApiSwift.swift赞分享AI模型推理服务推理引擎本地部署多模态【免费下载链接】runanywhere-sdksProduction ready toolkit to run AI locally项目地址https://gitcode.com/gh_mirrors/ru/runanywhere-sdks点击查看免费下载相关推荐RunAnywhere Kotlin SDK 完整指南端侧 LLM / STT / TTS / VAD 全模态 API 实战RunAnywhere Kotlin SDK 完整指南端侧 LLM / STT / TTS / VAD 全模态 API 实战 本篇技术指南以 bindingsAI模型推理服务推理引擎本地部署多模态RunAnywhere Flutter SDK 实战指南在 iOS / Android 上端侧运行 LLM、语音与多模态 AIRunAnywhere Flutter SDK 实战指南在 iOS / Android 上端侧运行 LLM、语音与多模态 AI RunAnywhere FluAI模型推理服务推理引擎本地部署多模态RunAnywhere React Native SDK 实战指南基于 NitroModules/JSI 的端侧 AI 全能力调用RunAnywhere React Native SDK 实战指南基于 NitroModules/JSI 的端侧 AI 全能力调用 导读 本文以 RunAnyAI模型推理服务推理引擎本地部署多模态上一篇突破百万数据限制Luckysheet虚拟滚动技术实现高性能表格渲染下一篇android-sunflower中的深色模式切换用户体验无缝过渡创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表