@tanstack-ai-browser/apfel 0.0.1 → 0.1.0

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.
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Tool-call repair. Apple's model picks the right tool but often gets its
3
+ * arguments wrong: it renames fields (`limit` for `numResults`, `site` for
4
+ * `includeDomains`) and drops optional ones it was asked to set. So after the
5
+ * model calls a tool, its arguments are written again with apfel's guided
6
+ * generation, which holds the model to the tool's JSON Schema:
7
+ *
8
+ * 1. For each optional field, a yes/no answer: does the request give it a
9
+ * value? (Asked for the arguments directly, the model leaves out optional
10
+ * numbers and arrays even when the request states them.)
11
+ * 2. The arguments, with the fields from step 1 required and the rest left
12
+ * out. Fields the model already got right (schema name, right type) are
13
+ * kept as it wrote them.
14
+ *
15
+ * Works from the schema alone, for any tool, MCP tools included. Through
16
+ * `chat()` with search, calendar, file and weather tools, the calls came out
17
+ * right 27 times in 32 with this, against 18 without; the misses left are
18
+ * the model not calling a tool at all, which this can't fix.
19
+ */
20
+ /** Keywords guided generation can enforce; apfel rejects others with 400. */
21
+ const KEPT = ["type", "description", "enum", "const"];
22
+ const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
23
+ /** The schema a local `$ref` (`#/$defs/X`, `#/definitions/X`) points to. */
24
+ function resolveRef(ref, root) {
25
+ if (!ref.startsWith("#/"))
26
+ return undefined;
27
+ let node = root;
28
+ for (const key of ref.slice(2).split("/")) {
29
+ node = isObject(node)
30
+ ? node[key.replace(/~1/g, "/").replace(/~0/g, "~")]
31
+ : undefined;
32
+ }
33
+ return isObject(node) ? node : undefined;
34
+ }
35
+ /**
36
+ * The schema in the subset guided generation enforces: types, properties,
37
+ * required, items, enum, const and descriptions. Local `$ref`s are inlined,
38
+ * `anyOf`/`oneOf`/type unions become their first non-null choice, and
39
+ * constraints it can't enforce (lengths, patterns, formats…) are dropped.
40
+ */
41
+ export function toGuidedSchema(schema, root = isObject(schema) ? schema : {}, depth = 0) {
42
+ if (!isObject(schema) || depth > 12)
43
+ return { type: "string" };
44
+ if (typeof schema.$ref === "string") {
45
+ const target = resolveRef(schema.$ref, root);
46
+ return target
47
+ ? toGuidedSchema({ ...target, ...withoutKey(schema, "$ref") }, root, depth + 1)
48
+ : { type: "string" };
49
+ }
50
+ const choices = (schema.anyOf ?? schema.oneOf);
51
+ if (Array.isArray(choices)) {
52
+ const choice = choices.find((c) => isObject(c) && c.type !== "null") ?? choices[0];
53
+ return toGuidedSchema({
54
+ ...(isObject(choice) ? choice : {}),
55
+ ...(schema.description !== undefined && {
56
+ description: schema.description
57
+ })
58
+ }, root, depth + 1);
59
+ }
60
+ if (Array.isArray(schema.allOf)) {
61
+ const merged = schema.allOf.reduce((all, part) => (isObject(part) ? mergeSchemas(all, part) : all), withoutKey(schema, "allOf"));
62
+ return toGuidedSchema(merged, root, depth + 1);
63
+ }
64
+ const out = {};
65
+ for (const key of KEPT) {
66
+ if (schema[key] !== undefined)
67
+ out[key] = schema[key];
68
+ }
69
+ if (Array.isArray(out.type)) {
70
+ out.type = out.type.find((t) => t !== "null") ?? "string";
71
+ }
72
+ if (out.type === undefined) {
73
+ if (isObject(schema.properties))
74
+ out.type = "object";
75
+ else if (schema.items !== undefined)
76
+ out.type = "array";
77
+ else if (Array.isArray(out.enum))
78
+ out.type = typeof out.enum[0];
79
+ else if (out.const === undefined)
80
+ out.type = "string";
81
+ }
82
+ if (out.type === "object") {
83
+ const properties = isObject(schema.properties) ? schema.properties : {};
84
+ out.properties = Object.fromEntries(Object.entries(properties).map(([key, value]) => [
85
+ key,
86
+ toGuidedSchema(value, root, depth + 1)
87
+ ]));
88
+ out.required = Array.isArray(schema.required)
89
+ ? schema.required.filter((key) => typeof key === "string" && key in properties)
90
+ : [];
91
+ }
92
+ if (out.type === "array") {
93
+ out.items = toGuidedSchema(schema.items ?? {}, root, depth + 1);
94
+ }
95
+ return out;
96
+ }
97
+ function withoutKey(schema, key) {
98
+ const rest = { ...schema };
99
+ delete rest[key];
100
+ return rest;
101
+ }
102
+ function mergeSchemas(a, b) {
103
+ const merged = { ...a, ...b };
104
+ if (isObject(a.properties) || isObject(b.properties)) {
105
+ merged.properties = {
106
+ ...(isObject(a.properties) ? a.properties : {}),
107
+ ...(isObject(b.properties) ? b.properties : {})
108
+ };
109
+ }
110
+ if (Array.isArray(a.required) || Array.isArray(b.required)) {
111
+ merged.required = [
112
+ ...new Set([
113
+ ...(Array.isArray(a.required) ? a.required : []),
114
+ ...(Array.isArray(b.required) ? b.required : [])
115
+ ])
116
+ ];
117
+ }
118
+ return merged;
119
+ }
120
+ /** Whether `value` fits a guided schema's type and choices. */
121
+ function fits(value, schema) {
122
+ if (Array.isArray(schema.enum) && !schema.enum.includes(value))
123
+ return false;
124
+ if (schema.const !== undefined)
125
+ return value === schema.const;
126
+ switch (schema.type) {
127
+ case "string":
128
+ return typeof value === "string";
129
+ case "integer":
130
+ return Number.isInteger(value);
131
+ case "number":
132
+ return typeof value === "number" && Number.isFinite(value);
133
+ case "boolean":
134
+ return typeof value === "boolean";
135
+ case "array":
136
+ return (Array.isArray(value) &&
137
+ value.every((item) => fits(item, (schema.items ?? {}))));
138
+ case "object":
139
+ return isObject(value);
140
+ default:
141
+ return true;
142
+ }
143
+ }
144
+ /**
145
+ * The fields of the model's own arguments that already have a schema's
146
+ * name and a value of the right type. They're kept as they are: with several
147
+ * calls to one tool in a reply, they're what tells the calls apart.
148
+ */
149
+ function validDraftFields(draft, properties) {
150
+ let parsed;
151
+ try {
152
+ parsed = draft ? JSON.parse(draft) : undefined;
153
+ }
154
+ catch {
155
+ return {};
156
+ }
157
+ if (!isObject(parsed))
158
+ return {};
159
+ return Object.fromEntries(Object.entries(parsed).filter(([key, value]) => Object.hasOwn(properties, key) &&
160
+ value !== null &&
161
+ fits(value, properties[key])));
162
+ }
163
+ /** One line per field: name, type or choices, and description. */
164
+ function describeFields(properties) {
165
+ return Object.entries(properties)
166
+ .map(([key, field]) => {
167
+ const kind = Array.isArray(field.enum)
168
+ ? field.enum.map((v) => JSON.stringify(v)).join(" | ")
169
+ : String(field.type ?? "any");
170
+ const about = typeof field.description === "string" ? `: ${field.description}` : "";
171
+ return `- ${key} (${kind})${about}`;
172
+ })
173
+ .join("\n");
174
+ }
175
+ /**
176
+ * The name of the tool the model meant, when it got the name slightly wrong
177
+ * (case, `-` for `_`…). Undefined if no tool matches.
178
+ */
179
+ export function matchToolName(name, toolNames) {
180
+ const names = [...toolNames];
181
+ if (names.includes(name))
182
+ return name;
183
+ const plain = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
184
+ const matches = names.filter((n) => plain(n) === plain(name));
185
+ return matches.length === 1 ? matches[0] : undefined;
186
+ }
187
+ /**
188
+ * The tool call's arguments, written again under the tool's schema.
189
+ * Undefined if the tool takes no arguments or its schema isn't an object
190
+ * (the model's own arguments are used then).
191
+ */
192
+ export async function repairToolArguments(tool, complete,
193
+ /** The model's own arguments, which may use the wrong field names. */
194
+ draft) {
195
+ const schema = toGuidedSchema(tool.inputSchema);
196
+ const properties = (schema.properties ?? {});
197
+ if (schema.type !== "object" || Object.keys(properties).length === 0) {
198
+ return undefined;
199
+ }
200
+ const required = schema.required;
201
+ const optional = Object.keys(properties).filter((key) => !required.includes(key));
202
+ const about = `the tool ${tool.name}${tool.description ? ` (${tool.description})` : ""}`;
203
+ // With several calls in one reply, the draft says which one this is.
204
+ const attempt = draft && draft !== "{}"
205
+ ? `\nThe assistant's first attempt at this call, which may use wrong field names: ${draft.slice(0, 1000)}`
206
+ : "";
207
+ let chosen = [];
208
+ if (optional.length > 0) {
209
+ const answer = await complete({
210
+ name: "fields",
211
+ instructions: `You are deciding the arguments of a call to ${about}, for the user's latest request. Its fields:\n${describeFields(properties)}\nFor each optional field, answer true only if the conversation states a value for it, otherwise false.`,
212
+ schema: {
213
+ type: "object",
214
+ properties: Object.fromEntries(optional.map((key) => [
215
+ key,
216
+ {
217
+ type: "boolean",
218
+ description: `Does the request state a value for ${key}?`
219
+ }
220
+ ])),
221
+ required: optional
222
+ }
223
+ });
224
+ if (isObject(answer))
225
+ chosen = optional.filter((key) => answer[key] === true);
226
+ }
227
+ const kept = validDraftFields(draft, properties);
228
+ const fields = [
229
+ ...new Set([
230
+ ...required,
231
+ ...chosen,
232
+ ...optional.filter((key) => key in kept)
233
+ ])
234
+ ];
235
+ const args = await complete({
236
+ name: tool.name,
237
+ instructions: `Write the arguments for a call to ${about} that does what the user asks in their latest request.${attempt}`,
238
+ schema: {
239
+ type: "object",
240
+ properties: Object.fromEntries(fields.map((key) => [key, properties[key]])),
241
+ required: fields
242
+ }
243
+ });
244
+ if (!isObject(args))
245
+ return undefined;
246
+ // Optional fields left empty weren't really set.
247
+ const written = Object.fromEntries(Object.entries(args).filter(([key, value]) => required.includes(key) ||
248
+ !(value === "" ||
249
+ value === null ||
250
+ (Array.isArray(value) && value.length === 0))));
251
+ return { ...written, ...kept };
252
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack-ai-browser/apfel",
3
- "version": "0.0.1",
3
+ "version": "0.1.0",
4
4
  "description": "TanStack AI adapter for Apple's on-device Foundation Model, served by apfel",
5
5
  "license": "MIT",
6
6
  "author": "daveycodez",
@@ -53,4 +53,4 @@
53
53
  "devDependencies": {
54
54
  "@tanstack/ai": "1.0.0"
55
55
  }
56
- }
56
+ }