使用 Ruby 调用 Mac 端侧苹果 Foundation Model 完整指南(基于 apfel 本地 OpenAI 兼容服务)

原创2026-10-08 21:41:091,768 阅读

使用 Ruby 调用 Mac 端侧苹果 Foundation Model 完整指南(基于 apfel 本地 OpenAI 兼容服务)

apfel 将苹果 FoundationModels 框架中的端侧模型,以本地 OpenAI 兼容 HTTP 服务的形式暴露在 http://localhost:11434/v1。本篇指南讲解如何用 ruby-openai gem 从 Ruby(脚本、Rails 控制器或后台任务)调用该模型:单次请求、流式输出、JSON 模式、错误处理、工具调用(tool calling)与真实管线示例,全程 100% 端侧推理、零 API 费用、推理不需要网络。

前置条件

条件 说明
macOS 26+ Tahoe 需为 Apple Silicon(M1+),并已开启 Apple Intelligence(System Settings -> Apple Intelligence & Siri)
brew install apfel 安装 apfel CLI 工具;更多安装途径(Nix、源码构建等)见 docs/install.md
apfel --serve 在终端前台运行(默认端口 11434),或 brew services start apfel 后台常驻(见 docs/background-service.md)
Ruby 2.6+ macOS 系统自带
gem install ruby-openai 或 bundle add ruby-openai(测试版本:ruby-openai 7.4.0)

在运行任何 Ruby 脚本之前,先确认服务可用:

apfel --serve &
curl -s http://localhost:11434/health
# {"status":"ok"}

若 /health 返回 ok,说明服务已就绪;之后所有 Ruby 代码都基于同一个 OpenAI::Client 指向本地端点:

client = OpenAI::Client.new(
  uri_base: "http://localhost:11434",  # ruby-openai 会自动追加 /v1
  access_token: "not-needed"           # 端侧服务默认不要求 token,占位即可
)

注意:请求中的模型名固定为 apple-foundationmodel。GET /v1/models 返回的就是这个名字,并且带出运行时上下文窗口(context_window)与能力信息,见 Sources/Server.swift。

1. 单次请求(One-shot)

ruby-openai 的 chat 方法对应 OpenAI Chat Completions 接口,max_tokens 控制输出上限:

require "openai"

client = OpenAI::Client.new(
  uri_base: "http://localhost:11434",
  access_token: "not-needed"
)

response = client.chat(
  parameters: {
    model: "apple-foundationmodel",
    messages: [{ role: "user", content: "In one sentence, what is the Swift programming language?" }],
    max_tokens: 80
  }
)

puts response.dig("choices", 0, "message", "content").strip

真实输出:

Swift is a modern, high-performance, and versatile programming language designed for developing iOS, macOS, watchOS, and tvOS applications.

关于 max_tokens 的取舍:按 OpenAI 语义,省略 max_tokens 将使用剩余上下文窗口(macOS 26 及 M1/M2 为 4096,macOS 27 + M3 及以上 + 12 GB 内存为 8192,运行时可通过 apfel --model-info 读取当前值)。若模型触顶,会以 finish_reason: "length" 干净结束并返回 HTTP 200 及部分内容;需要更紧的延迟预算或已知上限时,应显式传 max_tokens(详见 docs/openai-api-compatibility.md)。

2. 流式输出(Streaming)

ruby-openai 通过回调 proc 消费 SSE 流,逐 chunk 打印增量内容并 flush 到 stdout:

require "openai"

client = OpenAI::Client.new(uri_base: "http://localhost:11434", access_token: "not-needed")

client.chat(
  parameters: {
    model: "apple-foundationmodel",
    messages: [{ role: "user", content: "List three Apple silicon chips, one per line." }],
    max_tokens: 80,
    stream: proc do |chunk, _bytesize|
      next if chunk.dig("choices").nil? || chunk["choices"].empty?
      piece = chunk.dig("choices", 0, "delta", "content")
      print piece if piece
      $stdout.flush
    end
  }
)
puts

真实输出:

Apple M1
Apple M2
Apple M3

