Skip to content

feat: graceful apple context window error handling, countTokens API - #212

Merged
artus9033 merged 12 commits into
callstackincubator:mainfrom
JKobrynski:feat/apple-context-window-handling
Jun 1, 2026
Merged

artus9033 merged 12 commits into
callstackincubator:mainfrom
JKobrynski:feat/apple-context-window-handling

Conversation

@JKobrynski

@JKobrynski JKobrynski commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Related issue - fixes #125

Summary

Adds explicit handling for Apple Foundation Models context window overflow errors.

When LanguageModelSession fails with exceededContextWindowSize, the Apple provider now exposes a stable CONTEXT_WINDOW_EXCEEDED error code. This allows apps to detect the failure and decide how to recover, for example by starting a new conversation or trimming previous messages.

Changes

  • Map Apple’s native context window overflow error to CONTEXT_WINDOW_EXCEEDED
  • Forward the error code through streaming errors
  • Expose AppleLLMErrorCodes.ContextWindowExceeded
  • Update the Expo example so text streams surface the error properly
  • Document recommended app-level recovery strategies

@vercel

vercel Bot commented May 22, 2026

Copy link
Copy Markdown

@JKobrynski is attempting to deploy a commit to the Callstack Team on Vercel.

A member of the Team first needs to authorize it.

@JKobrynski
JKobrynski marked this pull request as ready for review May 22, 2026 13:44
@artus9033
artus9033 self-requested a review May 24, 2026 22:57
@artus9033 artus9033 added the enhancement New feature or request label May 24, 2026
@artus9033
artus9033 requested a review from Copilot May 24, 2026 22:58

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds explicit handling for Apple Foundation Models context-window overflow by introducing a stable CONTEXT_WINDOW_EXCEEDED error code and propagating it through streaming APIs, alongside documentation and example updates.

Changes:

  • Introduces AppleLLMErrorCodes.ContextWindowExceeded and a JS error wrapper that carries an optional code.
  • Forwards native error code through stream error events and converts stream errors into Error instances with code.
  • Updates iOS native layer to detect exceededContextWindowSize, emit the stable error code, and documents recovery strategies (plus updates the Expo example to surface stream errors).

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
website/src/docs/apple/generating.md Documents context window behavior, stable error code, and recommended recovery patterns (including streaming guidance).
packages/apple-llm/src/stream.ts Wraps stream error events using createAppleLLMError(..., code) to preserve an error code.
packages/apple-llm/src/NativeAppleLLM.ts Extends stream error event shape with optional code.
packages/apple-llm/src/index.ts Exports new Apple error types and constants.
packages/apple-llm/src/errors.ts Adds AppleLLMErrorCodes and createAppleLLMError helper for code-carrying errors.
packages/apple-llm/src/ai-sdk.ts Forwards stream error code into Error objects for AI SDK streaming consumers.
packages/apple-llm/ios/AppleLLMImpl.swift Adds native mapping for context-window overflow errors and forwards code through streaming callbacks.
packages/apple-llm/ios/AppleLLMError.swift Adds contextWindowExceeded case and stable CONTEXT_WINDOW_EXCEEDED code mapping.
packages/apple-llm/ios/AppleLLM.mm Emits stream error payloads with optional code field.
apps/expo-example/src/screens/ChatScreen/index.tsx Captures streamText errors via onError so text streaming surfaces failures properly.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@artus9033 artus9033 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM from my end after:

  1. let's double-check if the above Copilot comment is a false-positive
  2. this PR is missing a convenience feature - exposing a JS API that would allow users to count the number of tokens a string takes, before running inference on the model (+ docs update for that); let's address this here, or in a follow-up PR

@artus9033 artus9033 changed the title feat: apple context window handling feat: graceful apple context window error handling May 25, 2026
@JKobrynski
JKobrynski requested a review from artus9033 May 26, 2026 12:54
@JKobrynski

Copy link
Copy Markdown
Contributor Author

@artus9033 updated, feel free to take another look!

@artus9033 artus9033 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@artus9033

Copy link
Copy Markdown
Contributor

Great job, thanks for building this 🚀

@artus9033 artus9033 changed the title feat: graceful apple context window error handling feat: graceful apple context window error handling, countTokens API Jun 1, 2026
@artus9033
artus9033 merged commit 9e14139 into callstackincubator:main Jun 1, 2026
3 of 4 checks passed
grabbou added a commit that referenced this pull request Oct 24, 2026
* refactor(apple): export the native module as AppleFoundationModels

AppleFoundationModels.ts was added in #212 to reject countTokens on native
builds without it. #248 removed that guard, so the wrapper only re-declared
the native methods. Export the TurboModule directly, like the other native
modules in the package and as 0.12.0 did.

Also remove src/stream.ts, an unused stream helper still typed with
LanguageModelV2StreamPart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(apple): report token usage from foundation models

Responses and streams reported 0 input and 0 output tokens, so AI SDK
usage, prepareStep thresholds and telemetry always saw zero.

- iOS 27 passes through the usage Foundation Models measures (input,
  cached input, output and reasoning tokens), for the on-device model and
  Private Cloud Compute
- iOS 26.4 counts the transcript before and after the response with the
  on-device model's tokenizer
- otherwise usage is undefined instead of 0

Native generateText now resolves { content, usage } and onStreamComplete
carries usage, which changes the shape returned by
AppleFoundationModels.generateText.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(core-ai, llama): report unknown token usage as undefined

core-ai always reported 0 tokens and llama fell back to 0 when llama.rn
returned no timings. AI SDK treats 0 as a measured count, so totals looked
real. Report undefined instead, as adk does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(apple, llama): count tokens through language models

@react-native-ai/utils summarizes history by calling countTokens on the
model it is given, but no provider defined it, so it always fell back to
four characters per token.

Apple language models count with the on-device model's tokenizer
(iOS 26.4+) and llama.rn models with their own tokenizer.
AppleFoundationModels.countTokens stays available.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(apple): stream tool calls on ios 26 and structured output

On iOS 26, stream snapshots have no transcript entries, so streamText never
reported Apple tool calls. Read them from the session transcript instead,
which already holds the tool call and output entries when the first text
chunk arrives.

streamText with Output.object threw "Streaming JSON responses is not yet
supported." Native streams now send the snapshot's JSON. Partial snapshots
are not prefixes of the final JSON (even key order changes), so the provider
sends the complete object once the stream finishes.

Schema streams also report reasoning and tool entries on iOS 27.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: align provider factories with ProviderV4 naming

AI SDK 7 names provider factories embeddingModel and rerankingModel and
gives providers a specificationVersion.

- every provider factory sets specificationVersion: 'v4'
- apple and llama add embeddingModel, and llama adds rerankingModel; the
  published textEmbeddingModel and rerankModel stay as deprecated aliases
- core-ai drops textEmbeddingModel, which was never published
- mlc adds createMlcProvider, so mlc is a callable provider like the others;
  mlc.languageModel() keeps working

Docs, README and skills use the new names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(utils): call countTokens on its model

countPromptTokens took countTokens off the model and called it without a
receiver. The llama.rn model reads this.context in countTokens, so it threw
and the summarizer silently fell back to four characters per token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(apple): say private cloud compute has no token counting api

countTokens on a Private Cloud Compute model counts with the on-device
model's tokenizer, which may not match the server model, and needs the
on-device model to be available. Calling it an approximation claimed more
than is known.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

My app crashes after exceeding the 4096 token context window of Apple Foundation Model

3 participants