@tanstack-ai-browser/apfel 0.0.1 → 0.2.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.
- package/README.md +36 -5
- package/dist/adapter.d.ts +33 -79
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js +45 -574
- package/dist/guided-schema.d.ts +20 -0
- package/dist/guided-schema.d.ts.map +1 -0
- package/dist/guided-schema.js +136 -0
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/model-meta.d.ts +23 -0
- package/dist/model-meta.d.ts.map +1 -0
- package/dist/model-meta.js +20 -0
- package/dist/tool-repair.d.ts +56 -0
- package/dist/tool-repair.d.ts.map +1 -0
- package/dist/tool-repair.js +252 -0
- package/dist/tools.d.ts +68 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +469 -0
- package/package.json +11 -4
- package/src/adapter.test.ts +81 -0
- package/src/adapter.ts +80 -745
- package/src/availability.test.ts +61 -0
- package/src/index.ts +5 -8
- package/src/model-meta.ts +37 -0
- package/src/tool-calls.ts +0 -134
package/dist/adapter.js
CHANGED
|
@@ -1,584 +1,55 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* A TanStack AI text adapter for Apple's on-device Foundation Model, served
|
|
3
|
-
* by apfel's
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* and
|
|
7
|
-
*
|
|
3
|
+
* by apfel. apfel speaks OpenAI's Chat Completions API, so this is TanStack's
|
|
4
|
+
* OpenAI-compatible adapter pointed at it: tool calls and structured output
|
|
5
|
+
* go to apfel as `tools` and `response_format`, image parts as `image_url`
|
|
6
|
+
* parts, and `modelOptions` as given. It adds `availability()` and
|
|
7
|
+
* `create()`, which ask apfel whether it serves the model.
|
|
8
8
|
*/
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
return content;
|
|
29
|
-
return (content ?? [])
|
|
30
|
-
.map((part) => (part.type === "text" ? part.content : ""))
|
|
31
|
-
.join("");
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* The conversation in OpenAI's chat format. Tool calls and results from
|
|
35
|
-
* earlier turns are left out; their answers stay. With them in the history,
|
|
36
|
-
* Apple's model writes its next tool call as broken JSON text most of the
|
|
37
|
-
* time (4 of 12 calls worked, against 12 of 12 without). The current turn's
|
|
38
|
-
* calls and results are kept: the model answers from them.
|
|
39
|
-
*/
|
|
40
|
-
function toOpenAIMessages(messages) {
|
|
41
|
-
const out = [];
|
|
42
|
-
const currentTurn = messages.map((m) => m.role).lastIndexOf("user");
|
|
43
|
-
for (const [i, m] of messages.entries()) {
|
|
44
|
-
const earlierToolStep = i < currentTurn &&
|
|
45
|
-
(m.role === "tool" || (m.role === "assistant" && m.toolCalls?.length));
|
|
46
|
-
const content = contentText(m.content);
|
|
47
|
-
if (earlierToolStep) {
|
|
48
|
-
if (m.role === "assistant" && content) {
|
|
49
|
-
out.push({ role: "assistant", content });
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
else if (m.role === "tool") {
|
|
53
|
-
out.push({
|
|
54
|
-
role: "tool",
|
|
55
|
-
tool_call_id: m.toolCallId ?? "",
|
|
56
|
-
content: toolResultText(m)
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
else if (m.role === "assistant" && m.toolCalls?.length) {
|
|
60
|
-
out.push({
|
|
61
|
-
role: "assistant",
|
|
62
|
-
content: content || null,
|
|
63
|
-
tool_calls: m.toolCalls.map((call) => ({
|
|
64
|
-
id: call.id,
|
|
65
|
-
type: "function",
|
|
66
|
-
function: call.function
|
|
67
|
-
}))
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
else if (content) {
|
|
71
|
-
out.push({ role: m.role === "user" ? "user" : "assistant", content });
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
return out;
|
|
75
|
-
}
|
|
76
|
-
/** Tools as OpenAI function tools; `inputSchema` is already JSON Schema. */
|
|
77
|
-
function toOpenAITools(tools) {
|
|
78
|
-
return (tools ?? []).map((tool) => ({
|
|
79
|
-
type: "function",
|
|
80
|
-
function: {
|
|
81
|
-
name: tool.name,
|
|
82
|
-
description: tool.description,
|
|
83
|
-
parameters: tool.inputSchema ?? {
|
|
84
|
-
type: "object",
|
|
85
|
-
properties: {},
|
|
86
|
-
required: []
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}));
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* `tool_choice` for the request. "auto" is apfel's default and is left out,
|
|
93
|
-
* so a plain request is sent exactly as before.
|
|
94
|
-
*/
|
|
95
|
-
function toolChoice(choice) {
|
|
96
|
-
if (!choice || choice === "auto")
|
|
97
|
-
return {};
|
|
98
|
-
if (typeof choice === "string")
|
|
99
|
-
return { tool_choice: choice };
|
|
100
|
-
return {
|
|
101
|
-
tool_choice: { type: "function", function: { name: choice.name } }
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
/** The system prompts as one system message, if there are any. */
|
|
105
|
-
function systemMessages(prompts) {
|
|
106
|
-
const system = normalizeSystemPrompts(prompts)
|
|
107
|
-
.map((p) => p.content)
|
|
108
|
-
.join("\n\n");
|
|
109
|
-
return system ? [{ role: "system", content: system }] : [];
|
|
110
|
-
}
|
|
111
|
-
/** Yields the `data:` payloads of an SSE response body. */
|
|
112
|
-
async function* sseData(body) {
|
|
113
|
-
const reader = body.getReader();
|
|
114
|
-
const decoder = new TextDecoder();
|
|
115
|
-
let buffer = "";
|
|
116
|
-
try {
|
|
117
|
-
for (;;) {
|
|
118
|
-
const { value, done } = await reader.read();
|
|
119
|
-
if (done)
|
|
120
|
-
break;
|
|
121
|
-
buffer += decoder.decode(value, { stream: true });
|
|
122
|
-
let newline;
|
|
123
|
-
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
124
|
-
const line = buffer.slice(0, newline).trim();
|
|
125
|
-
buffer = buffer.slice(newline + 1);
|
|
126
|
-
if (line.startsWith("data:"))
|
|
127
|
-
yield line.slice(5).trim();
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
finally {
|
|
132
|
-
reader.releaseLock();
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
/** A tool call's JSON arguments, or undefined if they aren't a JSON object. */
|
|
136
|
-
function parseArguments(json) {
|
|
137
|
-
try {
|
|
138
|
-
const args = JSON.parse(json);
|
|
139
|
-
return args && typeof args === "object" && !Array.isArray(args)
|
|
140
|
-
? args
|
|
141
|
-
: undefined;
|
|
142
|
-
}
|
|
143
|
-
catch {
|
|
144
|
-
return undefined;
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
/** The message of apfel's `{"error": {"message"}}` body, or the raw body. */
|
|
148
|
-
async function errorBody(response) {
|
|
149
|
-
const raw = await response.text().catch(() => "");
|
|
150
|
-
try {
|
|
151
|
-
const message = JSON.parse(raw).error?.message;
|
|
152
|
-
if (message)
|
|
153
|
-
return message;
|
|
154
|
-
}
|
|
155
|
-
catch {
|
|
156
|
-
// Not JSON: the raw body says what it says.
|
|
157
|
-
}
|
|
158
|
-
return raw.slice(0, 200);
|
|
159
|
-
}
|
|
160
|
-
function usageOf(usage) {
|
|
161
|
-
if (usage?.prompt_tokens === undefined ||
|
|
162
|
-
usage.completion_tokens === undefined) {
|
|
163
|
-
return undefined;
|
|
164
|
-
}
|
|
165
|
-
const cachedTokens = usage.prompt_tokens_details?.cached_tokens;
|
|
166
|
-
return {
|
|
167
|
-
promptTokens: usage.prompt_tokens,
|
|
168
|
-
completionTokens: usage.completion_tokens,
|
|
169
|
-
totalTokens: usage.prompt_tokens + usage.completion_tokens,
|
|
170
|
-
...(cachedTokens && { promptTokensDetails: { cachedTokens } })
|
|
171
|
-
};
|
|
172
|
-
}
|
|
173
|
-
const errorText = (error) => error instanceof Error ? error.message : String(error);
|
|
174
|
-
const unreachable = (baseUrl) => `Couldn't reach Apple's on-device model at ${baseUrl}. Start it with \`apfel --serve --cors\`.`;
|
|
175
|
-
let ids = 0;
|
|
176
|
-
const nextId = (prefix) => `${prefix}_${Date.now().toString(36)}_${(ids++).toString(36)}`;
|
|
177
|
-
export class ApfelTextAdapter extends BaseTextAdapter {
|
|
178
|
-
name = "apfel";
|
|
179
|
-
api = "apfel";
|
|
180
|
-
baseUrl;
|
|
181
|
-
onStats;
|
|
182
|
-
constructor(options = {}) {
|
|
183
|
-
super({}, options.model ?? APFEL_MODEL);
|
|
184
|
-
this.baseUrl = (options.baseUrl ?? APFEL_BASE_URL).replace(/\/+$/, "");
|
|
185
|
-
this.onStats = options.onStats;
|
|
186
|
-
}
|
|
187
|
-
async *chatStream(options) {
|
|
188
|
-
const runId = options.runId ?? nextId("run");
|
|
189
|
-
const threadId = options.threadId;
|
|
190
|
-
const callId = nextId("call");
|
|
191
|
-
const messageId = nextId("msg");
|
|
192
|
-
const reasoningId = nextId("reasoning");
|
|
193
|
-
const model = this.model;
|
|
194
|
-
const { logger } = options;
|
|
195
|
-
const signal = options.abortController?.signal ??
|
|
196
|
-
options.request?.signal ??
|
|
197
|
-
undefined;
|
|
198
|
-
const timestamp = () => Date.now();
|
|
199
|
-
const runError = (message) => ({
|
|
200
|
-
type: EventType.RUN_ERROR,
|
|
201
|
-
model,
|
|
202
|
-
timestamp: timestamp(),
|
|
203
|
-
message,
|
|
204
|
-
error: { message }
|
|
205
|
-
});
|
|
206
|
-
yield {
|
|
207
|
-
type: EventType.RUN_STARTED,
|
|
208
|
-
runId,
|
|
209
|
-
threadId,
|
|
210
|
-
model,
|
|
211
|
-
timestamp: timestamp(),
|
|
212
|
-
...(options.parentRunId && { parentRunId: options.parentRunId })
|
|
213
|
-
};
|
|
214
|
-
const tools = toOpenAITools(options.tools);
|
|
215
|
-
const toolNames = new Set(tools.map((tool) => tool.function.name));
|
|
216
|
-
const send = options.wrapFetch ? options.wrapFetch(fetch) : fetch;
|
|
217
|
-
const url = `${this.baseUrl}/chat/completions`;
|
|
218
|
-
logger.request(`activity=chat provider=apfel model=${model} messages=${options.messages.length} tools=${tools.length} stream=true`, { provider: "apfel", model });
|
|
219
|
-
const sentAt = performance.now();
|
|
220
|
-
let response;
|
|
9
|
+
import { openaiCompatibleText } from "@tanstack/ai-openai/compatible";
|
|
10
|
+
import { APFEL_MODEL_META } from "./model-meta.js";
|
|
11
|
+
const DEFAULT_BASE_URL = "http://127.0.0.1:11434/v1";
|
|
12
|
+
export function apfelText(modelOrConfig, maybeConfig = {}) {
|
|
13
|
+
const model = typeof modelOrConfig === "string" ? modelOrConfig : "apple-foundationmodel";
|
|
14
|
+
const config = typeof modelOrConfig === "string" ? maybeConfig : (modelOrConfig ?? {});
|
|
15
|
+
const baseURL = (config.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
16
|
+
const headers = config.defaultHeaders;
|
|
17
|
+
const adapter = openaiCompatibleText(model, {
|
|
18
|
+
name: "apfel",
|
|
19
|
+
baseURL,
|
|
20
|
+
// apfel takes any key unless it was started with a token (see defaultHeaders).
|
|
21
|
+
apiKey: "apfel",
|
|
22
|
+
api: "chat-completions",
|
|
23
|
+
...(headers && { defaultHeaders: headers }),
|
|
24
|
+
// apfel runs on the user's own machine: there's no secret key to expose.
|
|
25
|
+
dangerouslyAllowBrowser: true
|
|
26
|
+
});
|
|
27
|
+
const availability = async (signal) => {
|
|
221
28
|
try {
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
headers
|
|
225
|
-
|
|
226
|
-
...options.modelOptions,
|
|
227
|
-
model,
|
|
228
|
-
stream: true,
|
|
229
|
-
// Token counts, for the stats.
|
|
230
|
-
stream_options: { include_usage: true },
|
|
231
|
-
messages: [
|
|
232
|
-
...systemMessages(options.systemPrompts),
|
|
233
|
-
...toOpenAIMessages(options.messages)
|
|
234
|
-
],
|
|
235
|
-
...(tools.length > 0 && {
|
|
236
|
-
tools,
|
|
237
|
-
...toolChoice(options.toolChoice)
|
|
238
|
-
})
|
|
239
|
-
}),
|
|
240
|
-
signal
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
catch (error) {
|
|
244
|
-
if (signal?.aborted)
|
|
245
|
-
return;
|
|
246
|
-
logger.errors("apfel.chatStream fetch failed", {
|
|
247
|
-
error,
|
|
248
|
-
source: "apfel.chatStream"
|
|
29
|
+
const timeout = AbortSignal.timeout(10_000);
|
|
30
|
+
const response = await fetch(`${baseURL}/models`, {
|
|
31
|
+
...(headers && { headers }),
|
|
32
|
+
signal: signal ? AbortSignal.any([signal, timeout]) : timeout
|
|
249
33
|
});
|
|
250
|
-
|
|
251
|
-
return;
|
|
34
|
+
const list = (await response.json());
|
|
35
|
+
return response.ok && list.data?.some((m) => m.id === model) ? "available" : "unavailable";
|
|
252
36
|
}
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
return;
|
|
37
|
+
catch {
|
|
38
|
+
return "unavailable";
|
|
256
39
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
if (
|
|
266
|
-
|
|
267
|
-
reasoning = "closed";
|
|
268
|
-
events.push({
|
|
269
|
-
type: EventType.REASONING_MESSAGE_END,
|
|
270
|
-
messageId: reasoningId,
|
|
271
|
-
model,
|
|
272
|
-
timestamp: timestamp()
|
|
273
|
-
}, {
|
|
274
|
-
type: EventType.REASONING_END,
|
|
275
|
-
messageId: reasoningId,
|
|
276
|
-
model,
|
|
277
|
-
timestamp: timestamp()
|
|
278
|
-
});
|
|
279
|
-
};
|
|
280
|
-
const addReasoning = (delta) => {
|
|
281
|
-
if (reasoning === "none") {
|
|
282
|
-
events.push({
|
|
283
|
-
type: EventType.REASONING_START,
|
|
284
|
-
messageId: reasoningId,
|
|
285
|
-
model,
|
|
286
|
-
timestamp: timestamp()
|
|
287
|
-
}, {
|
|
288
|
-
type: EventType.REASONING_MESSAGE_START,
|
|
289
|
-
messageId: reasoningId,
|
|
290
|
-
role: "reasoning",
|
|
291
|
-
model,
|
|
292
|
-
timestamp: timestamp()
|
|
293
|
-
});
|
|
294
|
-
}
|
|
295
|
-
reasoning = "open";
|
|
296
|
-
events.push({
|
|
297
|
-
type: EventType.REASONING_MESSAGE_CONTENT,
|
|
298
|
-
messageId: reasoningId,
|
|
299
|
-
delta,
|
|
300
|
-
model,
|
|
301
|
-
timestamp: timestamp()
|
|
302
|
-
});
|
|
303
|
-
};
|
|
304
|
-
const addText = (delta) => {
|
|
305
|
-
if (!delta)
|
|
306
|
-
return;
|
|
307
|
-
endReasoning();
|
|
308
|
-
if (!textStarted) {
|
|
309
|
-
textStarted = true;
|
|
310
|
-
events.push({
|
|
311
|
-
type: EventType.TEXT_MESSAGE_START,
|
|
312
|
-
messageId,
|
|
313
|
-
role: "assistant",
|
|
314
|
-
model,
|
|
315
|
-
timestamp: timestamp()
|
|
316
|
-
});
|
|
317
|
-
}
|
|
318
|
-
text += delta;
|
|
319
|
-
events.push({
|
|
320
|
-
type: EventType.TEXT_MESSAGE_CONTENT,
|
|
321
|
-
messageId,
|
|
322
|
-
delta,
|
|
323
|
-
content: text,
|
|
324
|
-
model,
|
|
325
|
-
timestamp: timestamp()
|
|
326
|
-
});
|
|
327
|
-
};
|
|
328
|
-
const endText = () => {
|
|
329
|
-
if (!textStarted)
|
|
330
|
-
return;
|
|
331
|
-
textStarted = false;
|
|
332
|
-
events.push({
|
|
333
|
-
type: EventType.TEXT_MESSAGE_END,
|
|
334
|
-
messageId,
|
|
335
|
-
model,
|
|
336
|
-
timestamp: timestamp()
|
|
337
|
-
});
|
|
338
|
-
};
|
|
339
|
-
// When apfel doesn't recognize a tool call, it passes it on as text;
|
|
340
|
-
// that part is held back and read once the reply ends.
|
|
341
|
-
const splitter = createToolCallSplitter(JSON_TOOL_CALLS_MARKER);
|
|
342
|
-
// Tool calls stream in pieces, by index.
|
|
343
|
-
const streamed = [];
|
|
344
|
-
// apfel streams a few tokens per chunk: the first chunk's share of the
|
|
345
|
-
// characters stands in for its share of the tokens.
|
|
346
|
-
const timing = { first: 0, last: 0, firstChars: 0, chars: 0 };
|
|
347
|
-
let usage;
|
|
348
|
-
let finishReason = null;
|
|
349
|
-
try {
|
|
350
|
-
for await (const data of sseData(response.body)) {
|
|
351
|
-
if (data === "[DONE]")
|
|
352
|
-
break;
|
|
353
|
-
const chunk = JSON.parse(data);
|
|
354
|
-
logger.provider("provider=apfel", { chunk });
|
|
355
|
-
if (chunk.error) {
|
|
356
|
-
throw new Error(chunk.error.message ?? "apfel sent an error.");
|
|
357
|
-
}
|
|
358
|
-
usage = chunk.usage ?? usage;
|
|
359
|
-
const choice = chunk.choices?.[0];
|
|
360
|
-
const delta = choice?.delta;
|
|
361
|
-
const chars = (delta?.content?.length ?? 0) +
|
|
362
|
-
(delta?.reasoning_content?.length ?? 0) +
|
|
363
|
-
(delta?.tool_calls ?? []).reduce((n, piece) => n +
|
|
364
|
-
(piece.function?.name?.length ?? 0) +
|
|
365
|
-
(piece.function?.arguments?.length ?? 0), 0);
|
|
366
|
-
if (chars > 0) {
|
|
367
|
-
timing.last = performance.now();
|
|
368
|
-
if (!timing.first) {
|
|
369
|
-
timing.first = timing.last;
|
|
370
|
-
timing.firstChars = chars;
|
|
371
|
-
// Token counts come only with the usage at the end.
|
|
372
|
-
this.onStats?.({ firstTokenMs: timing.first - sentAt }, { threadId, runId, callId, done: false });
|
|
373
|
-
}
|
|
374
|
-
timing.chars += chars;
|
|
375
|
-
}
|
|
376
|
-
if (delta?.reasoning_content)
|
|
377
|
-
addReasoning(delta.reasoning_content);
|
|
378
|
-
if (delta?.content)
|
|
379
|
-
addText(splitter.push(delta.content));
|
|
380
|
-
for (const piece of delta?.tool_calls ?? []) {
|
|
381
|
-
// apfel numbers its calls call_1, call_2… in every response; the
|
|
382
|
-
// adapter gives them ids of its own that are unique in the thread.
|
|
383
|
-
const call = (streamed[piece.index] ??= { name: "", arguments: "" });
|
|
384
|
-
call.name += piece.function?.name ?? "";
|
|
385
|
-
call.arguments += piece.function?.arguments ?? "";
|
|
386
|
-
}
|
|
387
|
-
if (choice?.finish_reason)
|
|
388
|
-
finishReason = choice.finish_reason;
|
|
389
|
-
yield* events.splice(0);
|
|
40
|
+
};
|
|
41
|
+
const apfel = Object.assign(adapter, {
|
|
42
|
+
inputModalities: Object.hasOwn(APFEL_MODEL_META, model) ? APFEL_MODEL_META[model].supports.input : undefined,
|
|
43
|
+
availability,
|
|
44
|
+
async create({ signal } = {}) {
|
|
45
|
+
signal?.throwIfAborted();
|
|
46
|
+
const answer = await availability(signal);
|
|
47
|
+
signal?.throwIfAborted();
|
|
48
|
+
if (answer !== "available") {
|
|
49
|
+
throw new Error(`apfel at ${baseURL} didn't answer, or doesn't serve ${model}. Start it with \`apfel --serve --cors\`.`);
|
|
390
50
|
}
|
|
51
|
+
return apfel;
|
|
391
52
|
}
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
return;
|
|
395
|
-
logger.errors("apfel.chatStream stream failed", {
|
|
396
|
-
error,
|
|
397
|
-
source: "apfel.chatStream"
|
|
398
|
-
});
|
|
399
|
-
endReasoning();
|
|
400
|
-
endText();
|
|
401
|
-
yield* events.splice(0);
|
|
402
|
-
yield runError(`apfel's stream failed: ${errorText(error)}`);
|
|
403
|
-
return;
|
|
404
|
-
}
|
|
405
|
-
const outputTokens = usage?.completion_tokens;
|
|
406
|
-
this.onStats?.({
|
|
407
|
-
inputTokens: usage?.prompt_tokens,
|
|
408
|
-
cachedTokens: usage?.prompt_tokens_details?.cached_tokens,
|
|
409
|
-
outputTokens,
|
|
410
|
-
...(timing.first && {
|
|
411
|
-
firstTokenMs: timing.first - sentAt,
|
|
412
|
-
...(outputTokens !== undefined && {
|
|
413
|
-
decodeTokens: (outputTokens * (timing.chars - timing.firstChars)) /
|
|
414
|
-
timing.chars,
|
|
415
|
-
decodeMs: timing.last - timing.first
|
|
416
|
-
})
|
|
417
|
-
})
|
|
418
|
-
}, { threadId, runId, callId, done: true });
|
|
419
|
-
endReasoning();
|
|
420
|
-
const { text: rest, markup } = splitter.flush();
|
|
421
|
-
const fromText = markup && streamed.length === 0
|
|
422
|
-
? parseJsonToolCalls(markup, toolNames)
|
|
423
|
-
: [];
|
|
424
|
-
// Text that wasn't a readable tool call is shown after all.
|
|
425
|
-
addText(`${rest}${fromText.length > 0 ? "" : (markup ?? "")}`);
|
|
426
|
-
yield* events.splice(0);
|
|
427
|
-
// Calls to tools that don't exist are passed on too: `chat()` answers
|
|
428
|
-
// them with an "Unknown tool" error, so the model can answer with what
|
|
429
|
-
// it has instead of stopping there.
|
|
430
|
-
const calls = [
|
|
431
|
-
...streamed.filter((call) => call?.name),
|
|
432
|
-
...fromText.map((call) => ({
|
|
433
|
-
name: call.name,
|
|
434
|
-
arguments: JSON.stringify(call.args)
|
|
435
|
-
}))
|
|
436
|
-
];
|
|
437
|
-
for (const [index, call] of calls.entries()) {
|
|
438
|
-
const toolCallId = nextId("tool");
|
|
439
|
-
const args = call.arguments || "{}";
|
|
440
|
-
const input = parseArguments(args);
|
|
441
|
-
yield {
|
|
442
|
-
type: EventType.TOOL_CALL_START,
|
|
443
|
-
toolCallId,
|
|
444
|
-
toolCallName: call.name,
|
|
445
|
-
parentMessageId: messageId,
|
|
446
|
-
index,
|
|
447
|
-
model,
|
|
448
|
-
timestamp: timestamp()
|
|
449
|
-
};
|
|
450
|
-
yield {
|
|
451
|
-
type: EventType.TOOL_CALL_ARGS,
|
|
452
|
-
toolCallId,
|
|
453
|
-
delta: args,
|
|
454
|
-
args,
|
|
455
|
-
model,
|
|
456
|
-
timestamp: timestamp()
|
|
457
|
-
};
|
|
458
|
-
yield {
|
|
459
|
-
type: EventType.TOOL_CALL_END,
|
|
460
|
-
toolCallId,
|
|
461
|
-
toolCallName: call.name,
|
|
462
|
-
args,
|
|
463
|
-
// Arguments that aren't JSON are left out; `chat()` reports them.
|
|
464
|
-
...(input && { input }),
|
|
465
|
-
model,
|
|
466
|
-
timestamp: timestamp()
|
|
467
|
-
};
|
|
468
|
-
}
|
|
469
|
-
endText();
|
|
470
|
-
yield* events.splice(0);
|
|
471
|
-
const finishUsage = usageOf(usage);
|
|
472
|
-
yield {
|
|
473
|
-
type: EventType.RUN_FINISHED,
|
|
474
|
-
runId,
|
|
475
|
-
threadId,
|
|
476
|
-
model,
|
|
477
|
-
timestamp: timestamp(),
|
|
478
|
-
finishReason: calls.length > 0
|
|
479
|
-
? "tool_calls"
|
|
480
|
-
: finishReason === "tool_calls" || finishReason === null
|
|
481
|
-
? "stop"
|
|
482
|
-
: finishReason,
|
|
483
|
-
...(finishUsage && { usage: finishUsage })
|
|
484
|
-
};
|
|
485
|
-
}
|
|
486
|
-
/**
|
|
487
|
-
* A JSON answer for `chat({ outputSchema })`, from apfel's JSON mode:
|
|
488
|
-
* `response_format: json_schema` constrains Apple's model to the schema
|
|
489
|
-
* (guided generation). `chat()` validates the result.
|
|
490
|
-
*/
|
|
491
|
-
async structuredOutput(options) {
|
|
492
|
-
const { chatOptions, outputSchema } = options;
|
|
493
|
-
const model = this.model;
|
|
494
|
-
const send = chatOptions.wrapFetch ? chatOptions.wrapFetch(fetch) : fetch;
|
|
495
|
-
chatOptions.logger.request(`activity=chat provider=apfel model=${model} messages=${chatOptions.messages.length} tools=0 stream=false`, { provider: "apfel", model });
|
|
496
|
-
let response;
|
|
497
|
-
try {
|
|
498
|
-
response = await send(`${this.baseUrl}/chat/completions`, {
|
|
499
|
-
method: "POST",
|
|
500
|
-
headers: { "Content-Type": "application/json" },
|
|
501
|
-
body: JSON.stringify({
|
|
502
|
-
...chatOptions.modelOptions,
|
|
503
|
-
model,
|
|
504
|
-
messages: [
|
|
505
|
-
...systemMessages(chatOptions.systemPrompts),
|
|
506
|
-
...toOpenAIMessages(chatOptions.messages)
|
|
507
|
-
],
|
|
508
|
-
response_format: {
|
|
509
|
-
type: "json_schema",
|
|
510
|
-
json_schema: { name: "output", schema: outputSchema }
|
|
511
|
-
}
|
|
512
|
-
}),
|
|
513
|
-
signal: chatOptions.abortController?.signal ??
|
|
514
|
-
chatOptions.request?.signal ??
|
|
515
|
-
undefined
|
|
516
|
-
});
|
|
517
|
-
}
|
|
518
|
-
catch (error) {
|
|
519
|
-
chatOptions.logger.errors("apfel.structuredOutput fetch failed", {
|
|
520
|
-
error,
|
|
521
|
-
source: "apfel.structuredOutput"
|
|
522
|
-
});
|
|
523
|
-
if (chatOptions.abortController?.signal.aborted)
|
|
524
|
-
throw error;
|
|
525
|
-
throw new Error(unreachable(this.baseUrl));
|
|
526
|
-
}
|
|
527
|
-
if (!response.ok) {
|
|
528
|
-
throw new Error(`apfel returned HTTP ${response.status}: ${await errorBody(response)}`);
|
|
529
|
-
}
|
|
530
|
-
const completion = (await response.json());
|
|
531
|
-
const choice = completion.choices?.[0];
|
|
532
|
-
if (choice?.finish_reason === "length") {
|
|
533
|
-
throw new Error("apfel's answer was cut off at the token limit before its JSON ended; raise modelOptions.max_tokens.");
|
|
534
|
-
}
|
|
535
|
-
const rawText = (choice?.message?.content ??
|
|
536
|
-
choice?.message?.refusal ??
|
|
537
|
-
"").trim();
|
|
538
|
-
const json = rawText.replace(/^```(?:json)?\s*|\s*```$/g, "");
|
|
539
|
-
const usage = usageOf(completion.usage);
|
|
540
|
-
try {
|
|
541
|
-
return {
|
|
542
|
-
data: JSON.parse(json),
|
|
543
|
-
rawText,
|
|
544
|
-
model,
|
|
545
|
-
...(usage && { usage })
|
|
546
|
-
};
|
|
547
|
-
}
|
|
548
|
-
catch {
|
|
549
|
-
throw new Error(`The model's answer isn't JSON: ${rawText.slice(0, 200)}${rawText.length > 200 ? "…" : ""}`);
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
/**
|
|
554
|
-
* A TanStack AI adapter for Apple's on-device Foundation Model through
|
|
555
|
-
* apfel (`apfel --serve --cors`).
|
|
556
|
-
*
|
|
557
|
-
* @example
|
|
558
|
-
* ```ts
|
|
559
|
-
* chat({ adapter: apfel(), messages, threadId })
|
|
560
|
-
* ```
|
|
561
|
-
*/
|
|
562
|
-
export function apfel(options) {
|
|
563
|
-
return new ApfelTextAdapter(options);
|
|
564
|
-
}
|
|
565
|
-
/**
|
|
566
|
-
* Whether apfel is running and serves the model: true if `GET /v1/models`
|
|
567
|
-
* lists it within 10 seconds.
|
|
568
|
-
*/
|
|
569
|
-
export async function isApfelAvailable(options = {}) {
|
|
570
|
-
const baseUrl = (options.baseUrl ?? APFEL_BASE_URL).replace(/\/+$/, "");
|
|
571
|
-
const model = options.model ?? APFEL_MODEL;
|
|
572
|
-
try {
|
|
573
|
-
const response = await fetch(`${baseUrl}/models`, {
|
|
574
|
-
signal: AbortSignal.timeout(10_000)
|
|
575
|
-
});
|
|
576
|
-
if (!response.ok)
|
|
577
|
-
return false;
|
|
578
|
-
const list = (await response.json());
|
|
579
|
-
return list.data?.some((m) => m.id === model) ?? false;
|
|
580
|
-
}
|
|
581
|
-
catch {
|
|
582
|
-
return false;
|
|
583
|
-
}
|
|
53
|
+
});
|
|
54
|
+
return apfel;
|
|
584
55
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool schemas in the subset of JSON Schema that apfel's guided generation
|
|
3
|
+
* enforces, for the tool step's arguments (see adapter.ts, `stepSchema`).
|
|
4
|
+
* apfel rejects the keywords it can't enforce with HTTP 400.
|
|
5
|
+
*/
|
|
6
|
+
type JsonSchema = Record<string, unknown>;
|
|
7
|
+
/**
|
|
8
|
+
* The schema in the subset guided generation enforces: types, properties,
|
|
9
|
+
* required, items, enum, const and descriptions. Local `$ref`s are inlined,
|
|
10
|
+
* `anyOf`/`oneOf`/type unions become their first non-null choice, and
|
|
11
|
+
* constraints it can't enforce (lengths, patterns, formats…) are dropped.
|
|
12
|
+
*/
|
|
13
|
+
export declare function toGuidedSchema(schema: unknown, root?: JsonSchema, depth?: number): JsonSchema;
|
|
14
|
+
/**
|
|
15
|
+
* Arguments written under `toGuidedSchema`, without the nulls it allows in
|
|
16
|
+
* optional fields: a null is a field the model left out.
|
|
17
|
+
*/
|
|
18
|
+
export declare function withoutNulls(value: unknown, schema: JsonSchema): unknown;
|
|
19
|
+
export {};
|
|
20
|
+
//# sourceMappingURL=guided-schema.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guided-schema.d.ts","sourceRoot":"","sources":["../src/guided-schema.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAoBzC;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,OAAO,EACf,IAAI,GAAE,UAA2C,EACjD,KAAK,SAAI,GACR,UAAU,CA4EZ;AA2BD;;;GAGG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAuBxE"}
|