@livekit/agents-plugin-openai 0.9.3 → 1.0.0-next.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.
Files changed (47) hide show
  1. package/dist/index.cjs +16 -5
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +4 -4
  4. package/dist/index.d.ts +4 -4
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +14 -3
  7. package/dist/index.js.map +1 -1
  8. package/dist/llm.cjs +156 -197
  9. package/dist/llm.cjs.map +1 -1
  10. package/dist/llm.d.cts +27 -8
  11. package/dist/llm.d.ts +27 -8
  12. package/dist/llm.d.ts.map +1 -1
  13. package/dist/llm.js +164 -188
  14. package/dist/llm.js.map +1 -1
  15. package/dist/models.cjs +14 -0
  16. package/dist/models.cjs.map +1 -1
  17. package/dist/models.d.cts +11 -6
  18. package/dist/models.d.ts +11 -6
  19. package/dist/models.d.ts.map +1 -1
  20. package/dist/models.js +6 -0
  21. package/dist/models.js.map +1 -1
  22. package/dist/realtime/api_proto.cjs.map +1 -1
  23. package/dist/realtime/api_proto.d.cts +15 -0
  24. package/dist/realtime/api_proto.d.ts +15 -0
  25. package/dist/realtime/api_proto.d.ts.map +1 -1
  26. package/dist/realtime/api_proto.js.map +1 -1
  27. package/dist/realtime/realtime_model.cjs +1056 -820
  28. package/dist/realtime/realtime_model.cjs.map +1 -1
  29. package/dist/realtime/realtime_model.d.cts +126 -160
  30. package/dist/realtime/realtime_model.d.ts +126 -160
  31. package/dist/realtime/realtime_model.d.ts.map +1 -1
  32. package/dist/realtime/realtime_model.js +1067 -825
  33. package/dist/realtime/realtime_model.js.map +1 -1
  34. package/dist/tts.cjs +5 -5
  35. package/dist/tts.cjs.map +1 -1
  36. package/dist/tts.d.cts +2 -1
  37. package/dist/tts.d.ts +2 -1
  38. package/dist/tts.d.ts.map +1 -1
  39. package/dist/tts.js +6 -6
  40. package/dist/tts.js.map +1 -1
  41. package/package.json +8 -7
  42. package/src/index.ts +19 -5
  43. package/src/llm.ts +227 -228
  44. package/src/models.ts +83 -5
  45. package/src/realtime/api_proto.ts +15 -1
  46. package/src/realtime/realtime_model.ts +1305 -996
  47. package/src/tts.ts +6 -6
package/dist/index.cjs CHANGED
@@ -27,8 +27,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
27
  mod
28
28
  ));