SSE 协议细节:服务端每个 JSON chunk 以 data: {json}\n\n 帧发送,流结束发送 data: <a href="https://link.gitcode.com/i/87e5709d567153ba88d6d5456271d15e" target="_blank">DONE](见 [Sources/SSE.swift)。由于存在 [DONE] 这类不含 choices 的帧,回调里必须先判空 choices 再取 delta.content,这正是上面 next if 守卫的作用。若需要最终 usage 统计,可加 stream_options: { include_usage: true },服务端会在 [DONE] 前追加一个 choices 为空的 usage chunk。

3. JSON 模式(JSON mode)

端侧模型支持 response_format: { type: "json_object" }。模型偶尔会把输出包在 markdown 代码围栏里,所以文档里的实战模式是先剥掉围栏再 JSON.parse:

require "openai"
require "json"

client = OpenAI::Client.new(uri_base: "http://localhost:11434", access_token: "not-needed")

response = client.chat(
  parameters: {
    model: "apple-foundationmodel",
    messages: [{ role: "user", content: "Return JSON with fields 'chip', 'year', 'cores'. Describe the Apple M1 chip. Return ONLY JSON." }],
    response_format: { type: "json_object" },
    max_tokens: 120
  }
)

raw = response.dig("choices", 0, "message", "content").to_s.strip
raw = raw.sub(/\A```(?:json)?\s*/, "").sub(/\s*```\z/, "").strip
puts JSON.pretty_generate(JSON.parse(raw))

真实输出:

{
  "chip": "Apple M1",
  "year": 2020,
  "cores": {
    "cpu": 8,
    "gpu": 8
  }
}

服务端实现:response_format: json_object 通过系统提示注入 + 输出围栏剥离实现;更严格的 response_format: json_schema 则走 FoundationModels DynamicGenerationSchema 引导解码,保证输出符合 schema(不支持的 schema 关键字会在生成前以 HTTP 400 拒绝)。完整支持/拒绝清单见 docs/openai-api-compatibility.md。

4. 错误处理(Error handling)

端侧模型不提供 embeddings。apfel 服务端对 POST /v1/embeddings 和 POST /v1/completions 会诚实返回 HTTP 501(见 Sources/Server.swift),ruby-openai 将这类 HTTP 错误包装为 Faraday::Error 抛出:

require "openai"

client = OpenAI::Client.new(uri_base: "http://localhost:11434", access_token: "not-needed")

begin
  client.embeddings(parameters: { model: "apple-foundationmodel", input: "apfel runs 100% on-device." })
rescue Faraday::Error => e
  status = e.response && e.response[:status]
  puts "Got expected error: HTTP #{status} - #{e.message}"
end

真实输出:

Got expected error: HTTP 501 - the server responded with status 501

注意事项:

  • e.response[:status] 仅在 Faraday 携带完整响应对象抛出时存在;底层 socket 级错误时它为 nil,所以要先判 e.response 再取值。
  • 同样的 501 也覆盖其他端侧不可用能力:视觉/音频输入(macOS 26 下返回 400)、/v1/responses 上的 previous_response_id、store: true、hosted tools 等,完整矩阵见 docs/openai-api-compatibility.md。

5. 工具调用(Tool calling)

apfel 服务端原生支持 OpenAI tools 参数。Ruby 侧流程为:先发带 tools 的请求拿到 tool_calls,执行本地函数后把 role: "tool" 结果回填进消息列表,再发第二次请求得到最终回答:

require "openai"
require "json"

client = OpenAI::Client.new(uri_base: "http://localhost:11434", access_token: "not-needed")

TOOLS = [{
  type: "function",
  function: {
    name: "get_weather",
    description: "Get the current temperature in Celsius for a city.",
    parameters: {
      type: "object",
      properties: { city: { type: "string" } },
      required: ["city"]
    }
  }
}]

def get_weather(args)
  fake = { "Vienna" => 14, "Cupertino" => 19, "Tokyo" => 11 }
  { city: args["city"], temp_c: fake[args["city"]] || 15 }.to_json
end

messages = [{ role: "user", content: "What is the temperature in Vienna right now?" }]
first = client.chat(parameters: { model: "apple-foundationmodel", messages: messages, tools: TOOLS, max_tokens: 256 })
msg = first.dig("choices", 0, "message")
messages << msg

if msg["tool_calls"] && !msg["tool_calls"].empty?
  msg["tool_calls"].each do |call|
    args = JSON.parse(call.dig("function", "arguments"))
    messages << { role: "tool", tool_call_id: call["id"], content: get_weather(args) }
  end
  final = client.chat(parameters: { model: "apple-foundationmodel", messages: messages, max_tokens: 120 })
  puts final.dig("choices", 0, "message", "content").to_s.strip
end

真实输出:

The current temperature in Vienna is 14 degrees Celsius.

协议细节:第一轮响应中 message.tool_calls 携带 id、function.name 与 JSON 字符串形式的 function.arguments;第二轮必须带上 role: "tool" 且 tool_call_id 与第一轮 call<a href="https://link.gitcode.com/i/d16867ebda74c67011132d3317f20d64" target="_blank">"id"] 对应。服务端还强制支持 tool_choice 与 parallel_tool_calls(none/auto/required 及具名函数;parallel_tool_calls: false 时最多返回一个调用),详见 [docs/tool-calling-guide.md。此外,apfel --serve 还可通过 --mcp 挂载 MCP 工具,由服务端自动执行(仅 Chat Completions 路径)。

6. 实战示例:用 stdin 内容做摘要

把管道输入喂给模型做摘要,system 角色设定行为约束,user 消息携带待摘要文本。这是 Rails 后台任务、CI 脚本中可复用的最小形态:

require "openai"

text = $stdin.read.strip
if text.empty?
  warn "usage: cat file.txt | ruby 06_example.rb"
  exit 1
end

client = OpenAI::Client.new(uri_base: "http://localhost:11434", access_token: "not-needed")

response = client.chat(
  parameters: {
    model: "apple-foundationmodel",
    messages: [
      { role: "system", content: "You are a concise summarizer. Reply with one short paragraph." },
      { role: "user", content: "Summarize:\n\n#{text}" }
    ],
    max_tokens: 150
  }
)
puts response.dig("choices", 0, "message", "content").to_s.strip

真实输出:

The Apple M1 chip, launched in November 2020, marked Apple's first ARM-based system-on-a-chip for Mac computers. It features an 8-core CPU with four performance and four efficiency cores, along with an integrated GPU that can have up to 8 cores. The chip integrates CPU, GPU, memory, and neural engine on a single die, offering significant performance-per-watt improvements over its Intel predecessors.

常见问题排查

  • Connection refused:先启动 apfel --serve 再运行 Ruby 脚本。若端口被占用(例如其他进程如 Ollama 监听 11434),可用 apfel --serve --port <other-port> 换端口,并同步修改 uri_base。
  • e.response[:status] 为 nil:仅当 Faraday 带着完整响应对象抛出时才存在;底层 socket 错误时为 nil,先判 e.response 再解包。
  • Rails 集成:上述模式无需改动即可放进 Rails controller 或后台 job——使用同一个指向 localhost 的 OpenAI::Client 实例即可。对耗时调用建议放入后台 job(服务端默认 --max-concurrent 为 5,超出会返回 429 rate_limit_error,见 Sources/Server.swift)。
  • 其他语言:Ruby 之外还提供 Python、Node.js、PHP、bash/curl、zsh、AppleScript、Swift、Perl、AWK 的对应指南,见 docs/guides/index.md。

各语言一致的诚实边界

  • 上下文窗口:4096 tokens(macOS 26 及 M1/M2)或 8192 tokens(macOS 27 + M3 及以上 + 12 GB,即 Apple AFM 3 Core Advanced 模型),运行时以 apfel --model-info 为准。
  • Embeddings:不支持,返回 HTTP 501(见上文第 4 节)。
  • 视觉 / 音频:不支持;macOS 26 下图像输入返回 400,macOS 27 起支持 base64 data URL 图像输入。
  • JSON 模式:通过 response_format: {type: "json_object"} 支持,偶尔包在 markdown 围栏中,因此指南给出单行剥围栏模式。
  • 流式:stream: true 支持。
  • 工具调用:通过 OpenAI tools 参数支持。

测试环境与验证

  • apfel v1.0.3 / macOS 26.3.1 Apple Silicon(原始采集环境;本指南使用的 CLI 与 HTTP 接口在每个版本上都由 apfel 测试套件门禁保护)
  • Ruby 2.6.10(系统自带)/ ruby-openai 7.4.0
  • 日期:2026-04-16

apfel 的集成测试在 Tests/integration/openai_client_test.py 中对 /v1/chat/completions、流式、种子确定性、/v1/completions 与 /v1/embeddings 的 501 stub(test_completions_stub_501、test_embeddings_stub_501,见该文件 L655-L666)以及 Responses API 均有覆盖,可直接作为服务端行为的验证参考。

参见

登录后查看全文
apfel