@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.
@@ -0,0 +1,584 @@
1
+ /**
2
+ * A TanStack AI text adapter for Apple's on-device Foundation Model, served
3
+ * by apfel's OpenAI-compatible server (`apfel --serve --cors`). No backend
4
+ * involved: the browser streams straight from localhost. Hand it to `chat()`
5
+ * like any hosted model's adapter: `chat()` runs tools and the agent loop,
6
+ * and each `chatStream` call here is one completion from apfel, streamed
7
+ * back as AG-UI events.
8
+ */
9
+ import { EventType, normalizeSystemPrompts } from "@tanstack/ai";
10
+ import { BaseTextAdapter } from "@tanstack/ai/adapters";
11
+ import { JSON_TOOL_CALLS_MARKER, createToolCallSplitter, parseJsonToolCalls } from "./tool-calls.js";
12
+ /** Where `apfel --serve` listens by default. */
13
+ export const APFEL_BASE_URL = "http://127.0.0.1:11434/v1";
14
+ /** The model id apfel serves Apple's Foundation Model under. */
15
+ export const APFEL_MODEL = "apple-foundationmodel";
16
+ /**
17
+ * A tool result for the model. A failed tool gives its error message, so the
18
+ * model can see what went wrong and try again.
19
+ */
20
+ function toolResultText(m) {
21
+ const text = contentText(m.content);
22
+ if (m.error)
23
+ return `Error: ${m.error}`;
24
+ return text && text !== "null" ? text : "The tool returned nothing.";
25
+ }
26
+ function contentText(content) {
27
+ if (typeof content === "string")
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;
221
+ try {
222
+ response = await send(url, {
223
+ method: "POST",
224
+ headers: { "Content-Type": "application/json" },
225
+ body: JSON.stringify({
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"
249
+ });
250
+ yield runError(unreachable(this.baseUrl));
251
+ return;
252
+ }
253
+ if (!response.ok || !response.body) {
254
+ yield runError(`apfel returned HTTP ${response.status}: ${await errorBody(response)}`);
255
+ return;
256
+ }
257
+ // Reasoning (apfel sends none for Apple's model today) streams as
258
+ // reasoning events, then the answer as text up to any tool call the
259
+ // model wrote as text, which is held back and parsed at the end.
260
+ let reasoning = "none";
261
+ let textStarted = false;
262
+ let text = "";
263
+ const events = [];
264
+ const endReasoning = () => {
265
+ if (reasoning !== "open")
266
+ return;
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);
390
+ }
391
+ }
392
+ catch (error) {
393
+ if (signal?.aborted)
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
+ }
584
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * TanStack AI adapter for Apple's on-device Foundation Model, served by apfel.
3
+ */
4
+ export { APFEL_BASE_URL, APFEL_MODEL, ApfelTextAdapter, apfel, isApfelAvailable } from "./adapter.js";
5
+ export type { ApfelModelOptions, ApfelOptions, ApfelStats } from "./adapter.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EACL,cAAc,EACd,WAAW,EACX,gBAAgB,EAChB,KAAK,EACL,gBAAgB,EACjB,MAAM,cAAc,CAAA;AACrB,YAAY,EAAE,iBAAiB,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ /**
2
+ * TanStack AI adapter for Apple's on-device Foundation Model, served by apfel.
3
+ */
4
+ export { APFEL_BASE_URL, APFEL_MODEL, ApfelTextAdapter, apfel, isApfelAvailable } from "./adapter.js";
@@ -0,0 +1,32 @@
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
+ export type ParsedToolCall = {
8
+ name: string;
9
+ args: Record<string, unknown>;
10
+ };
11
+ /** Where Apple's model starts a tool call it writes as text. */
12
+ export declare const JSON_TOOL_CALLS_MARKER = "{\"tool_calls\"";
13
+ /**
14
+ * Tool calls Apple's model wrote as JSON text. Its JSON varies and is often
15
+ * broken (`"function": "name"`, `"name: "name"`, stray strings in the
16
+ * arguments), so instead of parsing the whole thing, this finds each quoted
17
+ * name of a tool that exists and reads the `"arguments"` object after it.
18
+ */
19
+ export declare function parseJsonToolCalls(text: string, toolNames: Iterable<string>): Array<ParsedToolCall>;
20
+ /**
21
+ * Splits a streaming answer into the text before the first tool call written
22
+ * as text (passed through as it arrives) and the tool-call JSON after it
23
+ * (held back and parsed once the reply ends).
24
+ */
25
+ export declare function createToolCallSplitter(marker?: string): {
26
+ push: (text: string) => string;
27
+ flush: () => {
28
+ text: string;
29
+ markup: string | null;
30
+ };
31
+ };
32
+ //# sourceMappingURL=tool-calls.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-calls.d.ts","sourceRoot":"","sources":["../src/tool-calls.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,MAAM,cAAc,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,CAAA;AAE5E,gEAAgE;AAChE,eAAO,MAAM,sBAAsB,oBAAkB,CAAA;AAkCrD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,GAC1B,KAAK,CAAC,cAAc,CAAC,CAiCvB;AAUD;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,SAAyB;iBAKhD,MAAM;;;;;EA2B3B"}