29
29
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
- var src_exports = {};
31
- __export(src_exports, {
30
+ var index_exports = {};
31
+ __export(index_exports, {
32
32
  ChunkedStream: () => import_tts.ChunkedStream,
33
33
  LLM: () => import_llm.LLM,
34
34
  LLMStream: () => import_llm.LLMStream,
@@ -36,12 +36,23 @@ __export(src_exports, {
36
36
  TTS: () => import_tts.TTS,
37
37
  realtime: () => realtime
38
38
  });
39
- module.exports = __toCommonJS(src_exports);
40
- var realtime = __toESM(require("./realtime/index.cjs"), 1);
41
- __reExport(src_exports, require("./models.cjs"), module.exports);
39
+ module.exports = __toCommonJS(index_exports);
40
+ var import_agents = require("@livekit/agents");
42
41
  var import_llm = require("./llm.cjs");
42
+ __reExport(index_exports, require("./models.cjs"), module.exports);
43
+ var realtime = __toESM(require("./realtime/index.cjs"), 1);
43
44
  var import_stt = require("./stt.cjs");
44
45
  var import_tts = require("./tts.cjs");
46
+ class OpenAIPlugin extends import_agents.Plugin {
47
+ constructor() {
48
+ super({
49
+ title: "openai",
50
+ version: "0.9.1",
51
+ package: "@livekit/agents-plugin-openai"
52
+ });
53
+ }
54
+ }
55
+ import_agents.Plugin.registerPlugin(new OpenAIPlugin());
45
56
  // Annotate the CommonJS export names for ESM import in node:
46
57
  0 && (module.exports = {
47
58
  ChunkedStream,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nexport * as realtime from './realtime/index.js';\nexport * from './models.js';\nexport { type LLMOptions, LLM, LLMStream } from './llm.js';\nexport { type STTOptions, STT } from './stt.js';\nexport { type TTSOptions, TTS, ChunkedStream } from './tts.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,eAA0B;AAC1B,wBAAc,wBAJd;AAKA,iBAAgD;AAChD,iBAAqC;AACrC,iBAAoD;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { Plugin } from '@livekit/agents';\n\nexport { LLM, LLMStream, type LLMOptions } from './llm.js';\nexport * from './models.js';\nexport * as realtime from './realtime/index.js';\nexport { STT, type STTOptions } from './stt.js';\nexport { ChunkedStream, TTS, type TTSOptions } from './tts.js';\n\nclass OpenAIPlugin extends Plugin {\n constructor() {\n super({\n title: 'openai',\n version: '0.9.1',\n package: '@livekit/agents-plugin-openai',\n });\n }\n}\n\nPlugin.registerPlugin(new OpenAIPlugin());\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAAuB;AAEvB,iBAAgD;AAChD,0BAAc,wBANd;AAOA,eAA0B;AAC1B,iBAAqC;AACrC,iBAAoD;AAEpD,MAAM,qBAAqB,qBAAO;AAAA,EAChC,cAAc;AACZ,UAAM;AAAA,MACJ,OAAO;AAAA,MACP,SAAS;AAAA,MACT,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AACF;AAEA,qBAAO,eAAe,IAAI,aAAa,CAAC;","names":[]}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
- export * as realtime from './realtime/index.js';
1
+ export { LLM, LLMStream, type LLMOptions } from './llm.js';
2
2
  export * from './models.js';
3
- export { type LLMOptions, LLM, LLMStream } from './llm.js';
4
- export { type STTOptions, STT } from './stt.js';
5
- export { type TTSOptions, TTS, ChunkedStream } from './tts.js';
3
+ export * as realtime from './realtime/index.js';
4
+ export { STT, type STTOptions } from './stt.js';
5
+ export { ChunkedStream, TTS, type TTSOptions } from './tts.js';
6
6
  //# sourceMappingURL=index.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export * as realtime from './realtime/index.js';
1
+ export { LLM, LLMStream, type LLMOptions } from './llm.js';
2
2
  export * from './models.js';
3
- export { type LLMOptions, LLM, LLMStream } from './llm.js';
4
- export { type STTOptions, STT } from './stt.js';
5
- export { type TTSOptions, TTS, ChunkedStream } from './tts.js';
3
+ export * as realtime from './realtime/index.js';
4
+ export { STT, type STTOptions } from './stt.js';
5
+ export { ChunkedStream, TTS, type TTSOptions } from './tts.js';
6
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAC;AAChD,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,KAAK,UAAU,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAC3D,OAAO,EAAE,KAAK,UAAU,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAChD,OAAO,EAAE,KAAK,UAAU,EAAE,GAAG,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,KAAK,UAAU,EAAE,MAAM,UAAU,CAAC;AAC3D,cAAc,aAAa,CAAC;AAC5B,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,GAAG,EAAE,KAAK,UAAU,EAAE,MAAM,UAAU,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,GAAG,EAAE,KAAK,UAAU,EAAE,MAAM,UAAU,CAAC"}
package/dist/index.js CHANGED
@@ -1,8 +1,19 @@
1
- import * as realtime from "./realtime/index.js";
2
- export * from "./models.js";
1
+ import { Plugin } from "@livekit/agents";
3
2
  import { LLM, LLMStream } from "./llm.js";
3
+ export * from "./models.js";
4
+ import * as realtime from "./realtime/index.js";
4
5
  import { STT } from "./stt.js";
5
- import { TTS, ChunkedStream } from "./tts.js";
6
+ import { ChunkedStream, TTS } from "./tts.js";
7
+ class OpenAIPlugin extends Plugin {
8
+ constructor() {
9
+ super({
10
+ title: "openai",
11
+ version: "0.9.1",
12
+ package: "@livekit/agents-plugin-openai"
13
+ });
14
+ }
15
+ }
16
+ Plugin.registerPlugin(new OpenAIPlugin());
6
17
  export {
7
18
  ChunkedStream,
8
19
  LLM,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nexport * as realtime from './realtime/index.js';\nexport * from './models.js';\nexport { type LLMOptions, LLM, LLMStream } from './llm.js';\nexport { type STTOptions, STT } from './stt.js';\nexport { type TTSOptions, TTS, ChunkedStream } from './tts.js';\n"],"mappings":"AAGA,YAAY,cAAc;AAC1B,cAAc;AACd,SAA0B,KAAK,iBAAiB;AAChD,SAA0B,WAAW;AACrC,SAA0B,KAAK,qBAAqB;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { Plugin } from '@livekit/agents';\n\nexport { LLM, LLMStream, type LLMOptions } from './llm.js';\nexport * from './models.js';\nexport * as realtime from './realtime/index.js';\nexport { STT, type STTOptions } from './stt.js';\nexport { ChunkedStream, TTS, type TTSOptions } from './tts.js';\n\nclass OpenAIPlugin extends Plugin {\n constructor() {\n super({\n title: 'openai',\n version: '0.9.1',\n package: '@livekit/agents-plugin-openai',\n });\n }\n}\n\nPlugin.registerPlugin(new OpenAIPlugin());\n"],"mappings":"AAGA,SAAS,cAAc;AAEvB,SAAS,KAAK,iBAAkC;AAChD,cAAc;AACd,YAAY,cAAc;AAC1B,SAAS,WAA4B;AACrC,SAAS,eAAe,WAA4B;AAEpD,MAAM,qBAAqB,OAAO;AAAA,EAChC,cAAc;AACZ,UAAM;AAAA,MACJ,OAAO;AAAA,MACP,SAAS;AAAA,MACT,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AACF;AAEA,OAAO,eAAe,IAAI,aAAa,CAAC;","names":[]}
package/dist/llm.cjs CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
  var llm_exports = {};
30
20
  __export(llm_exports, {
@@ -33,20 +23,20 @@ __export(llm_exports, {
33
23
  });
34
24
  module.exports = __toCommonJS(llm_exports);
35
25
  var import_agents = require("@livekit/agents");
36
- var import_node_crypto = require("node:crypto");
37
26
  var import_openai = require("openai");
38
- var import_sharp = __toESM(require("sharp"), 1);
39
27
  const defaultLLMOptions = {
40
- model: "gpt-4o",
41
- apiKey: process.env.OPENAI_API_KEY
28
+ model: "gpt-4.1",
29
+ apiKey: process.env.OPENAI_API_KEY,
30
+ parallelToolCalls: true
42
31
  };
43
32
  const defaultAzureLLMOptions = {
44
- model: "gpt-4o",
33
+ model: "gpt-4.1",
45
34
  apiKey: process.env.AZURE_API_KEY
46
35
  };
47
36
  class LLM extends import_agents.llm.LLM {
48
37
  #opts;
49
38
  #client;
39
+ #providerFmt;
50
40
  /**
51
41
  * Create a new instance of OpenAI LLM.
52
42
  *
@@ -54,9 +44,10 @@ class LLM extends import_agents.llm.LLM {
54
44
  * `apiKey` must be set to your OpenAI API key, either using the argument or by setting the
55
45
  * `OPENAI_API_KEY` environmental variable.
56
46
  */
57
- constructor(opts = defaultLLMOptions) {
47
+ constructor(opts = defaultLLMOptions, providerFmt = "openai") {
58
48
  super();
59
49
  this.#opts = { ...defaultLLMOptions, ...opts };
50
+ this.#providerFmt = providerFmt;
60
51
  if (this.#opts.apiKey === void 0) {
61
52
  throw new Error("OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY");
62
53
  }
@@ -65,6 +56,12 @@ class LLM extends import_agents.llm.LLM {
65
56
  apiKey: opts.apiKey
66
57
  });
67
58
  }
59
+ label() {
60
+ return "openai.LLM";
61
+ }
62
+ get model() {
63
+ return this.#opts.model;
64
+ }
68
65
  /**
69
66
  * Create a new instance of OpenAI LLM with Azure.
70
67
  *
@@ -289,80 +286,142 @@ class LLM extends import_agents.llm.LLM {
289
286
  }
290
287
  chat({
291
288
  chatCtx,
292
- fncCtx,
293
- temperature,
294
- n,
295
- parallelToolCalls
289
+ toolCtx,
290
+ connOptions = import_agents.DEFAULT_API_CONNECT_OPTIONS,
291
+ parallelToolCalls,
292
+ toolChoice,
293
+ extraKwargs
296
294
  }) {
297
- temperature = temperature || this.#opts.temperature;
298
- return new LLMStream(
299
- this,
300
- this.#client,
295
+ const extras = { ...extraKwargs };
296
+ if (this.#opts.metadata) {
297
+ extras.metadata = this.#opts.metadata;
298
+ }
299
+ if (this.#opts.user) {
300
+ extras.user = this.#opts.user;
301
+ }
302
+ if (this.#opts.maxCompletionTokens) {
303
+ extras.max_completion_tokens = this.#opts.maxCompletionTokens;
304
+ }
305
+ if (this.#opts.temperature) {
306
+ extras.temperature = this.#opts.temperature;
307
+ }
308
+ if (this.#opts.serviceTier) {
309
+ extras.service_tier = this.#opts.serviceTier;
310
+ }
311
+ if (this.#opts.store !== void 0) {
312
+ extras.store = this.#opts.store;
313
+ }
314
+ parallelToolCalls = parallelToolCalls !== void 0 ? parallelToolCalls : this.#opts.parallelToolCalls;
315
+ if (toolCtx && Object.keys(toolCtx).length > 0 && parallelToolCalls !== void 0) {
316
+ extras.parallel_tool_calls = parallelToolCalls;
317
+ }
318
+ toolChoice = toolChoice !== void 0 ? toolChoice : this.#opts.toolChoice;
319
+ if (toolChoice) {
320
+ extras.tool_choice = toolChoice;
321
+ }
322
+ return new LLMStream(this, {
323
+ model: this.#opts.model,
324
+ providerFmt: this.#providerFmt,
325
+ client: this.#client,
301
326
  chatCtx,
302
- fncCtx,
303
- this.#opts,
304
- parallelToolCalls,
305
- temperature,
306
- n
307
- );
327
+ toolCtx,
328
+ connOptions,
329
+ extraKwargs: extras
330
+ });
308
331
  }
309
332
  }
310
333
  class LLMStream extends import_agents.llm.LLMStream {
311
334
  #toolCallId;
312
335
  #fncName;
313
336
  #fncRawArguments;
337
+ #toolIndex;
314
338
  #client;
315
- #logger = (0, import_agents.log)();
316
- #id = (0, import_node_crypto.randomUUID)();
317
- label = "openai.LLMStream";
318
- constructor(llm2, client, chatCtx, fncCtx, opts, parallelToolCalls, temperature, n) {
319
- super(llm2, chatCtx, fncCtx);
339
+ #providerFmt;
340
+ #extraKwargs;
341
+ model;
342
+ constructor(llm2, {
343
+ model,
344
+ providerFmt,
345
+ client,
346
+ chatCtx,
347
+ toolCtx,
348
+ connOptions,
349
+ extraKwargs
350
+ }) {
351
+ super(llm2, { chatCtx, toolCtx, connOptions });
320
352
  this.#client = client;
321
- this.#run(opts, n, parallelToolCalls, temperature);
353
+ this.#providerFmt = providerFmt;
354
+ this.#extraKwargs = extraKwargs;
355
+ this.model = model;
322
356
  }
323
- async #run(opts, n, parallelToolCalls, temperature) {
324
- const tools = this.fncCtx ? Object.entries(this.fncCtx).map(([name, func]) => ({
325
- type: "function",
326
- function: {
327
- name,
328
- description: func.description,
329
- // don't format parameters if they are raw openai params
330
- parameters: func.parameters.type == "object" ? func.parameters : import_agents.llm.oaiParams(func.parameters)
331
- }
332
- })) : void 0;
357
+ async run() {
358
+ var _a;
359
+ let retryable = true;
333
360
  try {
361
+ const messages = await this.chatCtx.toProviderFormat(
362
+ this.#providerFmt
363
+ );
364
+ const tools = this.toolCtx ? Object.entries(this.toolCtx).map(([name, func]) => ({
365
+ type: "function",
366
+ function: {
367
+ name,
368
+ description: func.description,
369
+ parameters: import_agents.llm.toJsonSchema(
370
+ func.parameters
371
+ )
372
+ }
373
+ })) : void 0;
334
374
  const stream = await this.#client.chat.completions.create({
335
- model: opts.model,
336
- user: opts.user,
337
- n,
338
- messages: await Promise.all(
339
- this.chatCtx.messages.map(async (m) => await buildMessage(m, this.#id))
340
- ),
341
- temperature: temperature || opts.temperature,
342
- stream_options: { include_usage: true },
343
- stream: true,
375
+ model: this.model,
376
+ messages,
344
377
  tools,
345
- parallel_tool_calls: this.fncCtx && parallelToolCalls
378
+ stream: true,
379
+ stream_options: { include_usage: true },
380
+ ...this.#extraKwargs
346
381
  });
347
382
  for await (const chunk of stream) {
348
383
  for (const choice of chunk.choices) {
384
+ if (this.abortController.signal.aborted) {
385
+ break;
386
+ }
349
387
  const chatChunk = this.#parseChoice(chunk.id, choice);
350
388
  if (chatChunk) {
389
+ retryable = false;
351
390
  this.queue.put(chatChunk);
352
391
  }
353
- if (chunk.usage) {
354
- const usage = chunk.usage;
355
- this.queue.put({
356
- requestId: chunk.id,
357
- choices: [],
358
- usage: {
359
- completionTokens: usage.completion_tokens,
360
- promptTokens: usage.prompt_tokens,
361
- totalTokens: usage.total_tokens
362
- }
363
- });
364
- }
365
392
  }
393
+ if (chunk.usage) {
394
+ const usage = chunk.usage;
395
+ retryable = false;
396
+ this.queue.put({
397
+ id: chunk.id,
398
+ usage: {
399
+ completionTokens: usage.completion_tokens,
400
+ promptTokens: usage.prompt_tokens,
401
+ promptCachedTokens: ((_a = usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) || 0,
402
+ totalTokens: usage.total_tokens
403
+ }
404
+ });
405
+ }
406
+ }
407
+ } catch (error) {
408
+ if (error instanceof import_openai.OpenAI.APIConnectionTimeoutError) {
409
+ throw new import_agents.APITimeoutError({ options: { retryable } });
410
+ } else if (error instanceof import_openai.OpenAI.APIError) {
411
+ throw new import_agents.APIStatusError({
412
+ message: error.message,
413
+ options: {
414
+ statusCode: error.status,
415
+ body: error.error,
416
+ requestId: error.request_id,
417
+ retryable
418
+ }
419
+ });
420
+ } else {
421
+ throw new import_agents.APIConnectionError({
422
+ message: (0, import_agents.toError)(error).message,
423
+ options: { retryable }
424
+ });
366
425
  }
367
426
  } finally {
368
427
  this.queue.close();
@@ -370,163 +429,63 @@ class LLMStream extends import_agents.llm.LLMStream {
370
429
  }
371
430
  #parseChoice(id, choice) {
372
431
  const delta = choice.delta;
432
+ if (delta === void 0) return void 0;
373
433
  if (delta.tool_calls) {
374
434
  for (const tool of delta.tool_calls) {
375
435
  if (!tool.function) {
376
436
  continue;
377
437
  }
378
438
  let callChunk;
379
- if (this.#toolCallId && tool.id && tool.id !== this.#toolCallId) {
380
- callChunk = this.#tryBuildFunction(id, choice);
439
+ if (this.#toolCallId && tool.id && tool.index !== this.#toolIndex) {
440
+ callChunk = this.#createRunningToolCallChunk(id, delta);
441
+ this.#toolCallId = this.#fncName = this.#fncRawArguments = void 0;
381
442
  }
382
443
  if (tool.function.name) {
444
+ this.#toolIndex = tool.index;
383
445
  this.#toolCallId = tool.id;
384
446
  this.#fncName = tool.function.name;
385
447
  this.#fncRawArguments = tool.function.arguments || "";
386
448
  } else if (tool.function.arguments) {
387
- this.#fncRawArguments += tool.function.arguments;
449
+ this.#fncRawArguments = (this.#fncRawArguments || "") + tool.function.arguments;
388
450
  }
389
451
  if (callChunk) {
390
452
  return callChunk;
391
453
  }
392
454
  }
393
455
  }
394
- if (choice.finish_reason && ["tool_calls", "stop"].includes(choice.finish_reason) && this.#toolCallId) {
395
- return this.#tryBuildFunction(id, choice);
396
- }
397
- return {
398
- requestId: id,
399
- choices: [
400
- {
401
- delta: { content: delta.content || void 0, role: import_agents.llm.ChatRole.ASSISTANT },
402
- index: choice.index
403
- }
404
- ]
405
- };
406
- }
407
- #tryBuildFunction(id, choice) {
408
- if (!this.fncCtx) {
409
- this.#logger.warn("oai stream tried to run function without function context");
410
- return void 0;
411
- }
412
- if (!this.#toolCallId) {
413
- this.#logger.warn("oai stream tried to run function but toolCallId is not set");
414
- return void 0;
456
+ if (choice.finish_reason && ["tool_calls", "stop"].includes(choice.finish_reason) && this.#toolCallId !== void 0) {
457
+ const callChunk = this.#createRunningToolCallChunk(id, delta);
458
+ this.#toolCallId = this.#fncName = this.#fncRawArguments = void 0;
459
+ return callChunk;
415
460
  }
416
- if (!this.#fncRawArguments || !this.#fncName) {
417
- this.#logger.warn("oai stream tried to run function but rawArguments or fncName are not set");
461
+ if (!delta.content) {
418
462
  return void 0;
419
463
  }
420
- const functionInfo = import_agents.llm.oaiBuildFunctionInfo(
421
- this.fncCtx,
422
- this.#toolCallId,
423
- this.#fncName,
424
- this.#fncRawArguments
425
- );
426
- this.#toolCallId = this.#fncName = this.#fncRawArguments = void 0;
427
- this._functionCalls.push(functionInfo);
428
464
  return {
429
- requestId: id,
430
- choices: [
431
- {
432
- delta: {
433
- content: choice.delta.content || void 0,
434
- role: import_agents.llm.ChatRole.ASSISTANT,
435
- toolCalls: this._functionCalls
436
- },
437
- index: choice.index
438
- }
439
- ]
440
- };
441
- }
442
- }
443
- const buildMessage = async (msg, cacheKey) => {
444
- const oaiMsg = {};
445
- switch (msg.role) {
446
- case import_agents.llm.ChatRole.SYSTEM:
447
- oaiMsg.role = "system";
448
- break;
449
- case import_agents.llm.ChatRole.USER:
450
- oaiMsg.role = "user";
451
- break;
452
- case import_agents.llm.ChatRole.ASSISTANT:
453
- oaiMsg.role = "assistant";
454
- break;
455
- case import_agents.llm.ChatRole.TOOL:
456
- oaiMsg.role = "tool";
457
- if (oaiMsg.role === "tool") {
458
- oaiMsg.tool_call_id = msg.toolCallId;
459
- }
460
- break;
461
- }
462
- if (msg.role === import_agents.llm.ChatRole.TOOL) {
463
- try {
464
- const serializedContent = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
465
- oaiMsg.content = serializedContent;
466
- } catch (e) {
467
- throw Error(`Tool call output is not JSON serializable: ${e}`);
468
- }
469
- } else {
470
- if (typeof msg.content === "string") {
471
- oaiMsg.content = msg.content;
472
- } else if (Array.isArray(msg.content)) {
473
- oaiMsg.content = await Promise.all(
474
- msg.content.map(async (c) => {
475
- if (typeof c === "string") {
476
- return { type: "text", text: c };
477
- } else if (
478
- // typescript type guard for determining ChatAudio vs ChatImage
479
- ((c2) => {
480
- return c2.image !== void 0;
481
- })(c)
482
- ) {
483
- return await buildImageContent(c, cacheKey);
484
- } else {
485
- throw new Error("ChatAudio is not supported");
486
- }
487
- })
488
- );
489
- } else if (msg.content === void 0) {
490
- oaiMsg.content = "";
491
- }
492
- }
493
- if (msg.toolCalls && oaiMsg.role === "assistant") {
494
- oaiMsg.tool_calls = Object.entries(msg.toolCalls).map(([name, func]) => ({
495
- id: func.toolCallId,
496
- type: "function",
497
- function: {
498
- name,
499
- arguments: func.rawParams
500
- }
501
- }));
502
- }
503
- return oaiMsg;
504
- };
505
- const buildImageContent = async (image, cacheKey) => {
506
- if (typeof image.image === "string") {
507
- return {
508
- type: "image_url",
509
- image_url: {
510
- url: image.image,
511
- detail: "auto"
465
+ id,
466
+ delta: {
467
+ role: "assistant",
468
+ content: delta.content
512
469
  }
513
470
  };
514
- } else {
515
- if (!image.cache[cacheKey]) {
516
- let encoded = (0, import_sharp.default)(image.image.data);
517
- if (image.inferenceHeight && image.inferenceHeight) {
518
- encoded = encoded.resize(image.inferenceWidth, image.inferenceHeight);
519
- }
520
- image.cache[cacheKey] = await encoded.jpeg().toBuffer().then((buffer) => buffer.toString("utf-8"));
521
- }
471
+ }
472
+ #createRunningToolCallChunk(id, delta) {
522
473
  return {
523
- type: "image_url",
524
- image_url: {
525
- url: `data:image/jpeg;base64,${image.cache[cacheKey]}`
474
+ id,
475
+ delta: {
476
+ role: "assistant",
477
+ content: delta.content || void 0,
478
+ toolCalls: [
479
+ import_agents.llm.FunctionCall.create({
480
+ callId: this.#toolCallId,
481
+ name: this.#fncName || "",
482
+ args: this.#fncRawArguments || ""
483
+ })
484
+ ]
526
485
  }
527
486
  };
528
487
  }
529
- };
488
+ }
530
489
  // Annotate the CommonJS export names for ESM import in node:
531
490
  0 && (module.exports = {
532
491
  LLM,