refactor(apple): run tools through the ai sdk instead of natively

Aperta
#267 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
25/100
Tipo di issue
Funzionalità
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
react-native, typescript

Direzione di ricerca

Start with ai-sdk.ts, AppleLLM.mm, and the JSITool and ToolInvoker plumbing to trace the current tool flow. Prototype the iOS 27 path first, then add bun test coverage and run a live check through the native module. Try the example app with stopWhen: stepCountIs(n), approvals, and streaming; completion also requires deciding how to handle built-in tools and verifying the iOS 26 path.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Summary

Today Apple runs JavaScript tools natively, inside one Foundation Models session. Apple could instead stop at the tool call and hand it to the AI SDK, which would run execute. That would make the Apple provider behave like other AI SDK providers: stopWhen, prepareStep, onStepFinish, tool approvals and client-side tools would all work.

This is for later. For now, #265 (toolChoice: 'required' and a named tool through a Dynamic Profile) and #266 (maxToolCalls) improve the native path.

How it works today

  1. The AI SDK passes the provider tool schemas only, so users register execute a second time with createAppleProvider({ availableTools }) or model.updateTools(...).
  2. prepareTools in ai-sdk.ts wraps each tool, gives it an id, and stores it in globalThis.__APPLE_LLM_TOOLS__.
  3. Native builds a JSITool per tool. When Apple calls one, JSITool.call goes through the tool invoker to callToolWithId in AppleLLM.mm, which hops to the JS thread, looks the tool up in the global and awaits it.
  4. Tool calls and results come back as providerExecuted: true. The AI SDK only loops on tool calls it ran itself (clientToolCalls = stepToolCalls.filter((toolCall) => !toolCall.providerExecuted) in ai's generateText), so the whole Apple loop is one step: stopWhen and prepareStep never apply, and onStepFinish fires once.

Proposed design

Each AI SDK step becomes one Apple request that stops at its first round of tool calls.

JS

  • Send tools as name, description and schema only. Remove availableTools, updateTools, prepareTools and the global registry.
  • doGenerate: return tool calls as plain tool-call parts (no providerExecuted), with finishReason: 'tool-calls'.
  • doStream: emit the tool calls and a 'tool-calls' finish when native stops.
  • toolChoice is applied per step by the AI SDK, so 'required' maps to Apple's .required for that one request. No Dynamic Profile mode switching is needed, because the request stops at the first call.

Native

  • iOS 27: create the session from a Dynamic Profile with:

    • the tools and .toolCallingMode(...),
    • .transcriptErrorHandlingPolicy(.preserveTranscript),
    • .historyTransform to hide the continuation prompt,
    • .onToolCall that throws a stop error for JS tools.

    On that error, read the calls (with Apple's ids) from the kept transcript.

  • iOS 26: no profiles. The tool's call(arguments:) records the arguments and throws. Ids are generated by us.

  • Let the history end with tool results: createTranscriptAndPrompt currently requires the last message to be from the user. Continue with an empty prompt.

  • Delete the ToolInvoker plumbing, JSITool's invoker and callToolWithId.

What was verified (on-device model, macOS 27, scratch tests)

Check Result
Stop at the tool calls with parallel calls ("weather and local time in Paris and London") onToolCall saw all 4 calls, with ids and arguments, before the error. 0 tools ran. preserveTranscript kept one tool-call entry with all 4.
The same while streaming All 4 captured, 0 ran. Stream snapshots don't include the calls, so capture comes from onToolCall or the kept transcript.
Today's native generateText with AI SDK step-2 messages (user, assistant tool call, tool result) Rejected: INVALID_MESSAGE: Last message must be from user role.
Resume from that history with an empty prompt and historyTransform hiding it "The weather in Paris is sunny with a temperature of 22°C.", with no new tool calls.
required for a single step "Tell me a short joke." was forced into one getWeather call, and stopped there.
iOS 26-style stop: throw from the tool itself All 4 parallel calls reached the tool before the error. No call ids. Only run on the macOS 27 runtime.

Caveats

  • Breaking change.
    • availableTools and updateTools go away.
    • Without stopWhen, generateText returns the tool call with no text answer, as with other providers. Today Apple runs the tool and answers in one call.
  • Built-in Vision tools (OCR, barcode) must still run on Apple's side. onToolCall fires for them too, so the stop must only trigger for JS tool names. A round mixing both kinds needs handling.
  • Each step is a new Apple request that reprocesses the transcript. That may be slower than Apple's internal loop. iOS 27 reports cached input tokens, but reuse across requests hasn't been measured.
  • The continuation prompt. Every respond overload needs a prompt, so steps after a tool result send an empty one. On iOS 27 historyTransform hides it from the model. On iOS 26 it stays in the transcript; it worked in a test without the transform.
  • iOS 26 differences. There are no tool call ids at stop time, no preserved transcript, and no required mode.
  • Not yet verified:
    • the iOS 26 path on an iOS 26 device;
    • the full AI SDK loop through the React Native bridge (needs a prototype and an example-app run);
    • mixed rounds of built-in and JS tools.

Suggested next step

Build a prototype on a branch: the iOS 27 path first, with bun test coverage and a live check through the native module. Then run it in the example app with stopWhen: stepCountIs(n), approvals and streaming before deciding. It could ship as part of the iOS 27-only rewrite.

Lingua principale
TypeScript
Stelle
1.4k
Fork
64
Merge medio
11h 8m
PR unite (30g)
2

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di callstackincubator/ai

Tutte le issue di callstackincubator/ai

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.