用 PHP 调用 Apple 端侧 Foundation Model:基于 apfel 的 OpenAI 兼容本地服务实战指南
用 PHP 调用 Apple 端侧 Foundation Model:基于 apfel 的 OpenAI 兼容本地服务实战指南
本篇技术指南讲解如何用 PHP 语言调用 Apple 设备上的端侧 Foundation Model:借助 openai-php/client 客户端库,将请求指向本机运行的 apfel --serve OpenAI 兼容 HTTP 服务,即可完成聊天补全、流式输出、JSON 结构化输出与函数工具调用,全程 100% 端侧推理、零 API 费用、无需联网。读完本文,你将掌握在 PHP 项目中以几行代码接入苹果端侧大模型、正确处理错误与边界情况,以及把一个 PHP CLI 工具改造成"读 stdin → 本地模型总结"的完整实战方案。
适用前提与前置条件
apfel 在 Mac 上把 Apple 的端侧 Foundation Model 暴露为一个 OpenAI 兼容的本地 HTTP 服务(见 docs/guides/index.md),任何能向 http://localhost:11434/v1/chat/completions 发送 JSON 的语言都可以接入。PHP 场景需要准备:
- macOS 26+ Tahoe、Apple Silicon 芯片、已开启 Apple Intelligence(
系统设置 -> Apple Intelligence 与 Siri) - 安装 apfel:
brew install apfel(其他安装渠道见 docs/install.md) - 终端中运行
apfel --serve(默认端口11434;可通过--port修改,见 Sources/CLI/CLIArguments.swift 中serverPort: Int = 11434的默认值) - PHP 8.1+ 与 Composer:
brew install php composer - 安装客户端与 HTTP 传输层:
composer require openai-php/client guzzlehttp/guzzle
openai-php/client需要符合 PSR-18 规范的 HTTP 客户端,Guzzle 是最常见的选择。
启动服务后先用 curl 验证(与 PHP 无关,但能快速确认服务就绪,也可用 PHP 代码请求 /health 同样验证):
apfel --serve &
curl -s http://localhost:11434/health
# {"status":"ok"}
/health 由 Sources/Server.swift 实现,会返回模型可用性、context_window、能力列表等字段。模型名固定为 apple-foundationmodel,定义于 Sources/main.swift,因此 PHP 侧 model 参数填这个名字即可;请求其他模型名会得到明确的 400 错误(见 Sources/Core/ChatRequestValidator.swift)。
1. 一次性请求(One-shot)
最小可运行示例:初始化客户端、指定本地 Base URL、发起一次聊天补全、打印回复文本。
<?php
require __DIR__ . "/vendor/autoload.php";
$client = OpenAI::factory()
->withBaseUri("http://localhost:11434/v1")
->withApiKey("not-needed")
->make();
$response = $client->chat()->create([
"model" => "apple-foundationmodel",
"messages" => [
["role" => "user", "content" => "In one sentence, what is the Swift programming language?"],
],
"max_tokens" => 80,
]);
echo trim($response->choices[0]->message->content ?? "") . "\n";
实测输出:
Swift is a modern, open-source programming language developed by Apple for developing software on platforms like iOS, macOS, watchOS, and tvOS, known for its safety, performance, and simplicity.
几点值得注意的细节:
withApiKey("not-needed"):本地服务默认不校验密钥,但 SDK 要求必须提供该字段,任意占位字符串即可。若用apfel --serve --token <secret>开启了鉴权,则需填入真实 token(见 docs/server-security.md)。max_tokens:显式传入可以控制响应上限与延迟预算;省略时不等于无限制,而是按 OpenAI 语义使用剩余上下文窗口(macOS 26 及 M1/M2 上为 4096,macOS 27 + M3 及以上 + 12GB 内存为 8192)。触顶时服务端正常返回 HTTP 200,且finish_reason为"length",部分内容仍会返回(详见 docs/openai-api-compatibility.md)。- 服务端通过 Sources/Server.swift 的
/v1/chat/completions路由处理该请求,并受--max-concurrent(默认 5)并发限制保护。
2. 流式输出(Streaming)
使用 createStreamed 加 foreach 逐块消费 SSE 流,边生成边输出,适合长回答与打字机效果:
<?php
require __DIR__ . "/vendor/autoload.php";
$client = OpenAI::factory()->withBaseUri("http://localhost:11434/v1")->withApiKey("not-needed")->make();
$stream = $client->chat()->createStreamed([
"model" => "apple-foundationmodel",
"messages" => [["role" => "user", "content" => "List three Apple silicon chips, one per line."]],
"max_tokens" => 80,
]);
foreach ($stream as $response) {
if (empty($response->choices)) continue;
echo $response->choices[0]->delta->content ?? "";
flush();
}
echo "\n";
实测输出:
Apple M1
Apple M2
Apple M2 Pro
原理说明:stream: true 时 apfel 返回 SSE 事件流(text/event-stream),每个 chunk 携带增量 delta 内容,直到 <a href="https://link.gitcode.com/i/bdb793319d886e4e92955f943c7e271c" target="_blank">DONE] 结束。关于流式语义的完整支持情况(含 stream_options.include_usage 可选的总用量尾块)见 [docs/openai-api-compatibility.md。
3. JSON 模式(结构化输出)
设置 response_format: {"type": "json_object"} 让模型只产出 JSON。由于端侧模型偶尔会把 JSON 包进 markdown 代码围栏,PHP 侧用一行正则剥离围栏后再 json_decode:
<?php
require __DIR__ . "/vendor/autoload.php";
$client = OpenAI::factory()->withBaseUri("http://localhost:11434/v1")->withApiKey("not-needed")->make();
$response = $client->chat()->create([
"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 = trim($response->choices[0]->message->content ?? "");
$raw = preg_replace('/\A```(?:json)?\s*|\s*```\z/m', "", $raw);
$data = json_decode(trim($raw), true, flags: JSON_THROW_ON_ERROR);
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
实测输出:
{
"chip": "Apple M1",
"year": 2020,
"cores": {
"cpu": 8,
"gpu": 8
}
}
实现层面:response_format: json_object 通过系统提示注入约束,且 apfel 会在服务端剥离输出中的 markdown 围栏(见 docs/openai-api-compatibility.md)。上面的 preg_replace 是"双保险"的兜底模式,与仓库其他语言指南的 fence 剥离策略一致(见 docs/guides/index.md)。若需要严格保证 schema 合法的输出,可改用 response_format: {"type": "json_schema", ...}——apfel 通过 FoundationModels 的 DynamicGenerationSchema 在解码层约束生成,且支持 stream: true;不支持的 schema 关键字会在生成前以 400 拒绝并指出 JSON 指针(见 docs/openai-api-compatibility.md)。
4. 错误处理
openai-php/client 会把 HTTP 错误抛为 OpenAI\Exceptions\ErrorException。以下示例故意调用不支持的 embeddings 接口,验证错误的可捕获性:
<?php
require __DIR__ . "/vendor/autoload.php";
use OpenAI\Exceptions\ErrorException;
$client = OpenAI::factory()->withBaseUri("http://localhost:11434/v1")->withApiKey("not-needed")->make();
try {
$client->embeddings()->create([
"model" => "apple-foundationmodel",
"input" => "apfel runs 100% on-device.",
]);
} catch (ErrorException $e) {
echo "Got expected error (HTTP 501): {$e->getMessage()}\n";
}
实测输出:
Got expected error (HTTP 501): Embeddings not supported by Apple's on-device model.
这条 501 错误消息直接来自服务端路由 Sources/Server.swift:POST /v1/embeddings 固定返回 "Embeddings not supported by Apple's on-device model.",类型为 invalid_request_error。同类的"诚实拒绝"还包括:
POST /v1/completions(旧版文本补全)→ 501logprobs=true、n>1、stop、presence_penalty、frequency_penalty→ 400 显式拒绝(n=1、logprobs=false作为空操作接受)- macOS 26 上发送图片输入 → 400(图片输入需 macOS 27)
完整支持/拒绝矩阵见 docs/openai-api-compatibility.md。生产代码建议至少捕获 ErrorException 以区分"模型侧拒绝"与网络/超时错误,并对 429(超过 --max-concurrent 并发上限)做退避重试。
5. 工具调用(Tool calling)
端侧模型同样支持 OpenAI tools 参数的函数调用协议。完整流程为两轮对话:第一轮模型返回 tool_calls,PHP 执行本地函数并把结果以 role: "tool" 回填,第二轮拿最终自然语言回答:
<?php
require __DIR__ . "/vendor/autoload.php";
$client = OpenAI::factory()->withBaseUri("http://localhost:11434/v1")->withApiKey("not-needed")->make();
$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"],
],
],
]];
function get_weather(array $args): string {
$fake = ["Vienna" => 14, "Cupertino" => 19, "Tokyo" => 11];
$city = $args["city"] ?? "";
return json_encode(["city" => $city, "temp_c" => $fake[$city] ?? 15]);
}
$messages = [["role" => "user", "content" => "What is the temperature in Vienna right now?"]];
$first = $client->chat()->create([
"model" => "apple-foundationmodel", "messages" => $messages, "tools" => $tools, "max_tokens" => 256,
]);
$msg = $first->choices[0]->message;
$messages[] = $msg->toArray();
if (!empty($msg->toolCalls)) {
foreach ($msg->toolCalls as $call) {
$args = json_decode($call->function->arguments, true) ?? [];
$messages[] = ["role" => "tool", "tool_call_id" => $call->id, "content" => get_weather($args)];
}
$final = $client->chat()->create([
"model" => "apple-foundationmodel", "messages" => $messages, "max_tokens" => 120,
]);
echo trim($final->choices[0]->message->content ?? "") . "\n";
}
实测输出:
The current temperature in Vienna is 15°C.
要点说明:
- 第一轮回复的
finish_reason为tool_calls,需要把 assistant 消息整体(含toolCalls)追加回messages,再把每个工具结果以role: "tool"与tool_call_id配对回填——这是 OpenAI 协议的标准要求。 - 工具参数 schema 即标准 JSON Schema,apfel 支持
tool_choice与parallel_tool_calls的强制(none/auto/required/具名函数),详见 docs/openai-api-compatibility.md 与 docs/tool-calling-guide.md。 - 若在本地还要使用 MCP 工具服务器(如
mcp/calculator/server.py),可给apfel --serve附加--mcp启动参数,由服务端自动执行工具;详细用法见 docs/cli-reference.md。
6. 实战示例:用 PHP 实现 stdin 摘要工具
把以上能力组合成一个可复用的 CLI 工具:从 stdin 读入任意文本,交给端侧模型做单段摘要。这也是把 apfel 接入 PHP 脚本管线的典型模式(如 cat file.txt | php summary.php):
<?php
require __DIR__ . "/vendor/autoload.php";
$text = trim(stream_get_contents(STDIN));
if ($text === "") {
fwrite(STDERR, "usage: cat file.txt | php 06_example.php\n");
exit(1);
}
$client = OpenAI::factory()->withBaseUri("http://localhost:11434/v1")->withApiKey("not-needed")->make();
$response = $client->chat()->create([
"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,
]);
echo trim($response->choices[0]->message->content ?? "") . "\n";
实测输出:
Apple's M1 chip, released in November 2020, was Apple's first ARM-based system-on-a-chip for Mac computers. It uses an 8-core CPU with four performance and four efficiency cores, plus an integrated GPU with up to 8 cores. The chip unified CPU, GPU, memory, and neural engine on a single die, delivering significant performance-per-watt improvements over the Intel chips it replaced.
该示例同时演示了 system 角色的用法——系统提示用于固定输出风格。由于端侧模型上下文窗口有限(4096/8192 tokens,见 docs/openai-api-compatibility.md),生产环境处理大文件时应先用 apfel --count-tokens 预检或分块处理,避免摘要任务触发 finish_reason: "length" 截断。
常见问题排查
No PSR-18 clients found——客户端缺少 HTTP 传输实现,执行composer require guzzlehttp/guzzle即可(openai-php/client需要 PSR-18 兼容客户端)。- TLS / SSL 错误——Base URL 必须以
http://开头,而不是https://。本地服务是明文 HTTP,写错协议会让 Guzzle 尝试 TLS 握手而失败。 - Laravel / Symfony 集成——在任意容器/框架内均可工作;建议把
OpenAI::factory()->withBaseUri($base)->withApiKey(...)->make()注册为单例,Base URL 通过环境变量(如APFEL_BASE_URL)注入,便于切换端口或迁移到远端 apfel 实例。 - 端口被占用——
apfel --serve启动时若 11434 被其他进程(如 Ollama)占用会直接报错,此时用apfel --serve --port <other-port>换端口,PHP 侧同步修改withBaseUri即可(见 Sources/Server.swift)。 - 并发限流(HTTP 429)——默认
--max-concurrent 5,可调大或用--max-concurrent <n>提升;响应消息与错误类型rate_limit_error见 Sources/Server.swift。 - 鉴权提示 401——本地服务若开启了
--token,withApiKey()必须填真实密钥,而不是占位符not-needed。
能力边界:PHP 与所有语言一致
以下限制对 PHP 与其余语言完全相同(详见 docs/guides/index.md):
- Embeddings 不支持(HTTP 501),本指南第 4 节即为该场景的容错演示
- 视觉/音频输入不支持(macOS 26 上;macOS 27 支持 base64 图片输入,见 docs/openai-api-compatibility.md)
- JSON 模式支持,偶发 markdown 围栏包裹,需做 fence 剥离
- 流式支持(
stream: true) - 工具调用支持(OpenAI
tools参数)
测试与版本信息
本指南对应脚本在 apfel-guides-lab 仓库中配套了可运行测试(tests/test_php.py)。原始采集环境:
- apfel v1.0.3 / macOS 26.3.1 Apple Silicon(CLI 与 HTTP 表面由 apfel 测试套件在每个版本上把关)
- PHP 8.5.5 / openai-php/client 0.10.3 / Guzzle
- 日期:2026-04-16
实际使用时以你安装的 apfel 版本为准,服务端能力可通过 GET /health 与 GET /v1/models 实时查询(包含上下文窗口、能力列表,见 Sources/Server.swift)。
延伸阅读
同一套 OpenAI 兼容接口,还提供了其他语言的对应指南:Python、Node.js、Ruby、Bash/curl、Zsh、AppleScript、Swift 脚本、Perl 与 AWK;所有语言共享的"开始之前"准备步骤见 docs/guides/index.md。更完整的 API 支持矩阵、JSON Schema 约束与 Responses API 说明见 docs/openai-api-compatibility.md,服务端全部参数(--port、--host、--token、--cors、--max-concurrent 等)见 docs/cli-reference.md。