How Do You Call the Mac's Built-in Apple Intelligence Model from .NET?
Getting to know the model
This post is based on macOS 27.2, Xcode 27.2 and .NET 10.
Since macOS 26, a Mac with Apple Intelligence has a built-in on-device language model, which the Foundation Models framework makes available to apps.
It runs locally: no API key, no server, no charge per use, and the data never leaves the computer.
I am building a Markdown editor, and its AI features used to require users to enter their own API key or set up a local model. For someone who only wants AI to summarize a passage, that is a real hurdle, so I tried letting a .NET program use this built-in model directly.
This post covers how I connected it, the problems I ran into along the way, and what the model is actually good for.
1️⃣ Getting to know the model
The Foundation Models framework gives you the on-device model behind Apple Intelligence. To use it, all of these must hold:
- A Mac with Apple Silicon (Intel Macs are not supported)
- macOS 26 or later
- The user has turned on Apple Intelligence in System Settings
- The model has finished downloading
It is a small model with a small context (the amount of text the model can take in at once, input and output together). My Mac on macOS 27.2 reports 8,192 tokens.
Most of what it can and cannot do follows from that size. The value may change between system versions, so query it with the framework's contextSize in code rather than hard-coding it.
One more thing to know up front: .NET calls native code through C functions (P/Invoke) or through Objective-C (the bindings on Apple platforms, since most Apple frameworks have an Objective-C interface).
Foundation Models, though, is a new Swift-only framework with no Objective-C interface, and it relies heavily on Swift's async, generics and macros, none of which have a C equivalent. Neither path connects, so the only option is to add a Swift adapter layer of your own in between.
2️⃣ The options in .NET
At the time of writing, I found roughly three approaches:
- Use Microsoft's
Microsoft.Maui.Essentials.AI. It provides anIChatClientfor this model, with more features (image support, for example). However, its Apple client only exists for platform-specific target frameworks such asnet11.0-ios,net11.0-maccatalystandnet11.0-macos, and it is still in preview. If your app is already MAUI or built for those target frameworks, this is the easiest choice. - Go through a local HTTP service. Some community tools wrap the model as an OpenAI-compatible API, so the .NET side calls it like any OpenAI service. The upside is that you never touch native code; the downside is that users have to install and start a separate program.
- Write your own Swift bridge and call it with P/Invoke. You write a small dynamic library in Swift that exposes only C functions, and .NET calls it with
LibraryImport. An ordinarynet10.0program (a console app, an Avalonia desktop app) can use it, with no change of target framework and no extra service.
My editor is an Avalonia app built for plain net10.0, and the same code has to run on Windows and Linux, so switching to a platform-specific target framework does not pay off. Asking users to install a service brings back the very hurdle I wanted to remove.
So I took the third path, and later turned this layer into an open-source package, Polhem.AI.Apple. Most of what follows only comes up on this path, but the model's own limits and the schema problems apply whichever path you take.
3️⃣ The bridge: C functions exported from Swift
Swift can export a function with the C calling convention through @_cdecl. The whole bridge exposes only a few functions: check the status, get the context size, start a generation, cancel, and release.
A generation request goes over as JSON, and text and the final status come back through callbacks:
public typealias TextCallback = @convention(c) (UnsafeMutableRawPointer?, UnsafePointer<CChar>?) -> Void
public typealias DoneCallback = @convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer<CChar>?) -> Void
@_cdecl("bridge_respond")
public func bridge_respond(_ requestJson: UnsafePointer<CChar>, _ context: UnsafeMutableRawPointer?, _ onText: TextCallback, _ onDone: DoneCallback) -> UnsafeMutableRawPointer {
// Generates in a Swift Task and returns a handle for cancelling and releasing it.
}
On the .NET side, I use the source-generated LibraryImport with function pointers, and mark the callback methods with [UnmanagedCallersOnly]. That needs no delegate marshalling and works with Native AOT (publishing ahead of time to native code, which cannot generate marshalling code at run time):
[LibraryImport("MyBridge", EntryPoint = "bridge_respond", StringMarshalling = StringMarshalling.Utf8)]
internal static unsafe partial nint Respond(string requestJson, nint context, delegate* unmanaged[Cdecl]<nint, byte*, void> onText, delegate* unmanaged[Cdecl]<nint, int, byte*, void> onDone);
context is a .NET object wrapped in a GCHandle, which lets the static callbacks find out which request they belong to.
With asynchronous calls across languages, lifetimes are where things most easily go wrong:
- The completion can arrive before the handle. When a request fails as soon as it is sent, Swift calls the completion callback before
Respondhas returned the handle. So the handle has to be released by whichever comes later, "got the handle" or "got the completion", with a lock in between. - A cancel can arrive before the Task. When a cancel request comes in, the Swift Task may not yet be stored in the object behind the handle. I record that cancellation was requested, and call
cancel()again once the Task is stored. - A released handle can no longer be cancelled. Before calling the native cancel function, the .NET side checks, under the same lock, that the handle is still there.
Two more points about the build:
- Weak-link the framework and target an older macOS. The library is compiled for macOS 14, with FoundationModels weak-linked through
-weak_framework. It then loads even on a macOS without the framework and reports "not supported" when asked for its status, instead of failing as soon as it loads. On the Swift side,#available(macOS 26.0, *)guards the actual calls. - Build for arm64 only. Intel Macs cannot run Apple Intelligence, so on Intel Macs, Windows and Linux the .NET side checks the platform first and never loads the library at all, reporting the model as unavailable. An app can then reference the same code on every platform and offer this model only on machines that can use it.
I put the Swift compile in an MSBuild target, so dotnet build on macOS compiles it with swiftc automatically, and packing places it in the NuGet package under runtimes/osx-arm64/native/.
One thing to watch when publishing: single-file publishing (PublishSingleFile) does not bundle native libraries into the executable by default. The library is a separate file that has to sit next to the executable (for example in an .app's Contents/MacOS). To bundle it, publish with -p:IncludeNativeLibrariesForSelfExtract=true.
4️⃣ Fitting IChatClient: turning a stateful session stateless
IChatClient, from Microsoft.Extensions.AI, is .NET's abstraction for AI. Every request carries the whole conversation, and the client itself keeps no state.
Foundation Models is designed the other way around: LanguageModelSession is stateful, the conversation lives in the session, and the session runs the tools itself.
To make it behave like any other IChatClient, I rebuild the session on every request: I convert the conversation sent from .NET into the framework's Transcript (its conversation record), create a new session from it, and generate a reply to the last user message. Every kind of Transcript entry (instructions, prompts, responses, tool calls, tool output) has a public initializer on macOS 26, which is what makes this possible.
Streaming gives you "the full text so far". What streamResponse gives each time is not the new text but the complete content so far. Streaming in IChatClient expects increments, so the bridge has to remember what it has already sent and send only the new part.
Now and then the framework revises text it generated earlier, and the new content no longer extends the old. Text already sent cannot be taken back, so I skip such a snapshot and resume with the next one that lines up.
Structured output (JSON returned according to a schema) works the same way: every snapshot is a complete JSON document that cannot be split into pieces and joined, so for those requests I wait until generation finishes and send it all at once.
Tool calls: stopping the model where it calls. Foundation Models is designed so that you give the session a set of objects that implement the Tool protocol, and when the model decides to call one, the framework runs it directly and continues generating with the result.
The usual pattern for IChatClient is that the client returns FunctionCallContent, the caller (usually the UseFunctionInvocation() middleware) runs it, and the result goes into the next request.
There are two choices here. Microsoft's MAUI approach lets the framework run the tools as usual and reports the calls and results marked InformationalOnly (for information only; the middleware will not run them again), so one request goes through the whole tool loop.
I chose the other: stop the model where it calls, and hand the call back to the caller. Each round of tool calls then costs one more request and one more session rebuild, but the behavior matches every other IChatClient, and the middleware's features (functions that need approval, a maximum number of rounds) all work. My editor has users confirm each edit the model proposes one by one, so having tool calls come back to the app is easier to handle.
The way to do that is to make every tool "record, don't run":
struct RecordingTool : Tool {
typealias Arguments = GeneratedContent
typealias Output = String
let name : String
let description : String
let parameters : GenerationSchema // Decoded from the JSON Schema sent by .NET.
let recorder : CallRecorder
func call(arguments : GeneratedContent) async throws -> String {
recorder.record(name, arguments.jsonString)
throw StopAtToolCall() // Throwing stops this response.
}
}
When a tool throws, the framework ends the response with LanguageModelSession.ToolCallError. The bridge catches it and passes the recorded calls back to .NET as FunctionCallContent.
When the next request comes in carrying the calls and their results, the bridge puts the matching tool calls and tool output into the Transcript and uses an empty string as the prompt, and the model goes on to answer from the results. In my tests, the model did not call the same tool again because of this; even if it did, UseFunctionInvocation() would just run one more round.
A few more details:
- The framework has no public call id, so the bridge generates its own.
- The model may call several tools at once.
callruns them in parallel, but only the first error surfaces, so calls have to be recorded in a recorder shared by all the tools, not read from the error. - "Must call a tool" (
GenerationOptions.toolCallingMode = .required) is an API added in macOS 27, and the framework has no option for "call this particular one". To require a specific function, I send the model only that function and then require a tool call. On macOS 26, asking for either mode throwsNotSupportedExceptioninstead of being silently ignored. - Throwing to stop the response relies on a behavior of Foundation Models: when a tool throws, the response ends. Apple's documentation only says that a tool's error is wrapped in
ToolCallError; it does not promise that the response ends because of it. If Foundation Models someday hands the error to the model and lets it keep generating, the response will complete normally and the recorded calls will be silently dropped. So the bridge also checks the recorder when a response ends normally, and reports any calls it finds there. Current macOS versions never take that path, but if the behavior changes, the calls will not disappear without a trace.
Classifying errors. The framework's error types differ between macOS 26 and 27. According to the declarations in the macOS 27 SDK, LanguageModelError is new in macOS 27, while the older LanguageModelSession.GenerationError has existed since macOS 26 and is marked deprecated in 27.
The bridge handles both with #available and maps them for .NET to a few reasons: context exceeded, blocked by the safety check (guardrail), unsupported language, rate limited, refused by the model, and model unavailable.
This also means the bridge has to be compiled with Xcode 27, while still running on macOS 26. All my testing, though, was on macOS 27.2. I have not verified how it actually behaves on macOS 26.
5️⃣ Schemas: the model reads only part of JSON Schema
Tool parameters and structured output are both described with a schema. The framework's GenerationSchema conforms to Codable, and its JSON form is JSON Schema, so the schema .NET generates with AIJsonUtilities can be sent over and decoded directly. In most cases that works, without converting by hand to the framework's dynamic schema types.
But it accepts only a subset of JSON Schema. What I found on macOS 27.2:
- Case
- Behavior
- Objects, strings, numbers, booleans, arrays, string enums,
const,required, nested objects,$ref - Works
"type": ["string", "null"],oneOf,allOf,anyOfor$defsentries without atitle, enums without atype- Fails to decode
format,minLength/maxLength,default, numeric enums (with atype)- Silently ignored
pattern- Decodes, but fails during generation
And ["string", "null"] is exactly what .NET generates for nullable types, so the schema has to be converted before it is sent: a nullable type becomes its non-null type, anyOf entries and definiti
Comments
No comments yet. Start the discussion.