File size: 19,100 Bytes
3adb92a
2ec195c
 
 
 
d2850b8
2ec195c
 
 
 
4975320
 
 
 
 
 
 
173f635
4975320
 
 
eebd3be
 
5383ef0
 
 
 
 
 
 
 
b310ce2
8bd700e
5383ef0
 
 
8bd700e
1a4d797
a78b2c4
1a4d797
 
670ebb9
 
5383ef0
3adb92a
 
 
 
 
 
2ec195c
3adb92a
 
 
 
2b4a989
d2850b8
811bf80
 
ff954f1
42f1e7b
0cb48f9
 
ff954f1
 
 
 
 
 
 
0cb48f9
ff954f1
42f1e7b
ff954f1
 
42f1e7b
 
 
ff954f1
42f1e7b
 
 
357bada
 
ff954f1
2b4a989
0cb48f9
ff954f1
0cb48f9
ff954f1
 
 
 
 
 
 
 
 
 
 
 
811bf80
0cb48f9
42f1e7b
ff954f1
42f1e7b
 
357bada
 
ff954f1
2b4a989
357bada
3adb92a
0cb48f9
ff954f1
3adb92a
357bada
ff954f1
0cb48f9
 
42f1e7b
0cb48f9
ff954f1
0cb48f9
 
 
ff954f1
d2850b8
 
ff954f1
 
 
811bf80
ff954f1
2b4a989
ff954f1
 
811bf80
2b4a989
 
357bada
0cb48f9
357bada
ff954f1
0cb48f9
357bada
ff954f1
3adb92a
 
ff954f1
0cb48f9
 
 
 
 
 
 
 
 
 
ff954f1
357bada
ff954f1
357bada
0cb48f9
 
 
42f1e7b
0cb48f9
ff954f1
42f1e7b
357bada
d2850b8
3adb92a
42f1e7b
ff954f1
 
42f1e7b
 
 
ff954f1
 
2b4a989
357bada
3adb92a
 
1a4d797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cb48f9
5383ef0
 
c81fc00
5383ef0
 
 
 
 
 
 
 
 
 
 
357bada
3adb92a
5383ef0
cfae871
357bada
cfae871
357bada
 
 
cfae871
357bada
 
 
 
 
35318fb
 
357bada
 
35318fb
 
357bada
cfae871
357bada
 
 
 
 
 
 
 
cfae871
 
 
357bada
c81fc00
 
 
357bada
5383ef0
 
8d1cf35
5383ef0
357bada
35318fb
0cb48f9
 
 
 
cfae871
5383ef0
357bada
 
0cb48f9
357bada
1baccaa
5383ef0
357bada
 
 
3adb92a
357bada
0cb48f9
357bada
5383ef0
357bada
 
5383ef0
 
357bada
3adb92a
0cb48f9
357bada
 
 
 
 
 
 
3adb92a
5383ef0
 
357bada
8d1cf35
cfae871
357bada
35318fb
357bada
 
0cb48f9
357bada
cfae871
357bada
cfae871
357bada
 
 
0cb48f9
357bada
 
cfae871
5383ef0
357bada
 
3adb92a
0cb48f9
357bada
 
 
 
3adb92a
 
5383ef0
 
1a4d797
 
 
357bada
5383ef0
357bada
 
 
 
 
 
5383ef0
0cb48f9
5383ef0
 
 
 
 
8d1cf35
 
5383ef0
8d1cf35
 
5383ef0
 
 
baab24d
cfae871
 
 
 
 
 
baab24d
 
 
 
 
 
1baccaa
5383ef0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ec195c
 
 
 
 
 
 
 
 
 
5383ef0
 
 
 
 
 
 
 
 
 
 
2ec195c
5383ef0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcacccd
fb79c98
dcacccd
fb79c98
5383ef0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcacccd
fb79c98
dcacccd
fb79c98
5383ef0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcacccd
fb79c98
5383ef0
aefe3d6
5383ef0
 
 
d70ec8d
5383ef0
 
 
 
 
 
 
 
 
 
 
 
 
8d1cf35
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
import OpenAI from "openai";
import { Worker } from "worker_threads";
import { fileURLToPath } from "url";
import path from "path";
import { LIGHTNING_BASE } from "./config.js";
import WebSocket from "ws";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const WORKER_PATH = path.join(__dirname, "searchWorker.js");

