squishling-apple_fm 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +33 -0
- data/LICENSE +201 -0
- data/README.md +90 -0
- data/Rakefile +12 -0
- data/SECURITY.md +28 -0
- data/docs/how-it-works.md +84 -0
- data/lib/squishling/apple_fm/adapter.rb +117 -0
- data/lib/squishling/apple_fm/generation_schema.rb +111 -0
- data/lib/squishling/apple_fm/helper.rb +137 -0
- data/lib/squishling/apple_fm/helper.swift +108 -0
- data/lib/squishling/apple_fm/version.rb +7 -0
- data/lib/squishling/apple_fm.rb +28 -0
- data/squishling-apple_fm.gemspec +45 -0
- metadata +79 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: f97e80f00f3372ce23f28c676a1ffd338ea30d12cbd75b873838cc01ab9ac2cc
|
|
4
|
+
data.tar.gz: 9e8caee2e3c3dbdac8cc77e3882d4c62b894d8fd4faa6b49ab4be861aaf2d4dc
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: e75902b790a2a7f30644cb4718225bbd344160f31ad1999c014bddcdfbf149e251e264089fdb9c916d16980c43b002ded9ec6cfeeb26f30216dfed6bf15f3c56
|
|
7
|
+
data.tar.gz: 81292e378a9671f34d37e105601c8080b68b08e80cf0a125aa2653f5a39276145ea29bb7be5144a3c12872f0ce767fe5f1edcaa00753b94d7a7cd892283ae8ec
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [0.1.0] - 2026-11-01
|
|
11
|
+
|
|
12
|
+
First release.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- A Squishling adapter for Apple Intelligence, registered as `:apple_fm`: Squishling's LLM calls run on the on-device
|
|
17
|
+
model built into macOS 26 and later (Apple Foundation Models), with no API key, no network, and no cost. Meant for
|
|
18
|
+
developing against Squishling locally; the model is small (4096-token context window) and macOS-only. Options:
|
|
19
|
+
`timeout:`, `helper:`, `cache_dir:`. Needs Squishling 0.5.0 or later. (#1, #4)
|
|
20
|
+
- A small Swift helper that the gem compiles with your own `swiftc` on first use, caches by the source's digest, and runs
|
|
21
|
+
once per request over stdin/stdout JSON. Nothing is downloaded or shipped prebuilt. (#1)
|
|
22
|
+
- Strict structured output: Squishling's strict schema is translated into Apple's guided generation, and Squishling still
|
|
23
|
+
validates every answer against your full schema. (#1)
|
|
24
|
+
- A reply cut off by `max_output_tokens` is reported to Squishling as a cutoff (`finish_reason: :max_tokens`), so
|
|
25
|
+
`InvalidOutputError#truncated?` says so instead of a generic failure. (#4)
|
|
26
|
+
- Live smoke tests in `examples/` (`quickstart.rb` and `apple_fm_example.rb`) for a Mac with Apple Intelligence. (#4)
|
|
27
|
+
|
|
28
|
+
### Security
|
|
29
|
+
|
|
30
|
+
- The helper is started with no shell, so a cache or helper path containing spaces or shell characters (for example a
|
|
31
|
+
home directory like `/Users/Mary Ann`) is run as given instead of being split or interpreted.
|
|
32
|
+
- The helper cache directories are created with mode 0700.
|
|
33
|
+
- A blank `helper:` or `cache_dir:` is rejected with a `ConfigurationError` instead of building under the filesystem root.
|
data/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
data/README.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# squishling-apple_fm
|
|
2
|
+
|
|
3
|
+
[Squishling](https://github.com/Coolhand-Labs/squishling) adapter for **Apple Intelligence**: run your Ruby LLM calls
|
|
4
|
+
on the on-device model built into macOS 26 and later (Apple Foundation Models). No API key, no network, no cost, so
|
|
5
|
+
you can try Squishling and develop against it locally, then run production on a hosted model.
|
|
6
|
+
|
|
7
|
+
```ruby
|
|
8
|
+
# Gemfile
|
|
9
|
+
gem "squishling"
|
|
10
|
+
gem "squishling-apple_fm", group: :development
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ruby
|
|
14
|
+
Squishling.configure do |config|
|
|
15
|
+
config.adapter = :apple_fm if Rails.env.development? # or any check that says "on my Mac"
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
class SentimentClassifier
|
|
19
|
+
include Squishling
|
|
20
|
+
|
|
21
|
+
purpose "Classify the sentiment of the review."
|
|
22
|
+
output_schema do
|
|
23
|
+
string :sentiment, enum: %w[positive negative neutral]
|
|
24
|
+
optional(:quote) { string }
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
SentimentClassifier.call(review: "Loved it, would buy again!")
|
|
29
|
+
# => #<data sentiment="positive", quote=nil>, the same typed result a hosted model returns
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Requirements
|
|
33
|
+
|
|
34
|
+
- macOS 26 or later on Apple Silicon, with **Apple Intelligence turned on** (System Settings).
|
|
35
|
+
- Xcode or its Command Line Tools (`xcode-select --install`). Apple's FoundationModels framework is Swift-only, so the
|
|
36
|
+
gem bundles a small Swift program and compiles it with your `swiftc` the first time it is needed (a few seconds). The
|
|
37
|
+
binary is cached under `~/Library/Caches/squishling/apple_fm`, so later calls start in under a second.
|
|
38
|
+
- Ruby 3.3+ and Squishling 0.5 or later.
|
|
39
|
+
|
|
40
|
+
It adds no other gem, runs no server, and makes no network request.
|
|
41
|
+
|
|
42
|
+
## Options
|
|
43
|
+
|
|
44
|
+
```ruby
|
|
45
|
+
config.adapter = { type: :apple_fm, timeout: 60 }
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
| Option | Default | Description |
|
|
49
|
+
|---|---|---|
|
|
50
|
+
| `timeout` | `120` | Seconds to wait for an answer before the call fails with an `LLMError`. |
|
|
51
|
+
| `helper` | compiled from the bundled source | The path of a prebuilt helper to run instead. |
|
|
52
|
+
| `cache_dir` | `~/Library/Caches/squishling/apple_fm` (or under `$XDG_CACHE_HOME`) | Where compiled helpers are kept. |
|
|
53
|
+
|
|
54
|
+
The system has one model, so `model:` and `provider:` are ignored. `temperature` and `max_output_tokens` are sent;
|
|
55
|
+
other params raise `Squishling::ConfigurationError`.
|
|
56
|
+
|
|
57
|
+
## Know the limits
|
|
58
|
+
|
|
59
|
+
This is a small on-device model, for **developing** the shape of a call, not for judging its quality:
|
|
60
|
+
|
|
61
|
+
- The **context window is 4096 tokens** for the prompt, schema, and answer together; a call that doesn't fit is an `LLMError`.
|
|
62
|
+
- An **optional nested object** (`optional { object { ... } }`) often comes back `null` even when the input has the
|
|
63
|
+
value; in testing, an optional scalar was filled in reliably. Make the object required, with `[]` or `""` for "none"
|
|
64
|
+
in its fields, when it matters.
|
|
65
|
+
- It picks between choices less reliably than a hosted model.
|
|
66
|
+
|
|
67
|
+
## Documentation
|
|
68
|
+
|
|
69
|
+
- **[How it works](docs/how-it-works.md)**: the Swift helper and its cache, how schemas are translated for Apple's guided
|
|
70
|
+
generation, how failures map to Squishling's errors, limits, and troubleshooting.
|
|
71
|
+
- [Squishling's adapters](https://github.com/Coolhand-Labs/squishling/blob/main/docs/adapters.md): the adapter contract
|
|
72
|
+
and the other adapters.
|
|
73
|
+
- [Changelog](CHANGELOG.md)
|
|
74
|
+
|
|
75
|
+
## Development
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
bundle install
|
|
79
|
+
bundle exec rake # RSpec (offline: the Swift helper is stubbed) + RuboCop
|
|
80
|
+
bin/exhale dry --include-tests # duplication gate
|
|
81
|
+
bin/exhale complexity # complexity gate
|
|
82
|
+
bundle exec ruby examples/quickstart.rb # live smoke test, on a Mac with Apple Intelligence
|
|
83
|
+
bundle exec ruby examples/apple_fm_example.rb # the full live suite, same requirements
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
See [AGENTS.md](AGENTS.md) for the design invariants and the release process.
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
|
|
90
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
data/Rakefile
ADDED
data/SECURITY.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Security Policy
|
|
2
|
+
|
|
3
|
+
## Supported Versions
|
|
4
|
+
|
|
5
|
+
Only the latest published version of `squishling-apple_fm` on RubyGems is supported with security fixes.
|
|
6
|
+
Please upgrade to the latest version before reporting an issue.
|
|
7
|
+
|
|
8
|
+
## Reporting a Vulnerability
|
|
9
|
+
|
|
10
|
+
Please do **not** open a public GitHub issue for security vulnerabilities.
|
|
11
|
+
|
|
12
|
+
Instead, report vulnerabilities privately using one of the following:
|
|
13
|
+
|
|
14
|
+
- [GitHub Security Advisories](https://github.com/Coolhand-Labs/squishling-apple-fm-adapter/security/advisories/new)
|
|
15
|
+
for this repository (preferred)
|
|
16
|
+
- Email team@coolhandlabs.com
|
|
17
|
+
|
|
18
|
+
Please include a description of the vulnerability, steps to reproduce, and the impact you believe
|
|
19
|
+
it has. We aim to acknowledge reports within 3 business days and to provide a fix or mitigation
|
|
20
|
+
plan within 30 days, depending on severity.
|
|
21
|
+
|
|
22
|
+
## What this gem runs
|
|
23
|
+
|
|
24
|
+
The gem compiles `lib/squishling/apple_fm/helper.swift` with the `swiftc` on your machine and runs the resulting binary
|
|
25
|
+
(cached under `~/Library/Caches/squishling/apple_fm`, or `$XDG_CACHE_HOME`) once per request. It never downloads or ships
|
|
26
|
+
a prebuilt binary. Anyone who can write to that cache directory can already run code as you, so keep it user-private;
|
|
27
|
+
the `helper:` option runs whatever path you give it. Reports about the helper, the cache, or the request/response
|
|
28
|
+
handling are in scope.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# How it works
|
|
2
|
+
|
|
3
|
+
`squishling-apple_fm` runs Squishling's requests on Apple's on-device model (Apple Intelligence, through the
|
|
4
|
+
FoundationModels framework). Squishling builds the request, this adapter makes one completion, and Squishling does the
|
|
5
|
+
rest: validation, retries and escalation, harnesses, `squawk`, and fallbacks. See
|
|
6
|
+
[Squishling's adapter contract](https://github.com/Coolhand-Labs/squishling/blob/main/docs/adapters.md#writing-your-own).
|
|
7
|
+
|
|
8
|
+
## The Swift helper
|
|
9
|
+
|
|
10
|
+
FoundationModels is Swift-only: it has no C or Objective-C interface, so Ruby can't call it directly. The gem ships one
|
|
11
|
+
small Swift program, `lib/squishling/apple_fm/helper.swift`.
|
|
12
|
+
|
|
13
|
+
- **Built on first use** with the `swiftc` from Xcode or its Command Line Tools, into
|
|
14
|
+
`~/Library/Caches/squishling/apple_fm/<digest of the source>/helper` (under `$XDG_CACHE_HOME` when that is set, or in
|
|
15
|
+
`cache_dir:`). A new gem version with a changed source builds a new binary; old ones stay until you delete the
|
|
16
|
+
directory. The build takes a few seconds, runs under a file lock so concurrent processes build once, and is renamed into
|
|
17
|
+
place so nobody runs a half-written file. The cache directories are created readable only by you (mode 0700), because
|
|
18
|
+
the binary's path is predictable; if you point `cache_dir:` at a directory that others can write to, they could put a
|
|
19
|
+
binary there, so keep it private.
|
|
20
|
+
- **One process per request.** Ruby writes one JSON request to its stdin and reads one JSON line from its stdout, so there
|
|
21
|
+
is no server, no shared state, and Squishling's concurrent samples each get their own process (about 0.8 seconds per
|
|
22
|
+
call once built, mostly model time).
|
|
23
|
+
- **Private protocol.** The request is `{ instructions, messages, schema, temperature?, max_tokens? }`; the answer is
|
|
24
|
+
`{ content, usage?, finish_reason? }` or `{ error: <code> }`. Apple's own error messages never leave the helper, only a code.
|
|
25
|
+
- **Token counts** (`usage`) come from FoundationModels on macOS 26.4 and later; on 26.0 to 26.3 there are none.
|
|
26
|
+
- `helper:` runs a prebuilt binary instead, for example one built in CI or by your own tooling. It is run as given, with
|
|
27
|
+
no shell, so a path with spaces or other special characters works.
|
|
28
|
+
|
|
29
|
+
## Schemas
|
|
30
|
+
|
|
31
|
+
Squishling always sends a strict schema: every key required, `optional` fields as `anyOf: [T, null]`. Apple's guided
|
|
32
|
+
generation reads its own JSON Schema dialect, so the adapter translates it, and the model is constrained to the result:
|
|
33
|
+
|
|
34
|
+
| Squishling's schema | Sent to the model |
|
|
35
|
+
|---|---|
|
|
36
|
+
| objects | a `title`, `x-order` (the property order), and `additionalProperties: false` |
|
|
37
|
+
| `anyOf: [T, null]` (`optional`) | the same, with a `title` on the union (a real nullable) |
|
|
38
|
+
| `type: ["string", "null"]` (raw schemas) | split into `anyOf` |
|
|
39
|
+
| `$ref` / `$defs` | inlined (a schema that refers to itself raises `ConfigurationError`) |
|
|
40
|
+
| `enum`, `minimum`, `maximum`, `minItems`, `maxItems`, `description` | kept |
|
|
41
|
+
| `pattern`, `minLength`, `maxLength`, `format`, `const`, `default`, … | left out |
|
|
42
|
+
|
|
43
|
+
What is left out can't guide the model (some of it makes generation fail), but **Squishling validates every answer
|
|
44
|
+
against your full schema anyway**, so a value that breaks a `pattern` is still rejected and retried.
|
|
45
|
+
|
|
46
|
+
## Failures
|
|
47
|
+
|
|
48
|
+
| What happened | Raised | Notes |
|
|
49
|
+
|---|---|---|
|
|
50
|
+
| Not macOS, or an Apple Silicon Mac without macOS 26 | `ConfigurationError` | never retried |
|
|
51
|
+
| Apple Intelligence off, or the device ineligible | `ConfigurationError` | the message says to turn it on |
|
|
52
|
+
| `swiftc` missing, the compile fails, or the cache isn't writable | `ConfigurationError` | the message gives the command to run |
|
|
53
|
+
| A schema the model can't generate | `ConfigurationError` | |
|
|
54
|
+
| A param other than `temperature` / `max_output_tokens` | `ConfigurationError` | |
|
|
55
|
+
| A reply cut off by `max_output_tokens` | invalid output (retried) | the framework only reports a decoding failure, so any decoding failure with a limit set is treated as a cutoff; the answer is empty and `finish_reason` is `:max_tokens`, so Squishling says it was a cutoff. Raise the limit or ask for less |
|
|
56
|
+
| Prompt, schema, and answer over 4096 tokens | `LLMError` | depends on the input, so a retry or fallback may help |
|
|
57
|
+
| Apple's guardrails decline, a rate limit, the model still downloading, an unsupported language | `LLMError` | |
|
|
58
|
+
| The helper crashes, answers with garbage, or takes longer than `timeout` | `LLMError` | a timed-out helper is killed |
|
|
59
|
+
|
|
60
|
+
Messages carry only the kind of failure. The system's own message, the helper's stderr, and the model's output never
|
|
61
|
+
appear in an error or log.
|
|
62
|
+
|
|
63
|
+
## Limits of the model
|
|
64
|
+
|
|
65
|
+
It is a small on-device model, so it is for developing the shape of a call:
|
|
66
|
+
|
|
67
|
+
- **4096-token context window**, shared by the instructions, the conversation (a retry replays the rejected answer), the
|
|
68
|
+
schema, and the answer.
|
|
69
|
+
- **An optional nested object comes back `null`.** Given a note that says "Heart rate 88", `optional :vitals { object {
|
|
70
|
+
integer :heart_rate } }` was `null` in 10 of 10 runs, while the same field required returned 88 in 10 of 10, and a
|
|
71
|
+
flat `optional(:heart_rate) { integer }` returned 88 in 10 of 10. The schema sent is the expected
|
|
72
|
+
`anyOf: [object, null]`, so whether this is the model's preference for the `null` branch or something in how the
|
|
73
|
+
union is written is not established; an earlier note that reordering the union or describing the field doesn't help
|
|
74
|
+
has not been re-checked. Make the object required, with `[]` or `""` for "none" in its fields, if it matters.
|
|
75
|
+
- **It chooses less reliably** than a hosted model between enum values, so a classification can differ from production's.
|
|
76
|
+
|
|
77
|
+
## Troubleshooting
|
|
78
|
+
|
|
79
|
+
- `turn on Apple Intelligence in System Settings`: System Settings → Apple Intelligence & Siri. The first run may also
|
|
80
|
+
download the model (`the on-device model isn't ready yet`); retry in a few minutes.
|
|
81
|
+
- `swiftc wasn't found`: `xcode-select --install`, or install Xcode.
|
|
82
|
+
- `compiling the apple_fm helper failed`: run the `swiftc` command in the message to see Swift's own output. The framework
|
|
83
|
+
needs Xcode 26 or later.
|
|
84
|
+
- A stale or suspect binary: delete `~/Library/Caches/squishling/apple_fm`; it rebuilds on the next call.
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Squishling
|
|
4
|
+
module AppleFM
|
|
5
|
+
# Runs requests on the on-device model built into macOS (Apple Intelligence, through the FoundationModels
|
|
6
|
+
# framework): free, offline, and private, so a good fit for developing against Squishling without an API key or a
|
|
7
|
+
# bill. It needs macOS 26 or later on Apple Silicon with Apple Intelligence turned on, and Xcode (or its Command
|
|
8
|
+
# Line Tools) to compile a small Swift helper on first use. No gem, no server, no network. The model is small
|
|
9
|
+
# (a 4096-token context window for the prompt, the schema, and the answer), so expect to develop here and run
|
|
10
|
+
# production on a bigger model. See the README.
|
|
11
|
+
#
|
|
12
|
+
# Squishling.configure do |config|
|
|
13
|
+
# config.adapter = :apple_fm
|
|
14
|
+
# end
|
|
15
|
+
class Adapter < Squishling::Adapter::Base
|
|
16
|
+
# What Response#model reports: the system has one model and doesn't name it.
|
|
17
|
+
MODEL = "apple-foundation-model"
|
|
18
|
+
PORTABLE_PARAMS = %i[temperature max_output_tokens].freeze
|
|
19
|
+
TOKEN_KEYS = %w[input_tokens output_tokens].freeze
|
|
20
|
+
# The helper's error codes. A setup mistake is never retried; the rest depend on the input or the moment, so
|
|
21
|
+
# another attempt may work. Only these texts are used: the system's own message is never repeated.
|
|
22
|
+
SETUP_FAILURES = {
|
|
23
|
+
"device_not_eligible" => "this Mac can't run Apple Intelligence",
|
|
24
|
+
"apple_intelligence_not_enabled" => "turn on Apple Intelligence in System Settings",
|
|
25
|
+
"unsupported_schema" => "the schema uses something the on-device model can't generate",
|
|
26
|
+
"bad_request" => "the helper couldn't read the request"
|
|
27
|
+
}.freeze
|
|
28
|
+
FAILURES = {
|
|
29
|
+
"context_window" => "the prompt, schema, and answer didn't fit the model's 4096-token context window",
|
|
30
|
+
"guardrail" => "the model declined the request (Apple's safety guardrails)",
|
|
31
|
+
"unsupported_language" => "the model doesn't support the language of the request",
|
|
32
|
+
"rate_limited" => "the system rate-limited the request",
|
|
33
|
+
"model_not_ready" => "the on-device model isn't ready yet (it may still be downloading)"
|
|
34
|
+
}.freeze
|
|
35
|
+
private_constant :PORTABLE_PARAMS, :TOKEN_KEYS, :SETUP_FAILURES, :FAILURES
|
|
36
|
+
|
|
37
|
+
# timeout: seconds to wait for an answer before giving up (an LLMError). helper: the path of a prebuilt helper
|
|
38
|
+
# to run instead of compiling the bundled one. cache_dir: where compiled helpers are kept (default
|
|
39
|
+
# ~/Library/Caches/squishling/apple_fm, or under $XDG_CACHE_HOME). Raises ConfigurationError for a bad option.
|
|
40
|
+
def initialize(timeout: 120, helper: nil, cache_dir: nil)
|
|
41
|
+
super()
|
|
42
|
+
invalid(:timeout, "a positive number", timeout) unless timeout.is_a?(Numeric) && timeout.positive?
|
|
43
|
+
@timeout = timeout
|
|
44
|
+
@helper = Helper.new(path: path(:helper, helper), cache_dir: path(:cache_dir, cache_dir))
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def complete(request)
|
|
48
|
+
answer = @helper.call(payload(request), timeout: @timeout)
|
|
49
|
+
if answer["content"].is_a?(String)
|
|
50
|
+
return Squishling::Adapter::Response.new(content: answer["content"], model: MODEL,
|
|
51
|
+
tokens: tokens_of(answer["usage"]), finish_reason: finish_reason_of(answer))
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
raise failure(request, answer["error"].to_s)
|
|
55
|
+
rescue Helper::Unavailable => e
|
|
56
|
+
raise configuration_error(request, e.message)
|
|
57
|
+
rescue Helper::Failed => e
|
|
58
|
+
raise llm_error(request, e.message)
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
private
|
|
62
|
+
|
|
63
|
+
def payload(request)
|
|
64
|
+
{ "instructions" => request.instructions, "messages" => messages(request),
|
|
65
|
+
"schema" => GenerationSchema.call(request.schema["schema"]) }.merge(generation_options(request))
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def messages(request)
|
|
69
|
+
request.messages.map { |message| { "role" => message[:role].to_s, "content" => message[:content] } }
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# The system has no reasoning mode and takes no provider-specific params.
|
|
73
|
+
def generation_options(request)
|
|
74
|
+
params = request.params
|
|
75
|
+
unsupported = params.keys - PORTABLE_PARAMS
|
|
76
|
+
unsupported -= [:thinking] unless params[:thinking]
|
|
77
|
+
unless unsupported.empty?
|
|
78
|
+
raise configuration_error(request, "the on-device model takes only the temperature and max_output_tokens " \
|
|
79
|
+
"params, not #{unsupported.join(', ')}")
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
{ "temperature" => params[:temperature], "max_tokens" => params[:max_output_tokens] }.compact
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# The helper counts tokens on macOS 26.4 and later; before that it sends none.
|
|
86
|
+
def tokens_of(usage)
|
|
87
|
+
return {} unless usage.is_a?(Hash)
|
|
88
|
+
|
|
89
|
+
usage.slice(*TOKEN_KEYS).select { |_, count| count.is_a?(Integer) }.transform_keys(&:to_sym)
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# The helper reports only a reply that max_output_tokens cut off; it has no other reason to give.
|
|
93
|
+
def finish_reason_of(answer)
|
|
94
|
+
:max_tokens if answer["finish_reason"] == "max_tokens"
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def failure(request, code)
|
|
98
|
+
return configuration_error(request, SETUP_FAILURES[code]) if SETUP_FAILURES.key?(code)
|
|
99
|
+
|
|
100
|
+
llm_error(request, FAILURES.fetch(code, "the on-device model failed"))
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def path(name, value)
|
|
104
|
+
return nil if value.nil?
|
|
105
|
+
|
|
106
|
+
text = value.respond_to?(:to_path) ? value.to_path : value
|
|
107
|
+
return text if text.is_a?(String) && !text.strip.empty?
|
|
108
|
+
|
|
109
|
+
invalid(name, "a path", value)
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def invalid(name, expected, value)
|
|
113
|
+
raise ConfigurationError, "adapter :apple_fm #{name} must be #{expected}, got #{value.inspect}"
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
end
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Squishling
|
|
4
|
+
module AppleFM
|
|
5
|
+
# Rewrites a strict output schema into the JSON Schema dialect Apple's on-device model decodes
|
|
6
|
+
# (FoundationModels' GenerationSchema), for AppleFM::Adapter. It keeps only the keywords the model can be
|
|
7
|
+
# guided by and adds the ones Apple's decoder insists on; Squishling's own validation still enforces the rest.
|
|
8
|
+
module GenerationSchema
|
|
9
|
+
# Everything else (pattern, minLength, format, const, ...) is dropped: the model fails to generate with some of
|
|
10
|
+
# them, and none can be guided, so local validation decides.
|
|
11
|
+
KEPT = %w[type enum description properties required items anyOf minimum maximum minItems maxItems].freeze
|
|
12
|
+
SCHEMA_MAPS = %w[properties $defs definitions].freeze
|
|
13
|
+
MAX_REF_DEPTH = 16
|
|
14
|
+
private_constant :KEPT, :SCHEMA_MAPS, :MAX_REF_DEPTH
|
|
15
|
+
|
|
16
|
+
module_function
|
|
17
|
+
|
|
18
|
+
# name: the title of the root object. Raises ConfigurationError for a schema that refers to itself.
|
|
19
|
+
def call(schema, name: "Response")
|
|
20
|
+
decorate(prune(inline(schema, schema, 0)), name)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# $ref to a local definition becomes the definition itself; Apple's decoder has no references.
|
|
24
|
+
def inline(node, root, depth)
|
|
25
|
+
case node
|
|
26
|
+
when Array then node.map { |item| inline(item, root, depth) }
|
|
27
|
+
when Hash then inline_hash(node, root, depth)
|
|
28
|
+
else node
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def inline_hash(node, root, depth)
|
|
33
|
+
return inline_ref(node["$ref"], root, depth) if node["$ref"].is_a?(String)
|
|
34
|
+
|
|
35
|
+
node.to_h { |key, value| [key, inline_value(key, value, root, depth)] }
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def inline_ref(ref, root, depth)
|
|
39
|
+
if depth > MAX_REF_DEPTH
|
|
40
|
+
raise ConfigurationError,
|
|
41
|
+
"squishling-apple_fm can't use a schema that refers to itself"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
inline(definition(root, ref), root, depth + 1)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Property and definition names are data, never keywords or references.
|
|
48
|
+
def inline_value(key, value, root, depth)
|
|
49
|
+
return inline(value, root, depth) unless SCHEMA_MAPS.include?(key) && value.is_a?(Hash)
|
|
50
|
+
|
|
51
|
+
value.transform_values { |schema| inline(schema, root, depth) }
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def definition(root, ref)
|
|
55
|
+
return root if ref == "#"
|
|
56
|
+
|
|
57
|
+
found = ref.delete_prefix("#/").split("/").reduce(root) { |node, key| node.is_a?(Hash) ? node[key] : nil }
|
|
58
|
+
return found if found.is_a?(Hash)
|
|
59
|
+
|
|
60
|
+
raise ConfigurationError, "squishling-apple_fm can't resolve the schema reference #{ref.inspect}"
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Drops every keyword outside KEPT. Property names are data and stay, so only a schema's keywords are filtered.
|
|
64
|
+
def prune(node)
|
|
65
|
+
return node unless node.is_a?(Hash)
|
|
66
|
+
return prune(split_types(node)) if node["type"].is_a?(Array)
|
|
67
|
+
|
|
68
|
+
node.slice(*KEPT).to_h { |key, value| [key, prune_value(key, value)] }
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# type: ["string", "null"] is anyOf: [{ type: "string" }, { type: "null" }], the form Apple's decoder reads.
|
|
72
|
+
def split_types(node)
|
|
73
|
+
shared = node.except("type", "description")
|
|
74
|
+
shared["enum"] = shared["enum"].compact if shared["enum"].is_a?(Array) && node["type"].include?("null")
|
|
75
|
+
branches = node["type"].map { |type| type == "null" ? { "type" => "null" } : shared.merge("type" => type) }
|
|
76
|
+
{ "anyOf" => branches }.merge(node.slice("description"))
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def prune_value(key, value)
|
|
80
|
+
case key
|
|
81
|
+
when "properties" then value.transform_values { |schema| prune(schema) }
|
|
82
|
+
when "items" then prune(value)
|
|
83
|
+
when "anyOf" then value.map { |schema| prune(schema) }
|
|
84
|
+
else value
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# Apple's decoder wants a title on every object and anyOf node, the property order, and an explicit
|
|
89
|
+
# additionalProperties. A title on a plain branch would make it a "named type", so branches stay bare.
|
|
90
|
+
def decorate(node, name)
|
|
91
|
+
return node unless node.is_a?(Hash)
|
|
92
|
+
|
|
93
|
+
if node["anyOf"] then decorate_union(node, name)
|
|
94
|
+
elsif node["type"] == "object" then decorate_object(node, name)
|
|
95
|
+
elsif node["type"] == "array" then node.merge("items" => decorate(node["items"], "#{name}Item"))
|
|
96
|
+
else node
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def decorate_union(node, name)
|
|
101
|
+
node.merge("title" => name, "anyOf" => node["anyOf"].map { |branch| decorate(branch, name) })
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def decorate_object(node, name)
|
|
105
|
+
properties = (node["properties"] || {}).to_h { |key, schema| [key, decorate(schema, key)] }
|
|
106
|
+
node.merge("title" => name, "properties" => properties, "x-order" => properties.keys,
|
|
107
|
+
"required" => node["required"] || [], "additionalProperties" => false)
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
end
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "fileutils"
|
|
5
|
+
require "json"
|
|
6
|
+
require "open3"
|
|
7
|
+
|
|
8
|
+
module Squishling
|
|
9
|
+
module AppleFM
|
|
10
|
+
# The small Swift program AppleFM::Adapter talks to. Apple's FoundationModels framework is Swift-only (no C or
|
|
11
|
+
# Objective-C interface), so something Swift has to call it: apple_fm/helper.swift reads one JSON request on stdin
|
|
12
|
+
# and writes one JSON answer on stdout. It is compiled on first use with the swiftc that ships with Xcode or the
|
|
13
|
+
# Command Line Tools, and the binary is cached by the source's digest, so later calls (and later processes) start
|
|
14
|
+
# it directly. A call is one process, so there is no shared state between threads.
|
|
15
|
+
class Helper
|
|
16
|
+
SOURCE = File.join(__dir__, "helper.swift")
|
|
17
|
+
|
|
18
|
+
# The helper can't run here (not macOS, no compiler, it won't compile): a setup mistake.
|
|
19
|
+
class Unavailable < StandardError
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# The helper ran but produced no answer (it crashed, or took too long): worth another attempt.
|
|
23
|
+
class Failed < StandardError
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# path: a prebuilt helper to use instead of compiling the bundled source. cache_dir: where compiled helpers go.
|
|
27
|
+
def initialize(path: nil, cache_dir: nil)
|
|
28
|
+
@path = path
|
|
29
|
+
@cache_dir = cache_dir || default_cache_dir
|
|
30
|
+
@build_lock = Mutex.new
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Sends request (a Hash) and returns the helper's answer (a Hash). Raises Unavailable or Failed.
|
|
34
|
+
def call(request, timeout:)
|
|
35
|
+
command = executable
|
|
36
|
+
# [command, command] is the program and its argv[0], run as given: a bare String with a space or a shell
|
|
37
|
+
# metacharacter in it (a home directory like "/Users/Mary Ann") would be split or handed to /bin/sh.
|
|
38
|
+
Open3.popen2([command, command], err: File::NULL) do |stdin, stdout, wait|
|
|
39
|
+
send_request(stdin, request)
|
|
40
|
+
reader = Thread.new { stdout.read }
|
|
41
|
+
timed_out = reader.join(timeout).nil?
|
|
42
|
+
kill(wait.pid) if timed_out
|
|
43
|
+
answer(timed_out ? nil : reader.value, wait.value, timeout)
|
|
44
|
+
end
|
|
45
|
+
rescue Errno::ENOENT, Errno::EACCES
|
|
46
|
+
raise Unavailable, "the apple_fm helper #{command.inspect} can't be run"
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
private
|
|
50
|
+
|
|
51
|
+
# The helper may exit on its own between the timeout and the kill.
|
|
52
|
+
def kill(pid)
|
|
53
|
+
Process.kill("KILL", pid)
|
|
54
|
+
rescue Errno::ESRCH
|
|
55
|
+
nil
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def send_request(stdin, request)
|
|
59
|
+
stdin.write(JSON.generate(request))
|
|
60
|
+
rescue Errno::EPIPE
|
|
61
|
+
nil # the helper already exited; its status explains why
|
|
62
|
+
ensure
|
|
63
|
+
stdin.close
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def answer(output, status, timeout)
|
|
67
|
+
raise Failed, "the helper took longer than #{timeout}s" if output.nil?
|
|
68
|
+
|
|
69
|
+
parsed = JSON.parse(output.to_s.dup.force_encoding(Encoding::UTF_8))
|
|
70
|
+
return parsed if parsed.is_a?(Hash)
|
|
71
|
+
|
|
72
|
+
raise Failed, "the helper answered with something other than a JSON object"
|
|
73
|
+
rescue JSON::ParserError
|
|
74
|
+
raise Failed, "the helper produced no answer (#{describe(status)})"
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def describe(status)
|
|
78
|
+
status.signaled? ? "signal #{status.termsig}" : "exit #{status.exitstatus}"
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Built once per process, and again if the cache was cleared since.
|
|
82
|
+
def executable
|
|
83
|
+
@build_lock.synchronize do
|
|
84
|
+
@executable = nil unless @executable && File.executable?(@executable)
|
|
85
|
+
@executable ||= @path || build
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def build
|
|
90
|
+
unless RUBY_PLATFORM.include?("darwin")
|
|
91
|
+
raise Unavailable, "Apple's on-device model needs macOS 26 or later on Apple Silicon"
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
target = File.join(@cache_dir, Digest::SHA256.file(SOURCE).hexdigest[0, 16], "helper")
|
|
95
|
+
compile(target) unless File.executable?(target)
|
|
96
|
+
target
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# Compiled to a temporary name and renamed into place, under a file lock so that concurrent processes build
|
|
100
|
+
# once and none runs a half-written binary. The directories it creates are private to the user: the binary's
|
|
101
|
+
# path is predictable (the source's digest), so nobody else may be able to put a file there.
|
|
102
|
+
def compile(target)
|
|
103
|
+
FileUtils.mkdir_p(File.dirname(target), mode: 0o700)
|
|
104
|
+
File.open("#{target}.lock", File::RDWR | File::CREAT) do |lock|
|
|
105
|
+
lock.flock(File::LOCK_EX)
|
|
106
|
+
next if File.executable?(target)
|
|
107
|
+
|
|
108
|
+
temporary = "#{target}.#{Process.pid}.tmp"
|
|
109
|
+
swiftc(temporary)
|
|
110
|
+
File.rename(temporary, target)
|
|
111
|
+
end
|
|
112
|
+
rescue SystemCallError
|
|
113
|
+
raise Unavailable, "the apple_fm helper can't be built in #{@cache_dir.inspect}; give the adapter a writable " \
|
|
114
|
+
"cache_dir:"
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def swiftc(output)
|
|
118
|
+
command = ["swiftc", "-O", SOURCE, "-o", output]
|
|
119
|
+
_, status = Open3.capture2e(*command)
|
|
120
|
+
return if status.success?
|
|
121
|
+
|
|
122
|
+
FileUtils.rm_f(output)
|
|
123
|
+
raise Unavailable, "compiling the apple_fm helper failed; run `#{command.join(' ')}` to see why " \
|
|
124
|
+
"(it needs Xcode 26 or later, or its Command Line Tools)"
|
|
125
|
+
rescue Errno::ENOENT
|
|
126
|
+
raise Unavailable, "swiftc wasn't found; install Xcode or run `xcode-select --install`"
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
# $XDG_CACHE_HOME when it is set and not empty (the XDG spec treats empty as unset), else ~/Library/Caches.
|
|
130
|
+
def default_cache_dir
|
|
131
|
+
base = ENV.fetch("XDG_CACHE_HOME", "").strip
|
|
132
|
+
base = File.join(Dir.home, "Library", "Caches") if base.empty?
|
|
133
|
+
File.join(base, "squishling", "apple_fm")
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
end
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import FoundationModels
|
|
3
|
+
|
|
4
|
+
// Reads one JSON request on stdin, writes one JSON line on stdout. Exit status is 0 whenever a line was written.
|
|
5
|
+
// Request: {"instructions": String?, "messages": [{"role": "user"|"assistant", "content": String}],
|
|
6
|
+
// "schema": <JSON Schema decodable as GenerationSchema>, "temperature": Double?, "max_tokens": Int?}
|
|
7
|
+
// Success: {"content": String, "usage": {"input_tokens": Int, "output_tokens": Int}?, "finish_reason": "max_tokens"?}
|
|
8
|
+
// Failure: {"error": <code>}, never the model's or the system's own message
|
|
9
|
+
|
|
10
|
+
func emit(_ object: [String: Any]) -> Never {
|
|
11
|
+
let data = (try? JSONSerialization.data(withJSONObject: object, options: [])) ?? Data("{\"error\":\"other\"}".utf8)
|
|
12
|
+
FileHandle.standardOutput.write(data)
|
|
13
|
+
FileHandle.standardOutput.write(Data("\n".utf8))
|
|
14
|
+
exit(0)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
func segments(_ text: String) -> [Transcript.Segment] {
|
|
18
|
+
[.text(Transcript.TextSegment(content: text))]
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
func unavailability(_ model: SystemLanguageModel) -> String? {
|
|
22
|
+
switch model.availability {
|
|
23
|
+
case .available: return nil
|
|
24
|
+
case .unavailable(let reason):
|
|
25
|
+
switch reason {
|
|
26
|
+
case .deviceNotEligible: return "device_not_eligible"
|
|
27
|
+
case .appleIntelligenceNotEnabled: return "apple_intelligence_not_enabled"
|
|
28
|
+
case .modelNotReady: return "model_not_ready"
|
|
29
|
+
@unknown default: return "unavailable"
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Token counts need macOS 26.4; on anything older, or if counting fails, the answer simply carries no usage.
|
|
35
|
+
func usage(_ model: SystemLanguageModel, entries: [Transcript.Entry], schema: GenerationSchema, answer: String) async -> [String: Int] {
|
|
36
|
+
guard #available(macOS 26.4, *) else { return [:] }
|
|
37
|
+
var counts: [String: Int] = [:]
|
|
38
|
+
if let prompt = try? await model.tokenCount(for: entries), let shape = try? await model.tokenCount(for: schema) {
|
|
39
|
+
counts["input_tokens"] = prompt + shape
|
|
40
|
+
}
|
|
41
|
+
if let generated = try? await model.tokenCount(for: answer) { counts["output_tokens"] = generated }
|
|
42
|
+
return counts
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
func failure(_ error: Error) -> String {
|
|
46
|
+
guard let generation = error as? LanguageModelSession.GenerationError else { return "other" }
|
|
47
|
+
switch generation {
|
|
48
|
+
case .exceededContextWindowSize: return "context_window"
|
|
49
|
+
case .guardrailViolation: return "guardrail"
|
|
50
|
+
case .unsupportedLanguageOrLocale: return "unsupported_language"
|
|
51
|
+
case .rateLimited: return "rate_limited"
|
|
52
|
+
case .assetsUnavailable: return "model_not_ready"
|
|
53
|
+
default: return "generation"
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// With max_tokens set, a reply cut off at the limit is truncated JSON that the framework can't decode, and it reports
|
|
58
|
+
// only a decoding failure, so any decoding failure with a limit set is treated as a cutoff. The partial text isn't
|
|
59
|
+
// kept: the answer is empty and says why, so Squishling can tell a cutoff from a wrong answer.
|
|
60
|
+
func isCutoff(_ error: Error, limit: Int?) -> Bool {
|
|
61
|
+
guard limit != nil, let generation = error as? LanguageModelSession.GenerationError else { return false }
|
|
62
|
+
if case .decodingFailure = generation { return true }
|
|
63
|
+
return false
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
let input = FileHandle.standardInput.readDataToEndOfFile()
|
|
67
|
+
guard let request = (try? JSONSerialization.jsonObject(with: input)) as? [String: Any],
|
|
68
|
+
let messages = request["messages"] as? [[String: String]], let last = messages.last,
|
|
69
|
+
let schemaObject = request["schema"] else { emit(["error": "bad_request"]) }
|
|
70
|
+
|
|
71
|
+
let model = SystemLanguageModel.default
|
|
72
|
+
if let reason = unavailability(model) { emit(["error": reason]) }
|
|
73
|
+
|
|
74
|
+
let schema: GenerationSchema
|
|
75
|
+
do {
|
|
76
|
+
let data = try JSONSerialization.data(withJSONObject: schemaObject)
|
|
77
|
+
schema = try JSONDecoder().decode(GenerationSchema.self, from: data)
|
|
78
|
+
} catch { emit(["error": "unsupported_schema"]) }
|
|
79
|
+
|
|
80
|
+
var entries: [Transcript.Entry] = []
|
|
81
|
+
if let instructions = request["instructions"] as? String, !instructions.isEmpty {
|
|
82
|
+
entries.append(.instructions(Transcript.Instructions(segments: segments(instructions), toolDefinitions: [])))
|
|
83
|
+
}
|
|
84
|
+
for message in messages.dropLast() {
|
|
85
|
+
let text = message["content"] ?? ""
|
|
86
|
+
if message["role"] == "assistant" {
|
|
87
|
+
entries.append(.response(Transcript.Response(assetIDs: [], segments: segments(text))))
|
|
88
|
+
} else {
|
|
89
|
+
entries.append(.prompt(Transcript.Prompt(segments: segments(text))))
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
var options = GenerationOptions()
|
|
94
|
+
if let temperature = request["temperature"] as? Double { options.temperature = temperature }
|
|
95
|
+
let limit = request["max_tokens"] as? Int
|
|
96
|
+
if let limit { options.maximumResponseTokens = limit }
|
|
97
|
+
|
|
98
|
+
do {
|
|
99
|
+
let session = LanguageModelSession(model: model, tools: [], transcript: Transcript(entries: entries))
|
|
100
|
+
let prompt = last["content"] ?? ""
|
|
101
|
+
let response = try await session.respond(to: prompt, schema: schema, options: options)
|
|
102
|
+
let asked = entries + [.prompt(Transcript.Prompt(segments: segments(prompt)))]
|
|
103
|
+
let counts = await usage(model, entries: asked, schema: schema, answer: response.content.jsonString)
|
|
104
|
+
emit(["content": response.content.jsonString, "usage": counts])
|
|
105
|
+
} catch {
|
|
106
|
+
if isCutoff(error, limit: limit) { emit(["content": "", "finish_reason": "max_tokens"]) }
|
|
107
|
+
emit(["error": failure(error)])
|
|
108
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "squishling"
|
|
4
|
+
|
|
5
|
+
# The squishling-apple_fm adapter registers itself with the pluggable-adapters API, so an older Squishling can't use it.
|
|
6
|
+
unless Squishling.respond_to?(:register_adapter)
|
|
7
|
+
raise LoadError, "squishling-apple_fm needs a Squishling release with pluggable adapters " \
|
|
8
|
+
"(Squishling.register_adapter); you have Squishling #{Squishling::VERSION}. Upgrade squishling."
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
require_relative "apple_fm/version"
|
|
12
|
+
require_relative "apple_fm/generation_schema"
|
|
13
|
+
require_relative "apple_fm/helper"
|
|
14
|
+
require_relative "apple_fm/adapter"
|
|
15
|
+
|
|
16
|
+
module Squishling
|
|
17
|
+
# Runs Squishling on the on-device model built into macOS (Apple Intelligence). Requiring this gem registers the
|
|
18
|
+
# adapter as :apple_fm; see Squishling::AppleFM::Adapter.
|
|
19
|
+
module AppleFM
|
|
20
|
+
# Registers the adapter under :apple_fm unless it is already there. Called when the gem loads; call it again
|
|
21
|
+
# after Squishling.reset_adapters!, which forgets every adapter that isn't built in.
|
|
22
|
+
def self.register
|
|
23
|
+
Squishling.register_adapter(:apple_fm, Adapter) unless Squishling.adapters.include?(:apple_fm)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
Squishling::AppleFM.register
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "lib/squishling/apple_fm/version"
|
|
4
|
+
|
|
5
|
+
Gem::Specification.new do |spec|
|
|
6
|
+
spec.name = "squishling-apple_fm"
|
|
7
|
+
spec.version = Squishling::AppleFM::VERSION
|
|
8
|
+
spec.authors = ["Michael Carroll"]
|
|
9
|
+
spec.email = ["mc@coolhandlabs.com"]
|
|
10
|
+
|
|
11
|
+
spec.summary = "Squishling adapter for Apple's on-device model (Apple Intelligence): free, offline LLM calls in " \
|
|
12
|
+
"development."
|
|
13
|
+
spec.description = "A Squishling adapter that runs Ruby LLM calls on the Apple Foundation Models on-device model " \
|
|
14
|
+
"built into macOS 26 and later (Apple Intelligence): no API key, no network, no cost. Meant " \
|
|
15
|
+
"for trying Squishling and developing against it locally, then running production on a " \
|
|
16
|
+
"hosted model. Strict structured output is translated into Apple's guided generation; the " \
|
|
17
|
+
"framework is Swift-only, so a small bundled Swift helper is compiled with the Xcode " \
|
|
18
|
+
"toolchain on first use."
|
|
19
|
+
spec.homepage = "https://github.com/Coolhand-Labs/squishling-apple-fm-adapter"
|
|
20
|
+
spec.license = "Apache-2.0"
|
|
21
|
+
spec.required_ruby_version = ">= 3.3"
|
|
22
|
+
|
|
23
|
+
spec.metadata["allowed_push_host"] = "https://rubygems.org"
|
|
24
|
+
|
|
25
|
+
spec.metadata["homepage_uri"] = spec.homepage
|
|
26
|
+
spec.metadata["source_code_uri"] = spec.homepage
|
|
27
|
+
spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/main/CHANGELOG.md"
|
|
28
|
+
spec.metadata["documentation_uri"] = "#{spec.homepage}/tree/main/docs"
|
|
29
|
+
|
|
30
|
+
# Ship only what's tracked in git, minus development-only files.
|
|
31
|
+
dev_files = %w[AGENTS.md CLAUDE.md]
|
|
32
|
+
dev_prefixes = %w[bin/ test/ spec/ features/ examples/ assets/
|
|
33
|
+
.git .claude .idea .rubocop .simplecov .rspec Gemfile]
|
|
34
|
+
spec.files = Dir.chdir(__dir__) do
|
|
35
|
+
`git ls-files -z`.split("\x0").reject do |f|
|
|
36
|
+
File.expand_path(f) == __FILE__ || dev_files.include?(f) || f.start_with?(*dev_prefixes)
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
spec.require_paths = ["lib"]
|
|
40
|
+
|
|
41
|
+
# 0.5.0 is the first Squishling release with pluggable adapters (Squishling.register_adapter).
|
|
42
|
+
spec.add_dependency "squishling", ">= 0.5.0"
|
|
43
|
+
|
|
44
|
+
spec.metadata["rubygems_mfa_required"] = "true"
|
|
45
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: squishling-apple_fm
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Michael Carroll
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: squishling
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
- - ">="
|
|
17
|
+
- !ruby/object:Gem::Version
|
|
18
|
+
version: 0.5.0
|
|
19
|
+
type: :runtime
|
|
20
|
+
prerelease: false
|
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
22
|
+
requirements:
|
|
23
|
+
- - ">="
|
|
24
|
+
- !ruby/object:Gem::Version
|
|
25
|
+
version: 0.5.0
|
|
26
|
+
description: 'A Squishling adapter that runs Ruby LLM calls on the Apple Foundation
|
|
27
|
+
Models on-device model built into macOS 26 and later (Apple Intelligence): no API
|
|
28
|
+
key, no network, no cost. Meant for trying Squishling and developing against it
|
|
29
|
+
locally, then running production on a hosted model. Strict structured output is
|
|
30
|
+
translated into Apple''s guided generation; the framework is Swift-only, so a small
|
|
31
|
+
bundled Swift helper is compiled with the Xcode toolchain on first use.'
|
|
32
|
+
email:
|
|
33
|
+
- mc@coolhandlabs.com
|
|
34
|
+
executables: []
|
|
35
|
+
extensions: []
|
|
36
|
+
extra_rdoc_files: []
|
|
37
|
+
files:
|
|
38
|
+
- CHANGELOG.md
|
|
39
|
+
- LICENSE
|
|
40
|
+
- README.md
|
|
41
|
+
- Rakefile
|
|
42
|
+
- SECURITY.md
|
|
43
|
+
- docs/how-it-works.md
|
|
44
|
+
- lib/squishling/apple_fm.rb
|
|
45
|
+
- lib/squishling/apple_fm/adapter.rb
|
|
46
|
+
- lib/squishling/apple_fm/generation_schema.rb
|
|
47
|
+
- lib/squishling/apple_fm/helper.rb
|
|
48
|
+
- lib/squishling/apple_fm/helper.swift
|
|
49
|
+
- lib/squishling/apple_fm/version.rb
|
|
50
|
+
- squishling-apple_fm.gemspec
|
|
51
|
+
homepage: https://github.com/Coolhand-Labs/squishling-apple-fm-adapter
|
|
52
|
+
licenses:
|
|
53
|
+
- Apache-2.0
|
|
54
|
+
metadata:
|
|
55
|
+
allowed_push_host: https://rubygems.org
|
|
56
|
+
homepage_uri: https://github.com/Coolhand-Labs/squishling-apple-fm-adapter
|
|
57
|
+
source_code_uri: https://github.com/Coolhand-Labs/squishling-apple-fm-adapter
|
|
58
|
+
changelog_uri: https://github.com/Coolhand-Labs/squishling-apple-fm-adapter/blob/main/CHANGELOG.md
|
|
59
|
+
documentation_uri: https://github.com/Coolhand-Labs/squishling-apple-fm-adapter/tree/main/docs
|
|
60
|
+
rubygems_mfa_required: 'true'
|
|
61
|
+
rdoc_options: []
|
|
62
|
+
require_paths:
|
|
63
|
+
- lib
|
|
64
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
65
|
+
requirements:
|
|
66
|
+
- - ">="
|
|
67
|
+
- !ruby/object:Gem::Version
|
|
68
|
+
version: '3.3'
|
|
69
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
70
|
+
requirements:
|
|
71
|
+
- - ">="
|
|
72
|
+
- !ruby/object:Gem::Version
|
|
73
|
+
version: '0'
|
|
74
|
+
requirements: []
|
|
75
|
+
rubygems_version: 3.6.9
|
|
76
|
+
specification_version: 4
|
|
77
|
+
summary: 'Squishling adapter for Apple''s on-device model (Apple Intelligence): free,
|
|
78
|
+
offline LLM calls in development.'
|
|
79
|
+
test_files: []
|