An on-device model with only a Swift API and a short context: how I connected it to IChatClient, and the trade-offs
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 an IChatClient for this model, with more features (image support, for example). However, its Apple client only exists for platform-specific target frameworks such as net11.0-ios, net11.0-maccatalyst and net11.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 ordinary net10.0 program (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
FoundationModelsweak-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, anyOf or $defs entries without a title, enums without a type | Fails to decode |
format, minLength/maxLength, default, numeric enums (with a type) | 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 definitions get a title, a string enum without a type gets "type": "string", and pattern is removed. What truly cannot be expressed (oneOf, allOf, enums with no type whose values are not all strings) throws NotSupportedException rather than guessing what it means.
There is another problem that is easy to miss: properties get sorted alphabetically. In structured output, the model generates properties one by one in order, so the order matters (for example, the reasoning first, then the conclusion). To keep the original order, add x-order to the schema.
Optional properties keep the model from stopping
This was the most serious problem in the whole integration.
I had the model propose edits through a tool whose parameter is an array, each element with two properties, the original text and the rewrite. In the C# class, those two were settable properties, so the schema AIJsonUtilities generated treated them as optional. Once the model started generating that array, it could not stop: the system's model service pinned the CPU, its memory went past 30 GB, and setting MaxOutputTokens did nothing. After such a request ran once or twice, macOS began refusing every app's model requests with CriticalMemoryPressure until the model service restarted.
After I made both properties required, the same request finished in 5 to 8 seconds.
In the end I changed the conversion rule: every property of every object is listed as required. The side effect is that the model gives a value for every property, so parameter defaults are never used and nullable values are never null; where a value needs to be "allowed to be left out", accept an empty string or an empty list instead. The one exception is a property that points to a type through $ref in the schema (including lists whose elements are such a type), which keeps its original setting. Otherwise, for a self-referencing type such as the "next node" of a linked list, making every level required would mean the response could never end.
Whatever integration you use, if your tool or response types contain "an array of objects with optional properties", it is worth testing first.
6️⃣ Using it in a Markdown editor
I connected it to the Markdown editor I am building, Polhem MD. Since the interface is IChatClient, the chat panel and the inline commands (select text, then ask AI to rewrite it) share the same code as every other model, and the Apple model is just one template in Settings. Everything that sets it apart from other models is handled by a DelegatingChatClient wrapped around it:
var apple = new AppleIntelligenceChatClient(); IChatClient client = apple.AsBuilder() .UseFunctionInvocation() .Use(inner => new AppleModelChatClient(inner, apple.GetAvailability)) .Build(); AppleModelChatClient is the app's own class, and it takes care of the following.
It appears only on machines that can use it. The template is offered only on a Mac where the model "works now, or will work once the user turns on Apple Intelligence and the model finishes downloading"; on Windows, Linux, Intel Macs or Macs that are not eligible, the option does not appear. When the framework reports the model as unavailable, it gives a reason: the machine is not eligible, Apple Intelligence is turned off, or the model is still downloading. The user cannot change the first, while the other two only need a short wait or a trip to Settings, and they call for entirely different handling. So the settings page does not just say "unavailable"; it gives the reason and what to do, for example "Apple Intelligence is turned off. Turn it on in System Settings, under Apple Intelligence & Siri."
It turns errors into messages users understand and can act on. When the context is exceeded, for example, it suggests selecting just one passage or starting a new conversation. The framework checks whether a request exceeds the context before generating, so the app does not need to estimate token counts itself.
It removes the web-reading tool. Other models can read web pages, but one page plus the conversation easily goes over 8K tokens, so requests to this model drop that tool, and the instructions tell the model it cannot read web pages.
Instructions must match the tools actually given
When this model could not yet use tools, I appended "you currently have no tools available" to the app's existing instructions (which tell the model to propose edits with a tool). The model followed the earlier instructions and answered "I have proposed the edits", having done nothing. A small model is easily led astray by contradictory instructions. I changed it so that when there are no tools, the part of the instructions about tools is replaced entirely, rather than having a sentence tacked on at the end.
Test results
With a test document, the edit-proposing tool and the app's instructions, I tried several requests on macOS 27.2:
| Request | Result |
|---|---|
| Fix spelling and grammar (prompt in English) | Every error was fixed through the tool |
| Fix spelling and grammar (prompt in Chinese) | Proposed edits, but in two of three runs missed a spelling error at the start of a sentence |
| Shorten a paragraph | The edit was correct, but the reply said it had "already applied" it, when it had only proposed it |
| Translate a paragraph | Wrote the translation directly in the reply without calling the tool |
| One-sentence summary | Answered directly without the tool, in Traditional Chinese as instructed |
It can handle small edits, but what it says it has done is not always reliable. So the app has users confirm each proposed edit one by one, and does not trust the model's "done".
7️⃣ Limits and where it fits
How much fits in an 8K context
The 8,192 tokens are shared by input and output: the instructions, the tool definitions, the document and the model's reply must all fit within it together. In one test, with about 7,000 tokens of input and a request to rewrite it sentence by sentence, the model got a little over 1,100 tokens in before stopping because it exceeded the context.
To find out how much actually fits, I used the instructions and tools Polhem MD sends to this model on macOS 27.2, cut various kinds of content to different lengths, and found the longest length that still started generating. With the app's instructions at about 490 tokens and the edit-proposing tool definition at about 270 tokens, roughly 7,440 tokens are left for the document and the prompt:
| Content | Per token, about | Most that fits |
|---|---|---|
| Traditional Chinese plain text | 1.4 characters | About 10,000 characters |
| Traditional Chinese technical article (with English terms and code) | 1.8 characters | About 13,000 characters |
| English article | 4.2 characters | About 31,000 characters, about 5,100 English words |
| C# code | 4.1 characters | About 720 lines |
| JSON data | 1.9 characters | About 130 small objects with four fields |
This is the upper limit of what "fits"; at the limit, the model has no room left to answer. The reply also comes out of the same 8,192: a summary needs a few hundred to a thousand tokens, and a rewrite needs about as much as the original, so text you ask the model to rewrite can in practice be only about half of what the table shows. The characters per token were measured with the framework's tokenCount(for:) (available from macOS 26.4), vary with the content, and should be taken only as a rough order of magnitude.
Take the original Chinese version of this post as an example: the whole article is about 6,400 tokens, which fits, but that leaves only about 1,000 tokens for the reply. A summary is still possible; rewriting the whole article is not. A section, a selected passage or an email is the size it is comfortable with. Conversations accumulate the same way: after a few rounds, the earlier content takes up most of the space.
Good fits:
- Summarizing a passage, or asking about the selected content
- Small edits: fixing typos, polishing a paragraph
- Extracting a few fields from short text, or classifying it (with structured output)
- Situations that must work offline, or where data cannot leave the computer
Poor fits:
- Long documents: a whole document often does not fit in the context, so send a selection or summarize first
- Work that needs to read web pages or a lot of outside data
- Agent-style tasks with many tools and multi-step reasoning. When you do use tools, keep them few, with clear names and descriptions; it sometimes answers in text when it should have called a tool
- Major rewrites or long translations
Platform limits:
- Only Macs with Apple Silicon, macOS 26 or later and Apple Intelligence turned on; Windows, Linux and Intel Macs need another model. In my editor, those users switch to a local model such as Ollama or LM Studio, which likewise needs no key and keeps data on the computer. Since all of them are
IChatClient, switching just means creating a different client. - An unsupported language returns an error right away, and that error needs to be explained clearly to the user too.
- The model version follows macOS updates, so the same request may behave differently on different system versions.
Development and testing
- Unit tests do not call the real model. On the .NET side I put the native calls behind an interface, and the tests use a fake that replays a script, checking conversation conversion, streaming, tool calls, error classification and cancellation. The real model is tested only for "does it load, and what does it report when unavailable".
- CI needs a Mac. The build compiles Swift with Xcode, so CI has to run on a macOS runner; and runners usually do not have Apple Intelligence turned on, so how the model actually performs can only be checked by hand on your own machine.
- What the model can really do has to be tried with real requests. The test results table above and the "optional properties keep it from stopping" problem are both things unit tests cannot catch.
✅ Wrapping up
Bringing Apple's on-device model into .NET is technically hard because it has only a Swift API, and its session is stateful, unlike the stateless convention of IChatClient. The limits in actual use come from its being a small model with a short context.
For a desktop app, its greatest value is that users get basic AI features without applying for an API key or installing anything else, and their data stays on the computer. But it works only on some Macs and its abilities are limited, so it is better as one of an app's AI options than as the only source. If your app already targets MAUI or an Apple platform target framework, Microsoft's package will be easier than writing a bridge yourself; if it is an ordinary net10.0 program, writing a bridge of your own is not that complicated.
The bridge and the editor in this post are both open source. The code is here:
- polhem-ai-apple: the Swift bridge and the
IChatClientimplementation (NuGet package Polhem.AI.Apple) - polhem-md: Polhem MD, the Markdown editor that uses this model
Further reading
- Foundation Models: Apple's official framework documentation
- Microsoft.Extensions.AI: .NET's AI abstraction, where
IChatClientcomes from - Apple Intelligence IChatClient (.NET MAUI): Microsoft's integration for MAUI
- Native interoperability: the official guide to calling native code from .NET, including
LibraryImportand function pointers
📘 Original article on HackMD, in Traditional Chinese:
👉 https://hackmd.io/@jeff377/dotnet-apple-ai
📢 You are welcome to republish this, please credit the source.
📬 Follow for more engineering notes:
Facebook | HackMD | GitHub | NuGet