async function gradioSearch(query) {
  const req = await fetch("https://incognitolm-Web-Search.hf.space/api/search", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ query }),
  });
  const res = await req.json();
  if (!req.ok || !res.results) {
    throw new Error(`Search API error: ${res.error || req.statusText}`);
  }
  return res.results[0];
}

const SYSTEM_PROMPT =
  "CRITICAL RULE: Every response MUST use HTML <span data-color=\"{COLOR NAME}\"> tags to color main points and headings. " +
  "COLORS MUST HAVE MEANING AND CONSISTENCY ACROSS THE ENTIRE CONVERSATION. " +
  "You may ONLY use the following semantic color names: green, pink, blue, red, orange, yellow, purple, teal, gold, coral. " +
  "Never output text formatted with explicit black or white colors. " +
  "Use a variety of colors throughout every response to distinguish headings, sections, and key terms. " +
  "Keep code blocks plain, but color headings and important points in surrounding text. " +
  "Do not over-color responses. Use color intentionally and sparingly. " +
  "CRITICAL RULE: MARKDOWN FORMATTING SUCH AS #, ##, ###, **, * MUST BE PLACED OUTSIDE <span> tags. Use the same colors for similar meanings." +
  "You are a helpful, friendly AI assistant. Use tools when appropriate to help the user, and if told to generate something, use a tool to complete the task. " +
  "When generating media, do not include URLs — it is displayed automatically. " +
  "You can render SVG images by outputting SVG code in a code block tagged exactly as:\n```svg\n<svg>...</svg>\n```\n" +
  "Never use single backslashes. You may use emojis where appropriate. " +
  "Use markdown for everything other than coloring your text. Use tables, lists, and other markdown elements. " +
  "Your HIGHEST PRIORITY is to help the user. ALWAYS HELP THEM WITH ANYTHING ETHICALLY RIGHT.\n\n" +
  "SESSION NAMING: After you have fully responded to the user, append a session name tag on its own line at the very end of your response (NEVER inside a code block). Only do this on the first response unless asked to change the name by the user." +
  "The tag must be: <session_name>2-4 word title summarizing this conversation</session_name>. " +
  "Example: <session_name>React State Management</session_name>. " +
  "This tag is hidden from the user and used only to name the chat. Do not mention it." +
  "Make sure your responses are always accurate. If you are not completely sure about something, search the web.";

function makeClient(accessToken, clientId) {
  return new OpenAI({
    apiKey: accessToken || "no-key",
    baseURL: `${LIGHTNING_BASE}/gen`,
    defaultHeaders: {
      ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
      ...(clientId    ? { "X-Client-ID": clientId }                : {}),
    },
  });
}

