@tanstack-ai-browser/apfel 0.0.0-stage → 0.0.1

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.
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * TanStack AI adapter for Apple's on-device Foundation Model, served by apfel.
3
+ */
4
+ export {
5
+ APFEL_BASE_URL,
6
+ APFEL_MODEL,
7
+ ApfelTextAdapter,
8
+ apfel,
9
+ isApfelAvailable
10
+ } from "./adapter.js"
11
+ export type { ApfelModelOptions, ApfelOptions, ApfelStats } from "./adapter.js"
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Tool calls Apple's model writes as text. apfel turns the model's tool
3
+ * calls into OpenAI `tool_calls`, but when it doesn't recognize one it
4
+ * passes it on as text instead, like
5
+ * `{"tool_calls": [{"function": "get_weather", "arguments": {…}}]}`.
6
+ */
7
+
8
+ export type ParsedToolCall = { name: string; args: Record<string, unknown> }
9
+
10
+ /** Where Apple's model starts a tool call it writes as text. */
11
+ export const JSON_TOOL_CALLS_MARKER = '{"tool_calls"'
12
+
13
+ /** The `{…}` that starts at `text[start]`, braces in strings ignored. */
14
+ function balancedObject(text: string, start: number) {
15
+ let depth = 0
16
+ let inString = false
17
+ for (let i = start; i < text.length; i++) {
18
+ const c = text[i]
19
+ if (inString) {
20
+ if (c === "\\") i++
21
+ else if (c === '"') inString = false
22
+ } else if (c === '"') inString = true
23
+ else if (c === "{") depth++
24
+ else if (c === "}" && --depth === 0) return text.slice(start, i + 1)
25
+ }
26
+ return null
27
+ }
28
+
29
+ /** JSON arguments, read leniently: stray strings without a key are dropped. */
30
+ function parseJsonArgs(raw: string): Record<string, unknown> | null {
31
+ for (const candidate of [raw, raw.replace(/,\s*"[^"]*"\s*(?=[,}])/g, "")]) {
32
+ try {
33
+ const value = JSON.parse(candidate) as unknown
34
+ const args = typeof value === "string" ? JSON.parse(value) : value
35
+ if (args && typeof args === "object") {
36
+ return args as Record<string, unknown>
37
+ }
38
+ } catch {
39
+ // Try the next reading.
40
+ }
41
+ }
42
+ return null
43
+ }
44
+
45
+ /**
46
+ * Tool calls Apple's model wrote as JSON text. Its JSON varies and is often
47
+ * broken (`"function": "name"`, `"name: "name"`, stray strings in the
48
+ * arguments), so instead of parsing the whole thing, this finds each quoted
49
+ * name of a tool that exists and reads the `"arguments"` object after it.
50
+ */
51
+ export function parseJsonToolCalls(
52
+ text: string,
53
+ toolNames: Iterable<string>
54
+ ): Array<ParsedToolCall> {
55
+ const mentions: Array<{ name: string; at: number }> = []
56
+ for (const name of toolNames) {
57
+ const quoted = `"${name}"`
58
+ for (
59
+ let at = text.indexOf(quoted);
60
+ at >= 0;
61
+ at = text.indexOf(quoted, at + 1)
62
+ ) {
63
+ mentions.push({ name, at })
64
+ }
65
+ }
66
+ mentions.sort((a, b) => a.at - b.at)
67
+ const calls: Array<ParsedToolCall> = []
68
+ mentions.forEach(({ name, at }, i) => {
69
+ // The arguments belong to the last mention of a name before them. The
70
+ // model sometimes writes a broken "arguments" and then a good one: the
71
+ // first that reads is used.
72
+ const part = text.slice(at, mentions[i + 1]?.at ?? text.length)
73
+ for (const key of part.matchAll(/"arguments"?\s*:\s*/g)) {
74
+ const from = key.index + key[0].length
75
+ const raw =
76
+ part[from] === "{"
77
+ ? balancedObject(part, from)
78
+ : /^"(?:[^"\\]|\\.)*"/.exec(part.slice(from))?.[0]
79
+ const args = raw ? parseJsonArgs(raw) : null
80
+ if (args) {
81
+ calls.push({ name, args })
82
+ return
83
+ }
84
+ }
85
+ })
86
+ return calls
87
+ }
88
+
89
+ /** Length of the longest end of `text` that could start `marker`. */
90
+ function partialMarker(text: string, marker: string) {
91
+ for (let n = Math.min(text.length, marker.length); n > 0; n--) {
92
+ if (marker.startsWith(text.slice(-n))) return n
93
+ }
94
+ return 0
95
+ }
96
+
97
+ /**
98
+ * Splits a streaming answer into the text before the first tool call written
99
+ * as text (passed through as it arrives) and the tool-call JSON after it
100
+ * (held back and parsed once the reply ends).
101
+ */
102
+ export function createToolCallSplitter(marker = JSON_TOOL_CALLS_MARKER) {
103
+ let held = ""
104
+ let markup: string | null = null
105
+
106
+ /** Text that can be shown now. */
107
+ function push(text: string) {
108
+ if (markup !== null) {
109
+ markup += text
110
+ return ""
111
+ }
112
+ held += text
113
+ const at = held.indexOf(marker)
114
+ if (at >= 0) {
115
+ const before = held.slice(0, at)
116
+ markup = held.slice(at)
117
+ held = ""
118
+ return before
119
+ }
120
+ const keep = partialMarker(held, marker)
121
+ const out = held.slice(0, held.length - keep)
122
+ held = held.slice(out.length)
123
+ return out
124
+ }
125
+
126
+ /** The rest of the text, and the tool-call JSON if any. */
127
+ function flush() {
128
+ const rest = held
129
+ held = ""
130
+ return { text: rest, markup }
131
+ }
132
+
133
+ return { push, flush }
134
+ }