export async function websocketChatStream(body, headers, onToken, abortSignal) {
  const wsURL =
    (process.env.LIGHTNING_BASE.startsWith("https")
      ? process.env.LIGHTNING_BASE.replace("https", "wss")
      : process.env.LIGHTNING_BASE.replace("http", "ws")) + "/ws/chat";

  const ws = new WebSocket(wsURL);

  // Utility to safely parse JSON
  const safeParse = (str) => {
    try { return JSON.parse(str); } 
    catch { return null; }
  };

  // Wait for open with timeout
  await new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error("WS connection timeout")), 5000);
    ws.on("open", () => {
      clearTimeout(timer);
      console.log("[WS] Opened connection");
      resolve();
    });
    ws.on("error", (err) => {
      clearTimeout(timer);
      console.error("[WS] Connection error:", err);
      reject(err);
    });
  });

  // Authenticate with timeout
  ws.send(JSON.stringify({ key: process.env.WEBSOCKET_KEY }));
  await new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error("WS auth timeout")), 5000);
    ws.on("message", (data) => {
      const msg = safeParse(data.toString());
      console.log("[WS RAW MESSAGE]", data.toString());
      if (!msg) return;
      if (msg.type === "auth" && msg.status === "ok") {
        clearTimeout(timer);
        console.log("[WS] Auth successful");
        resolve();
      }
      if (msg.error) {
        clearTimeout(timer);
        console.error("[WS] Auth error:", msg.error);
        reject(new Error(`WS auth error: ${msg.error}`));
      }
    });
    ws.on("error", (err) => {
      clearTimeout(timer);
      reject(err);
    });
  });

  // Send the chat body
  ws.send(JSON.stringify({ body, headers }));

  let assistantText = "";
  const toolCallBuffer = new Map();
  let finished = false;

  return new Promise((resolve, reject) => {
    // Abort handling
    if (abortSignal) {
      abortSignal.addEventListener("abort", () => {
        console.log("[WS] Aborted by signal");
        ws.close();
        if (!finished) reject(new Error("AbortError"));
      });
    }

    // Handle messages
    ws.on("message", (data) => {
      const line = data.toString();
      console.log("[WS MESSAGE RECEIVED]", line);
      let payload = safeParse(line);
      if (!payload) return;

      // Handle errors from server
      if (payload.error) {
        console.error("[WS PAYLOAD ERROR]", payload.error);
        if (typeof onToken === "function") onToken(`[ERROR] ${payload.error}`);
        return;
      }

      const delta = payload.choices?.[0]?.delta;
      if (!delta) return;

      // Stream content tokens
      if (delta.content) {
        assistantText += delta.content;
        if (typeof onToken === "function") onToken(delta.content);
      }

      // Collect tool calls
      if (delta.tool_calls) {
        for (const call of delta.tool_calls) {
          const entry = toolCallBuffer.get(call.index) ?? { arguments: "" };
          if (call.id) entry.id = call.id;
          if (call.function?.name) entry.name = call.function.name;
          if (call.function?.arguments) entry.arguments += call.function.arguments;
          toolCallBuffer.set(call.index, entry);
        }
      }

      // Finish detection
      if (payload.choices?.[0]?.finish_reason) {
        finished = true;
        ws.close();
        const toolCalls = [...toolCallBuffer.values()].map((t) => ({
          id: t.id || `call_${crypto.randomUUID()}`,
          type: "function",
          function: { name: t.name, arguments: t.arguments },
        }));
        console.log("[WS] Finished streaming");
        resolve({ assistantText, toolCalls });
      }
    });

    ws.on("error", (err) => {
      console.error("[WS ERROR]", err);
      if (!finished) reject(err);
    });

    ws.on("close", (code, reason) => {
      console.log(`[WS CLOSED] Code: ${code}, Reason: ${reason}`);
      if (!finished) reject(new Error("WebSocket closed prematurely"));
    });
  });
}

/**
 * Extract session name from <session_name>...</session_name> tag.
 * Must NOT be inside any kind of code block.
 */
export function extractSessionName(text) {
  if (!text) return null;

  // Remove all code blocks first (``` ... ```) so we don't match tags inside them
  const withoutCode = text.replace(/```[\s\S]*?```/g, '');

  const match = withoutCode.match(/<session_name>([\s\S]*?)<\/session_name>/i);
  if (!match) return null;

  const name = match[1].trim();
  // Sanity check: 1-80 chars, no newlines
  if (!name || name.length > 80 || /\n/.test(name)) return null;
  return name;
}

export async function streamChat({
  sessionId,
  model,
  history = [],
  userMessage,
  tools,
  accessToken,
  clientId,
  onToken,
  onDone,
  onError,
  onToolCall,
  onNewAsset,
  abortSignal,
}) {

  const enabledTools = buildToolList(tools);

  let normalizedUserMessage = userMessage;

  if (Array.isArray(userMessage)) {

    const hasImages = userMessage.some(item => item.type === "image_url");

    if (hasImages) {

      const textItems = userMessage.filter(
        item => item.type === "text" && item.text?.trim()
      );

      if (textItems.length === 0) {
        normalizedUserMessage = [
          { type: "text", text: "[Image(s) attached]" },
          ...userMessage.filter(item => item.type === "image_url"),
        ];
      }

    } else {

      normalizedUserMessage =
        userMessage
          .filter(b => b.type === "text")
          .map(b => b.text)
          .join("\n")
          .trim() || "";

    }
  }

  const hasUserMessage =
      userMessage !== undefined &&
      userMessage !== null &&
      (typeof userMessage === "string" ? userMessage.trim() !== "" : Array.isArray(userMessage) && userMessage.length > 0);

  const messages = [
    { role: "system", content: SYSTEM_PROMPT },
    ...history.map(normalizeMessage).filter(Boolean),
  ];

  if (hasUserMessage) {
    messages.push({
      role: "user",
      content: normalizedUserMessage,
    });
  }

  const headers = {
    ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
    ...(clientId ? { "X-Client-ID": clientId } : {}),
  };

  try {

    const body = {
      model: model || "lightning",
      messages,
      tools: enabledTools.length ? enabledTools : undefined,
      stream: true,
    };

    let { assistantText, toolCalls } =
      await websocketChatStream(body, headers, onToken, abortSignal);

    if (toolCalls.length > 0) {

      const toolResults = await processToolCalls(
        null,
        toolCalls,
        tools,
        accessToken,
        clientId,
        abortSignal,
        onToolCall,
        onNewAsset
      );

      const followUpMessages = [
        { role: "system", content: SYSTEM_PROMPT },
        ...history.map(normalizeMessage).filter(Boolean),
      ];

      if (hasUserMessage) {
        followUpMessages.push({
          role: "user",
          content: normalizedUserMessage,
        });
      }

      followUpMessages.push(
        {
          role: "assistant",
          content: assistantText || "",
          tool_calls: toolCalls,
        },
        ...toolResults
      );

      const followUpBody = {
        model: model || "lightning",
        messages: followUpMessages,
        stream: true,
      };

      const followUp =
        await websocketChatStream(followUpBody, headers, onToken, abortSignal);

      assistantText += followUp.assistantText;
    }

    const sessionName = extractSessionName(assistantText);

    onDone(assistantText, toolCalls, false, sessionName);

  } catch (err) {

    if (
      err.name === "AbortError" ||
      err.message === "AbortError"
    ) {
      onDone(null, null, true, null);
    } else {
      console.error("streamChat error:", err);
      onError(String(err));
    }
  }
}

const VALID_ROLES = new Set(["system", "user", "assistant", "tool"]);

function normalizeMessage(msg) {
  if (!VALID_ROLES.has(msg.role)) return null;

  if (msg.role === "assistant" && msg.tool_calls) {
    return { role: "assistant", content: "", tool_calls: msg.tool_calls };
  }
  if (Array.isArray(msg.content)) {
    // If the array contains images, preserve the full array format
    const hasImages = msg.content.some(item => item.type === 'image_url');
    if (hasImages) {
      return { role: msg.role, content: msg.content };
    }
    // Otherwise extract text only
    const textOnly = msg.content
      .filter(b => b.type === "text")
      .map(b => b.text)
      .join("\n");
    return { role: msg.role, content: textOnly || "" };
  }
  return { role: msg.role, content: msg.content ?? "" };
}

function buildToolList(tools) {
  if (!tools) return [];
  const list = [];
  if (tools.webSearch) {
    list.push({
      type: "function",
      function: {
        name: "ollama_search",
        description: "Search the web for current information",
        parameters: {
          type: "object",
          properties: { query: { type: "string", description: "Search query" } },
          required: ["query"],
        },
      },
    });
    list.push({
      type: "function",
      function: {
        name: "read_web_page",
        description: "Read the content of a web page by URL",
        parameters: {
          type: "object",
          properties: { url: { type: "string", description: "URL to fetch" } },
          required: ["url"],
        },
      },
    });
  }
  if (tools.imageGen) {
    list.push({
      type: "function",
      function: {
        name: "generate_image",
        description: "Generate an image from a prompt",
        parameters: {
          type: "object",
          properties: {
            prompt: { type: "string" },
            mode: { type: "string", enum: ["auto", "fantasy", "realistic"] },
            image_urls: { type: "array", items: { type: "string" } },
          },
          required: ["prompt"],
        },
      },
    });
  }
  if (tools.videoGen) {
    list.push({
      type: "function",
      function: {
        name: "generate_video",
        description: "Generate a video from a prompt",
        parameters: {
          type: "object",
          properties: {
            prompt: { type: "string" },
            ratio: { type: "string", enum: ["3:2", "2:3", "1:1"] },
            mode: { type: "string", enum: ["normal", "fun"] },
            duration: { type: "number" },
            image_urls: { type: "array", items: { type: "string" } },
          },
          required: ["prompt"],
        },
      },
    });
  }
  if (tools.audioGen) {
    list.push({
      type: "function",
      function: {
        name: "generate_audio",
        description: "Generate music or sound effects from a prompt",
        parameters: {
          type: "object",
          properties: { prompt: { type: "string" } },
          required: ["prompt"],
        },
      },
    });
  }
  return list;
}

async function processToolCalls(ws, toolCalls, tools, accessToken, clientId, abortSignal, onToolCall, onNewAsset) {
  const toolResults = [];
  const authHeaders = {};
  if (accessToken) {
    authHeaders["Authorization"] = `Bearer ${accessToken}`;
  } else {
    console.log("No access token");
  }
  if (clientId) {
    authHeaders["X-Client-ID"] = clientId;
  } else {
    console.log("No Client ID");
  }

  for (const call of toolCalls) {
    let args;
    try { args = JSON.parse(call.function.arguments || "{}"); } catch { args = {}; }

    onToolCall({ id: call.id, name: call.function.name, state: "pending", args });

    let result = "Tool completed.";

    try {
      if (call.function.name === "ollama_search") {
        result = await gradioSearch(args.query);
      }

      else if (call.function.name === "read_web_page") {
        const { convert } = await import("html-to-text");
        const res = await fetch(args.url, { signal: abortSignal });
        if (!res.ok) {
          result = `Failed to fetch: ${res.status}`;
        } else {
          const html = await res.text();
          const titleMatch = html.match(/<title>(.*?)<\/title>/i);
          result = JSON.stringify({
            title: titleMatch?.[1] || "No title",
            content: convert(html, { wordwrap: false }).slice(0, 8000),
          });
        }
      }

      else if (call.function.name === "generate_image") {
        const body = { prompt: args.prompt };
        if (args.mode) body.mode = args.mode;
        if (args.image_urls?.length) body.image_urls = args.image_urls;

        const res = await fetch(`${LIGHTNING_BASE}/gen/image`, {
          method: "POST",
          headers: { "Content-Type": "application/json", ...authHeaders },
          body: JSON.stringify(body),
          signal: abortSignal,
        });
        if (res.ok) {
          const buf = await res.arrayBuffer();
          const ct = res.headers.get("content-type") || "image/png";
          const b64 = Buffer.from(buf).toString("base64");
          const dataUrl = `data:${ct};base64,${b64}`;
          onNewAsset({ role: "image", content: dataUrl });
          result = "Image generated successfully and shown to the user.";
        } else if (res.status == 402) {
          result = "An upgraded plan is required for higher limits.";
        } else if (res.status == 429) {
          result = "Too many requests. Try again later.";
        } else {
          result = `Image generation failed: ${res.status}`;
        }
      }

      else if (call.function.name === "generate_video") {
        const body = { prompt: args.prompt };
        if (args.ratio) body.ratio = args.ratio;
        if (args.mode) body.mode = args.mode;
        if (args.duration) body.duration = args.duration;
        if (args.image_urls?.length) body.image_urls = args.image_urls;

        const res = await fetch(`${LIGHTNING_BASE}/gen/video`, {
          method: "POST",
          headers: { "Content-Type": "application/json", ...authHeaders },
          body: JSON.stringify(body),
          signal: abortSignal,
        });
        if (res.ok) {
          const buf = await res.arrayBuffer();
          const b64 = Buffer.from(buf).toString("base64");
          const dataUrl = `data:video/mp4;base64,${b64}`;
          onNewAsset({ role: "video", content: dataUrl });
          result = "Video generated successfully and shown to the user.";
        } else if (res.status == 402) {
          result = "An upgraded plan is required for higher limits.";
        } else if (res.status == 429) {
          result = "Too many requests. Try again later.";
        } else {
          result = `Video generation failed: ${res.status}`;
        }
      }

      else if (call.function.name === "generate_audio") {
        const res = await fetch(`${LIGHTNING_BASE}/gen/sfx`, {
          method: "POST",
          headers: { "Content-Type": "application/json", ...authHeaders },
          body: JSON.stringify({ prompt: args.prompt }),
          signal: abortSignal,
        });
        if (res.ok) {
          const buf = await res.arrayBuffer();
          const b64 = Buffer.from(buf).toString("base64");
          const dataUrl = `data:audio/mpeg;base64,${b64}`;
          onNewAsset({ role: "audio", content: dataUrl });
          result = "Audio generated successfully and shown to the user.";
        } else if (res.status == 429) {
          result = "Too many requests. Try again later.";
        } else {
          result = `Audio generation failed: ${res.status}. This is most likely an upstream provider error.`;
        }
      }
    } catch (err) {
      console.log(`Tool error: ${String(err)}`);
      result = `Tool error: ${String(err)}`;
    }

    onToolCall({ id: call.id, name: call.function.name, state: "resolved", result });

    toolResults.push({
      role: "tool",
      tool_call_id: call.id,
      content: typeof result === "string" ? result : JSON.stringify(result),
    });
  }

  return toolResults;
}