@livekit/agents-plugin-openai 1.7.1 → 1.8.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 (91) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/realtime/gpt_live_model.cjs +883 -0
  4. package/dist/realtime/gpt_live_model.cjs.map +1 -0
  5. package/dist/realtime/gpt_live_model.d.cts +183 -0
  6. package/dist/realtime/gpt_live_model.d.ts +183 -0
  7. package/dist/realtime/gpt_live_model.d.ts.map +1 -0
  8. package/dist/realtime/gpt_live_model.js +859 -0
  9. package/dist/realtime/gpt_live_model.js.map +1 -0
  10. package/dist/realtime/gpt_live_model.test.cjs +1397 -0
  11. package/dist/realtime/gpt_live_model.test.cjs.map +1 -0
  12. package/dist/realtime/gpt_live_model.test.d.cts +2 -0
  13. package/dist/realtime/gpt_live_model.test.d.ts +2 -0
  14. package/dist/realtime/gpt_live_model.test.d.ts.map +1 -0
  15. package/dist/realtime/gpt_live_model.test.js +1398 -0
  16. package/dist/realtime/gpt_live_model.test.js.map +1 -0
  17. package/dist/realtime/gpt_live_types.cjs +17 -0
  18. package/dist/realtime/gpt_live_types.cjs.map +1 -0
  19. package/dist/realtime/gpt_live_types.d.cts +170 -0
  20. package/dist/realtime/gpt_live_types.d.ts +170 -0
  21. package/dist/realtime/gpt_live_types.d.ts.map +1 -0
  22. package/dist/realtime/gpt_live_types.js +1 -0
  23. package/dist/realtime/gpt_live_types.js.map +1 -0
  24. package/dist/realtime/index.cjs +22 -1
  25. package/dist/realtime/index.cjs.map +1 -1
  26. package/dist/realtime/index.d.cts +2 -0
  27. package/dist/realtime/index.d.ts +2 -0
  28. package/dist/realtime/index.d.ts.map +1 -1
  29. package/dist/realtime/index.js +5 -0
  30. package/dist/realtime/index.js.map +1 -1
  31. package/dist/realtime/realtime_model.cjs +4 -1
  32. package/dist/realtime/realtime_model.cjs.map +1 -1
  33. package/dist/realtime/realtime_model.d.ts.map +1 -1
  34. package/dist/realtime/realtime_model.js +4 -1
  35. package/dist/realtime/realtime_model.js.map +1 -1
  36. package/dist/realtime/realtime_model.test.cjs +29 -0
  37. package/dist/realtime/realtime_model.test.cjs.map +1 -1
  38. package/dist/realtime/realtime_model.test.js +29 -0
  39. package/dist/realtime/realtime_model.test.js.map +1 -1
  40. package/dist/responses/llm.cjs +10 -0
  41. package/dist/responses/llm.cjs.map +1 -1
  42. package/dist/responses/llm.d.ts.map +1 -1
  43. package/dist/responses/llm.js +10 -0
  44. package/dist/responses/llm.js.map +1 -1
  45. package/dist/responses/llm.test.cjs +51 -0
  46. package/dist/responses/llm.test.cjs.map +1 -1
  47. package/dist/responses/llm.test.js +52 -1
  48. package/dist/responses/llm.test.js.map +1 -1
  49. package/dist/tool_utils.cjs +12 -8
  50. package/dist/tool_utils.cjs.map +1 -1
  51. package/dist/tool_utils.d.cts +1 -0
  52. package/dist/tool_utils.d.ts +1 -0
  53. package/dist/tool_utils.d.ts.map +1 -1
  54. package/dist/tool_utils.js +11 -8
  55. package/dist/tool_utils.js.map +1 -1
  56. package/dist/tool_utils.test.cjs +27 -0
  57. package/dist/tool_utils.test.cjs.map +1 -1
  58. package/dist/tool_utils.test.js +27 -0
  59. package/dist/tool_utils.test.js.map +1 -1
  60. package/dist/ws/llm.cjs +25 -7
  61. package/dist/ws/llm.cjs.map +1 -1
  62. package/dist/ws/llm.d.cts +2 -2
  63. package/dist/ws/llm.d.ts +2 -2
  64. package/dist/ws/llm.d.ts.map +1 -1
  65. package/dist/ws/llm.js +25 -7
  66. package/dist/ws/llm.js.map +1 -1
  67. package/dist/ws/llm.test.cjs +117 -0
  68. package/dist/ws/llm.test.cjs.map +1 -1
  69. package/dist/ws/llm.test.js +126 -3
  70. package/dist/ws/llm.test.js.map +1 -1
  71. package/dist/ws/types.cjs +12 -0
  72. package/dist/ws/types.cjs.map +1 -1
  73. package/dist/ws/types.d.cts +18 -0
  74. package/dist/ws/types.d.ts +18 -0
  75. package/dist/ws/types.d.ts.map +1 -1
  76. package/dist/ws/types.js +11 -0
  77. package/dist/ws/types.js.map +1 -1
  78. package/package.json +5 -5
  79. package/src/realtime/gpt_live_model.test.ts +1458 -0
  80. package/src/realtime/gpt_live_model.ts +1032 -0
  81. package/src/realtime/gpt_live_types.ts +140 -0
  82. package/src/realtime/index.ts +2 -0
  83. package/src/realtime/realtime_model.test.ts +32 -0
  84. package/src/realtime/realtime_model.ts +4 -1
  85. package/src/responses/llm.test.ts +55 -1
  86. package/src/responses/llm.ts +10 -0
  87. package/src/tool_utils.test.ts +30 -0
  88. package/src/tool_utils.ts +21 -18
  89. package/src/ws/llm.test.ts +141 -5
  90. package/src/ws/llm.ts +29 -8
  91. package/src/ws/types.ts +17 -0
@@ -84,6 +84,57 @@ async function attemptsUntilStall(events, maxRetry) {
84
84
  (0, import_vitest.expect)(await attemptsUntilStall([RESPONSE_CREATED, TEXT_DELTA], 2)).toBe(1);
85
85
  });
86
86
  });
87
+ (0, import_vitest.describe)("OpenAI Responses HTTP incomplete handling", () => {
88
+ import_vitest.it.each([
89
+ ["max_output_tokens", "max_output_tokens"],
90
+ [void 0, "reason unavailable"]
91
+ ])("surfaces %s as non-retryable", async (reason, expectedMessage) => {
92
+ let attempts = 0;
93
+ const incomplete = {
94
+ type: "response.incomplete",
95
+ response: {
96
+ id: "resp_1",
97
+ ...reason === void 0 ? {} : { incomplete_details: { reason } }
98
+ }
99
+ };
100
+ const client = {
101
+ responses: {
102
+ create: async () => {
103
+ attempts++;
104
+ return {
105
+ async *[Symbol.asyncIterator]() {
106
+ yield RESPONSE_CREATED;
107
+ yield incomplete;
108
+ }
109
+ };
110
+ }
111
+ }
112
+ };
113
+ const model = new import_llm.LLM({
114
+ model: "gpt-4.1",
115
+ apiKey: "test-key",
116
+ useWebSocket: false,
117
+ client
118
+ });
119
+ const errorEvent = new Promise((resolve) => {
120
+ model.once("error", (event) => resolve(event.error));
121
+ });
122
+ const chatCtx = import_agents.ChatContext.empty();
123
+ chatCtx.addMessage({ role: "user", content: "hi" });
124
+ const stream = model.chat({
125
+ chatCtx,
126
+ connOptions: { maxRetry: 2, retryIntervalMs: 0, timeoutMs: 5e3 }
127
+ });
128
+ for await (const _chunk of stream) void _chunk;
129
+ const error = await errorEvent;
130
+ (0, import_vitest.expect)(error).toBeInstanceOf(import_agents.APIStatusError);
131
+ (0, import_vitest.expect)(error.message).toContain(expectedMessage);
132
+ (0, import_vitest.expect)(error.statusCode).toBe(-1);
133
+ (0, import_vitest.expect)(error.retryable).toBe(false);
134
+ (0, import_vitest.expect)(attempts).toBe(1);
135
+ await model.aclose();
136
+ });
137
+ });
87
138
  if (hasOpenAIApiKey) {
88
139
  (0, import_vitest.describe)("OpenAI Responses", async () => {
89
140
  await (0, import_agents_plugins_test.llm)(
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/responses/llm.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { ChatContext, initializeLogger } from '@livekit/agents';\nimport { llm, llmStrict } from '@livekit/agents-plugins-test';\nimport type OpenAI from 'openai';\nimport { describe, expect, it } from 'vitest';\nimport { wsServerEventSchema } from '../ws/types.js';\nimport { LLM } from './llm.js';\n\ninitializeLogger({ level: 'silent', pretty: false });\n\nconst hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);\n\ndescribe('OpenAI Responses WebSocket', () => {\n it('preserves top-level code and param on error frames', () => {\n const frame = {\n type: 'error',\n message:\n \"Invalid type for 'reasoning.mode': expected one of 'standard' or 'pro', but got null instead.\",\n code: 'invalid_type',\n param: 'reasoning.mode',\n status: 400,\n };\n\n const parsed = wsServerEventSchema.parse(frame);\n\n expect(parsed.type).toBe('error');\n if (parsed.type !== 'error') throw new Error('expected error event');\n expect(parsed.message).toBe(frame.message);\n expect(parsed.param).toBe('reasoning.mode');\n });\n});\n\ntype ResponsesEvent = Record<string, unknown>;\n\n// opens every stream, on every provider\nconst RESPONSE_CREATED: ResponsesEvent = {\n type: 'response.created',\n response: { id: 'resp_1' },\n};\n\n// a reasoning phase marker: a message item with no text of its own\nconst PHASE_METADATA: ResponsesEvent = {\n type: 'response.output_item.done',\n item: { type: 'message', phase: 'thinking' },\n};\n\nconst TEXT_DELTA: ResponsesEvent = {\n type: 'response.output_text.delta',\n delta: 'hello',\n};\n\n/**\n * Replays the given events, then dies the way a provider going quiet does.\n * Returns how many times the request was attempted.\n */\nasync function attemptsUntilStall(events: ResponsesEvent[], maxRetry: number): Promise<number> {\n let attempts = 0;\n\n const client = {\n responses: {\n create: async () => {\n attempts++;\n return {\n async *[Symbol.asyncIterator]() {\n for (const event of events) {\n yield event;\n }\n throw new Error('stalled mid-stream');\n },\n };\n },\n },\n };\n\n const model = new LLM({\n model: 'gpt-4.1',\n apiKey: 'test-key',\n useWebSocket: false,\n client: client as unknown as OpenAI,\n });\n // the stream emits 'error' on every failed attempt; without a listener the\n // EventEmitter turns it into an unhandled error and fails the run\n model.on('error', () => {});\n\n const chatCtx = ChatContext.empty();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n\n try {\n const stream = model.chat({\n chatCtx,\n connOptions: { maxRetry, retryIntervalMs: 0, timeoutMs: 5000 },\n });\n for await (const _chunk of stream) {\n void _chunk;\n }\n } catch {\n // the stall surfaces through the 'error' event; the iterator just ends\n }\n\n return attempts;\n}\n\ndescribe('OpenAI Responses HTTP retry eligibility', () => {\n it('retries a stall that follows the stream-opening event alone', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED], 2)).toBe(3);\n });\n\n it('retries a stall that follows a phase marker', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED, PHASE_METADATA], 2)).toBe(3);\n });\n\n it('does not retry once generated text has reached the caller', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED, TEXT_DELTA], 2)).toBe(1);\n });\n});\n\nif (hasOpenAIApiKey) {\n describe('OpenAI Responses', async () => {\n await llm(\n new LLM({\n temperature: 0,\n strictToolSchema: false,\n }),\n true,\n );\n });\n} else {\n describe('OpenAI Responses', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n\nif (hasOpenAIApiKey) {\n describe('OpenAI Responses strict tool schema', async () => {\n await llmStrict(\n new LLM({\n temperature: 0,\n strictToolSchema: true,\n }),\n );\n });\n} else {\n describe('OpenAI Responses strict tool schema', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n"],"mappings":";AAGA,oBAA8C;AAC9C,iCAA+B;AAE/B,oBAAqC;AACrC,mBAAoC;AACpC,iBAAoB;AAAA,IAEpB,gCAAiB,EAAE,OAAO,UAAU,QAAQ,MAAM,CAAC;AAEnD,MAAM,kBAAkB,QAAQ,QAAQ,IAAI,cAAc;AAAA,IAE1D,wBAAS,8BAA8B,MAAM;AAC3C,wBAAG,sDAAsD,MAAM;AAC7D,UAAM,QAAQ;AAAA,MACZ,MAAM;AAAA,MACN,SACE;AAAA,MACF,MAAM;AAAA,MACN,OAAO;AAAA,MACP,QAAQ;AAAA,IACV;AAEA,UAAM,SAAS,iCAAoB,MAAM,KAAK;AAE9C,8BAAO,OAAO,IAAI,EAAE,KAAK,OAAO;AAChC,QAAI,OAAO,SAAS,QAAS,OAAM,IAAI,MAAM,sBAAsB;AACnE,8BAAO,OAAO,OAAO,EAAE,KAAK,MAAM,OAAO;AACzC,8BAAO,OAAO,KAAK,EAAE,KAAK,gBAAgB;AAAA,EAC5C,CAAC;AACH,CAAC;AAKD,MAAM,mBAAmC;AAAA,EACvC,MAAM;AAAA,EACN,UAAU,EAAE,IAAI,SAAS;AAC3B;AAGA,MAAM,iBAAiC;AAAA,EACrC,MAAM;AAAA,EACN,MAAM,EAAE,MAAM,WAAW,OAAO,WAAW;AAC7C;AAEA,MAAM,aAA6B;AAAA,EACjC,MAAM;AAAA,EACN,OAAO;AACT;AAMA,eAAe,mBAAmB,QAA0B,UAAmC;AAC7F,MAAI,WAAW;AAEf,QAAM,SAAS;AAAA,IACb,WAAW;A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AAkB;AAAA,MACpB,CAAC;AAAA,MACD;AAAA,IACF;AAAA,EACF,CAAC;AACH,OAAO;AACL,8BAAS,oBAAoB,MAAM;AACjC,qBAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;AAEA,IAAI,iBAAiB;AACnB,8BAAS,uCAAuC,YAAY;AAC1D,cAAM;AAAA,MACJ,IAAI,eAAI;AAAA,QACN,aAAa;AAAA,QACb,kBAAkB;AAAA,MACpB,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH,OAAO;AACL,8BAAS,uCAAuC,MAAM;AACpD,qBAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/responses/llm.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { APIStatusError, ChatContext, initializeLogger } from '@livekit/agents';\nimport { llm, llmStrict } from '@livekit/agents-plugins-test';\nimport type OpenAI from 'openai';\nimport { describe, expect, it } from 'vitest';\nimport { wsServerEventSchema } from '../ws/types.js';\nimport { LLM } from './llm.js';\n\ninitializeLogger({ level: 'silent', pretty: false });\n\nconst hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);\n\ndescribe('OpenAI Responses WebSocket', () => {\n it('preserves top-level code and param on error frames', () => {\n const frame = {\n type: 'error',\n message:\n \"Invalid type for 'reasoning.mode': expected one of 'standard' or 'pro', but got null instead.\",\n code: 'invalid_type',\n param: 'reasoning.mode',\n status: 400,\n };\n\n const parsed = wsServerEventSchema.parse(frame);\n\n expect(parsed.type).toBe('error');\n if (parsed.type !== 'error') throw new Error('expected error event');\n expect(parsed.message).toBe(frame.message);\n expect(parsed.param).toBe('reasoning.mode');\n });\n});\n\ntype ResponsesEvent = Record<string, unknown>;\n\n// opens every stream, on every provider\nconst RESPONSE_CREATED: ResponsesEvent = {\n type: 'response.created',\n response: { id: 'resp_1' },\n};\n\n// a reasoning phase marker: a message item with no text of its own\nconst PHASE_METADATA: ResponsesEvent = {\n type: 'response.output_item.done',\n item: { type: 'message', phase: 'thinking' },\n};\n\nconst TEXT_DELTA: ResponsesEvent = {\n type: 'response.output_text.delta',\n delta: 'hello',\n};\n\n/**\n * Replays the given events, then dies the way a provider going quiet does.\n * Returns how many times the request was attempted.\n */\nasync function attemptsUntilStall(events: ResponsesEvent[], maxRetry: number): Promise<number> {\n let attempts = 0;\n\n const client = {\n responses: {\n create: async () => {\n attempts++;\n return {\n async *[Symbol.asyncIterator]() {\n for (const event of events) {\n yield event;\n }\n throw new Error('stalled mid-stream');\n },\n };\n },\n },\n };\n\n const model = new LLM({\n model: 'gpt-4.1',\n apiKey: 'test-key',\n useWebSocket: false,\n client: client as unknown as OpenAI,\n });\n // the stream emits 'error' on every failed attempt; without a listener the\n // EventEmitter turns it into an unhandled error and fails the run\n model.on('error', () => {});\n\n const chatCtx = ChatContext.empty();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n\n try {\n const stream = model.chat({\n chatCtx,\n connOptions: { maxRetry, retryIntervalMs: 0, timeoutMs: 5000 },\n });\n for await (const _chunk of stream) {\n void _chunk;\n }\n } catch {\n // the stall surfaces through the 'error' event; the iterator just ends\n }\n\n return attempts;\n}\n\ndescribe('OpenAI Responses HTTP retry eligibility', () => {\n it('retries a stall that follows the stream-opening event alone', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED], 2)).toBe(3);\n });\n\n it('retries a stall that follows a phase marker', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED, PHASE_METADATA], 2)).toBe(3);\n });\n\n it('does not retry once generated text has reached the caller', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED, TEXT_DELTA], 2)).toBe(1);\n });\n});\n\ndescribe('OpenAI Responses HTTP incomplete handling', () => {\n it.each([\n ['max_output_tokens', 'max_output_tokens'],\n [undefined, 'reason unavailable'],\n ] as const)('surfaces %s as non-retryable', async (reason, expectedMessage) => {\n let attempts = 0;\n const incomplete = {\n type: 'response.incomplete',\n response: {\n id: 'resp_1',\n ...(reason === undefined ? {} : { incomplete_details: { reason } }),\n },\n };\n const client = {\n responses: {\n create: async () => {\n attempts++;\n return {\n async *[Symbol.asyncIterator]() {\n yield RESPONSE_CREATED;\n yield incomplete;\n },\n };\n },\n },\n };\n const model = new LLM({\n model: 'gpt-4.1',\n apiKey: 'test-key',\n useWebSocket: false,\n client: client as unknown as OpenAI,\n });\n const errorEvent = new Promise<Error>((resolve) => {\n model.once('error', (event) => resolve(event.error));\n });\n const chatCtx = ChatContext.empty();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n\n const stream = model.chat({\n chatCtx,\n connOptions: { maxRetry: 2, retryIntervalMs: 0, timeoutMs: 5000 },\n });\n for await (const _chunk of stream) void _chunk;\n const error = await errorEvent;\n\n expect(error).toBeInstanceOf(APIStatusError);\n expect(error.message).toContain(expectedMessage);\n expect((error as APIStatusError).statusCode).toBe(-1);\n expect((error as APIStatusError).retryable).toBe(false);\n expect(attempts).toBe(1);\n await model.aclose();\n });\n});\n\nif (hasOpenAIApiKey) {\n describe('OpenAI Responses', async () => {\n await llm(\n new LLM({\n temperature: 0,\n strictToolSchema: false,\n }),\n true,\n );\n });\n} else {\n describe('OpenAI Responses', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n\nif (hasOpenAIApiKey) {\n describe('OpenAI Responses strict tool schema', async () => {\n await llmStrict(\n new LLM({\n temperature: 0,\n strictToolSchema: true,\n }),\n );\n });\n} else {\n describe('OpenAI Responses strict tool schema', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n"],"mappings":";AAGA,oBAA8D;AAC9D,iCAA+B;AAE/B,oBAAqC;AACrC,mBAAoC;AACpC,iBAAoB;AAAA,IAEpB,gCAAiB,EAAE,OAAO,UAAU,QAAQ,MAAM,CAAC;AAEnD,MAAM,kBAAkB,QAAQ,QAAQ,IAAI,cAA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M;AACpD,qBAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;","names":[]}
@@ -1,4 +1,4 @@
1
- import { ChatContext, initializeLogger } from "@livekit/agents";
1
+ import { APIStatusError, ChatContext, initializeLogger } from "@livekit/agents";
2
2
  import { llm, llmStrict } from "@livekit/agents-plugins-test";
3
3
  import { describe, expect, it } from "vitest";
4
4
  import { wsServerEventSchema } from "../ws/types.js";
@@ -83,6 +83,57 @@ describe("OpenAI Responses HTTP retry eligibility", () => {
83
83
  expect(await attemptsUntilStall([RESPONSE_CREATED, TEXT_DELTA], 2)).toBe(1);
84
84
  });
85
85
  });
86
+ describe("OpenAI Responses HTTP incomplete handling", () => {
87
+ it.each([
88
+ ["max_output_tokens", "max_output_tokens"],
89
+ [void 0, "reason unavailable"]
90
+ ])("surfaces %s as non-retryable", async (reason, expectedMessage) => {
91
+ let attempts = 0;
92
+ const incomplete = {
93
+ type: "response.incomplete",
94
+ response: {
95
+ id: "resp_1",
96
+ ...reason === void 0 ? {} : { incomplete_details: { reason } }
97
+ }
98
+ };
99
+ const client = {
100
+ responses: {
101
+ create: async () => {
102
+ attempts++;
103
+ return {
104
+ async *[Symbol.asyncIterator]() {
105
+ yield RESPONSE_CREATED;
106
+ yield incomplete;
107
+ }
108
+ };
109
+ }
110
+ }
111
+ };
112
+ const model = new LLM({
113
+ model: "gpt-4.1",
114
+ apiKey: "test-key",
115
+ useWebSocket: false,
116
+ client
117
+ });
118
+ const errorEvent = new Promise((resolve) => {
119
+ model.once("error", (event) => resolve(event.error));
120
+ });
121
+ const chatCtx = ChatContext.empty();
122
+ chatCtx.addMessage({ role: "user", content: "hi" });
123
+ const stream = model.chat({
124
+ chatCtx,
125
+ connOptions: { maxRetry: 2, retryIntervalMs: 0, timeoutMs: 5e3 }
126
+ });
127
+ for await (const _chunk of stream) void _chunk;
128
+ const error = await errorEvent;
129
+ expect(error).toBeInstanceOf(APIStatusError);
130
+ expect(error.message).toContain(expectedMessage);
131
+ expect(error.statusCode).toBe(-1);
132
+ expect(error.retryable).toBe(false);
133
+ expect(attempts).toBe(1);
134
+ await model.aclose();
135
+ });
136
+ });
86
137
  if (hasOpenAIApiKey) {
87
138
  describe("OpenAI Responses", async () => {
88
139
  await llm(
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/responses/llm.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { ChatContext, initializeLogger } from '@livekit/agents';\nimport { llm, llmStrict } from '@livekit/agents-plugins-test';\nimport type OpenAI from 'openai';\nimport { describe, expect, it } from 'vitest';\nimport { wsServerEventSchema } from '../ws/types.js';\nimport { LLM } from './llm.js';\n\ninitializeLogger({ level: 'silent', pretty: false });\n\nconst hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);\n\ndescribe('OpenAI Responses WebSocket', () => {\n it('preserves top-level code and param on error frames', () => {\n const frame = {\n type: 'error',\n message:\n \"Invalid type for 'reasoning.mode': expected one of 'standard' or 'pro', but got null instead.\",\n code: 'invalid_type',\n param: 'reasoning.mode',\n status: 400,\n };\n\n const parsed = wsServerEventSchema.parse(frame);\n\n expect(parsed.type).toBe('error');\n if (parsed.type !== 'error') throw new Error('expected error event');\n expect(parsed.message).toBe(frame.message);\n expect(parsed.param).toBe('reasoning.mode');\n });\n});\n\ntype ResponsesEvent = Record<string, unknown>;\n\n// opens every stream, on every provider\nconst RESPONSE_CREATED: ResponsesEvent = {\n type: 'response.created',\n response: { id: 'resp_1' },\n};\n\n// a reasoning phase marker: a message item with no text of its own\nconst PHASE_METADATA: ResponsesEvent = {\n type: 'response.output_item.done',\n item: { type: 'message', phase: 'thinking' },\n};\n\nconst TEXT_DELTA: ResponsesEvent = {\n type: 'response.output_text.delta',\n delta: 'hello',\n};\n\n/**\n * Replays the given events, then dies the way a provider going quiet does.\n * Returns how many times the request was attempted.\n */\nasync function attemptsUntilStall(events: ResponsesEvent[], maxRetry: number): Promise<number> {\n let attempts = 0;\n\n const client = {\n responses: {\n create: async () => {\n attempts++;\n return {\n async *[Symbol.asyncIterator]() {\n for (const event of events) {\n yield event;\n }\n throw new Error('stalled mid-stream');\n },\n };\n },\n },\n };\n\n const model = new LLM({\n model: 'gpt-4.1',\n apiKey: 'test-key',\n useWebSocket: false,\n client: client as unknown as OpenAI,\n });\n // the stream emits 'error' on every failed attempt; without a listener the\n // EventEmitter turns it into an unhandled error and fails the run\n model.on('error', () => {});\n\n const chatCtx = ChatContext.empty();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n\n try {\n const stream = model.chat({\n chatCtx,\n connOptions: { maxRetry, retryIntervalMs: 0, timeoutMs: 5000 },\n });\n for await (const _chunk of stream) {\n void _chunk;\n }\n } catch {\n // the stall surfaces through the 'error' event; the iterator just ends\n }\n\n return attempts;\n}\n\ndescribe('OpenAI Responses HTTP retry eligibility', () => {\n it('retries a stall that follows the stream-opening event alone', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED], 2)).toBe(3);\n });\n\n it('retries a stall that follows a phase marker', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED, PHASE_METADATA], 2)).toBe(3);\n });\n\n it('does not retry once generated text has reached the caller', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED, TEXT_DELTA], 2)).toBe(1);\n });\n});\n\nif (hasOpenAIApiKey) {\n describe('OpenAI Responses', async () => {\n await llm(\n new LLM({\n temperature: 0,\n strictToolSchema: false,\n }),\n true,\n );\n });\n} else {\n describe('OpenAI Responses', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n\nif (hasOpenAIApiKey) {\n describe('OpenAI Responses strict tool schema', async () => {\n await llmStrict(\n new LLM({\n temperature: 0,\n strictToolSchema: true,\n }),\n );\n });\n} else {\n describe('OpenAI Responses strict tool schema', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n"],"mappings":"AAGA,SAAS,aAAa,wBAAwB;AAC9C,SA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B,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH,OAAO;AACL,WAAS,uCAAuC,MAAM;AACpD,OAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/responses/llm.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { APIStatusError, ChatContext, initializeLogger } from '@livekit/agents';\nimport { llm, llmStrict } from '@livekit/agents-plugins-test';\nimport type OpenAI from 'openai';\nimport { describe, expect, it } from 'vitest';\nimport { wsServerEventSchema } from '../ws/types.js';\nimport { LLM } from './llm.js';\n\ninitializeLogger({ level: 'silent', pretty: false });\n\nconst hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);\n\ndescribe('OpenAI Responses WebSocket', () => {\n it('preserves top-level code and param on error frames', () => {\n const frame = {\n type: 'error',\n message:\n \"Invalid type for 'reasoning.mode': expected one of 'standard' or 'pro', but got null instead.\",\n code: 'invalid_type',\n param: 'reasoning.mode',\n status: 400,\n };\n\n const parsed = wsServerEventSchema.parse(frame);\n\n expect(parsed.type).toBe('error');\n if (parsed.type !== 'error') throw new Error('expected error event');\n expect(parsed.message).toBe(frame.message);\n expect(parsed.param).toBe('reasoning.mode');\n });\n});\n\ntype ResponsesEvent = Record<string, unknown>;\n\n// opens every stream, on every provider\nconst RESPONSE_CREATED: ResponsesEvent = {\n type: 'response.created',\n response: { id: 'resp_1' },\n};\n\n// a reasoning phase marker: a message item with no text of its own\nconst PHASE_METADATA: ResponsesEvent = {\n type: 'response.output_item.done',\n item: { type: 'message', phase: 'thinking' },\n};\n\nconst TEXT_DELTA: ResponsesEvent = {\n type: 'response.output_text.delta',\n delta: 'hello',\n};\n\n/**\n * Replays the given events, then dies the way a provider going quiet does.\n * Returns how many times the request was attempted.\n */\nasync function attemptsUntilStall(events: ResponsesEvent[], maxRetry: number): Promise<number> {\n let attempts = 0;\n\n const client = {\n responses: {\n create: async () => {\n attempts++;\n return {\n async *[Symbol.asyncIterator]() {\n for (const event of events) {\n yield event;\n }\n throw new Error('stalled mid-stream');\n },\n };\n },\n },\n };\n\n const model = new LLM({\n model: 'gpt-4.1',\n apiKey: 'test-key',\n useWebSocket: false,\n client: client as unknown as OpenAI,\n });\n // the stream emits 'error' on every failed attempt; without a listener the\n // EventEmitter turns it into an unhandled error and fails the run\n model.on('error', () => {});\n\n const chatCtx = ChatContext.empty();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n\n try {\n const stream = model.chat({\n chatCtx,\n connOptions: { maxRetry, retryIntervalMs: 0, timeoutMs: 5000 },\n });\n for await (const _chunk of stream) {\n void _chunk;\n }\n } catch {\n // the stall surfaces through the 'error' event; the iterator just ends\n }\n\n return attempts;\n}\n\ndescribe('OpenAI Responses HTTP retry eligibility', () => {\n it('retries a stall that follows the stream-opening event alone', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED], 2)).toBe(3);\n });\n\n it('retries a stall that follows a phase marker', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED, PHASE_METADATA], 2)).toBe(3);\n });\n\n it('does not retry once generated text has reached the caller', async () => {\n expect(await attemptsUntilStall([RESPONSE_CREATED, TEXT_DELTA], 2)).toBe(1);\n });\n});\n\ndescribe('OpenAI Responses HTTP incomplete handling', () => {\n it.each([\n ['max_output_tokens', 'max_output_tokens'],\n [undefined, 'reason unavailable'],\n ] as const)('surfaces %s as non-retryable', async (reason, expectedMessage) => {\n let attempts = 0;\n const incomplete = {\n type: 'response.incomplete',\n response: {\n id: 'resp_1',\n ...(reason === undefined ? {} : { incomplete_details: { reason } }),\n },\n };\n const client = {\n responses: {\n create: async () => {\n attempts++;\n return {\n async *[Symbol.asyncIterator]() {\n yield RESPONSE_CREATED;\n yield incomplete;\n },\n };\n },\n },\n };\n const model = new LLM({\n model: 'gpt-4.1',\n apiKey: 'test-key',\n useWebSocket: false,\n client: client as unknown as OpenAI,\n });\n const errorEvent = new Promise<Error>((resolve) => {\n model.once('error', (event) => resolve(event.error));\n });\n const chatCtx = ChatContext.empty();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n\n const stream = model.chat({\n chatCtx,\n connOptions: { maxRetry: 2, retryIntervalMs: 0, timeoutMs: 5000 },\n });\n for await (const _chunk of stream) void _chunk;\n const error = await errorEvent;\n\n expect(error).toBeInstanceOf(APIStatusError);\n expect(error.message).toContain(expectedMessage);\n expect((error as APIStatusError).statusCode).toBe(-1);\n expect((error as APIStatusError).retryable).toBe(false);\n expect(attempts).toBe(1);\n await model.aclose();\n });\n});\n\nif (hasOpenAIApiKey) {\n describe('OpenAI Responses', async () => {\n await llm(\n new LLM({\n temperature: 0,\n strictToolSchema: false,\n }),\n true,\n );\n });\n} else {\n describe('OpenAI Responses', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n\nif (hasOpenAIApiKey) {\n describe('OpenAI Responses strict tool schema', async () => {\n await llmStrict(\n new LLM({\n temperature: 0,\n strictToolSchema: true,\n }),\n );\n });\n} else {\n describe('OpenAI Responses strict tool schema', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n"],"mappings":"AAGA,SAAS,gBAAgB,aAAa,wBAAwB;AAC9D,SAAS,KAAK,iBAAiB;AAE/B,SAAS,UAAU,QAAQ,UAAU;AACrC,SAAS,2BAA2B;AACpC,SAAS,WAAW;AAEpB,iBAAiB,EAAE,OAAO,UAAU,QAAQ,MAAM,CAAC;AAEnD,MAAM,kBAAkB,QAAQ,QAAQ,IAAI,cAAc;AAE1D,SAAS,8BAA8B,MAAM;AAC3C,KAAG,sDAAsD,MAAM;AAC7D,UAAM,QAAQ;AAAA,MACZ,MAAM;AAAA,MACN,SACE;AAAA,MACF,MAAM;AAAA,MACN,OAAO;AAAA,MACP,QAAQ;AAAA,IACV;AAEA,UAAM,SAAS,oBAAoB,MAAM,KAAK;AAE9C,WAAO,OAAO,IAAI,EAAE,KAAK,OAAO;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AAElD,UAAM,SAAS,MAAM,KAAK;AAAA,MACxB;AAAA,MACA,aAAa,EAAE,UAAU,GAAG,iBAAiB,GAAG,WAAW,IAAK;AAAA,IAClE,CAAC;AACD,qBAAiB,UAAU,OAAQ,MAAK;AACxC,UAAM,QAAQ,MAAM;AAEpB,WAAO,KAAK,EAAE,eAAe,cAAc;AAC3C,WAAO,MAAM,OAAO,EAAE,UAAU,eAAe;AAC/C,WAAQ,MAAyB,UAAU,EAAE,KAAK,EAAE;AACpD,WAAQ,MAAyB,SAAS,EAAE,KAAK,KAAK;AACtD,WAAO,QAAQ,EAAE,KAAK,CAAC;AACvB,UAAM,MAAM,OAAO;AAAA,EACrB,CAAC;AACH,CAAC;AAED,IAAI,iBAAiB;AACnB,WAAS,oBAAoB,YAAY;AACvC,UAAM;AAAA,MACJ,IAAI,IAAI;AAAA,QACN,aAAa;AAAA,QACb,kBAAkB;AAAA,MACpB,CAAC;AAAA,MACD;AAAA,IACF;AAAA,EACF,CAAC;AACH,OAAO;AACL,WAAS,oBAAoB,MAAM;AACjC,OAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;AAEA,IAAI,iBAAiB;AACnB,WAAS,uCAAuC,YAAY;AAC1D,UAAM;AAAA,MACJ,IAAI,IAAI;AAAA,QACN,aAAa;AAAA,QACb,kBAAkB;AAAA,MACpB,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH,OAAO;AACL,WAAS,uCAAuC,MAAM;AACpD,OAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;","names":[]}
@@ -18,16 +18,17 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var tool_utils_exports = {};
20
20
  __export(tool_utils_exports, {
21
+ toResponsesTool: () => toResponsesTool,
21
22
  toResponsesTools: () => toResponsesTools
22
23
  });
23
24
  module.exports = __toCommonJS(tool_utils_exports);
24
25
  var import_agents = require("@livekit/agents");
25
26
  var import_tools = require("./tools.cjs");
26
- function toResponsesTools(toolCtx, strictToolSchema) {
27
- const functionTools = import_agents.llm.sortedToolEntries(toolCtx).map(([name, tool]) => {
27
+ function toResponsesTool(tool, strictToolSchema) {
28
+ if (import_agents.llm.isFunctionTool(tool)) {
28
29
  const oaiParams = {
29
30
  type: "function",
30
- name,
31
+ name: tool.name,
31
32
  description: tool.description,
32
33
  parameters: import_agents.llm.toJsonSchema(
33
34
  tool.parameters,
@@ -39,15 +40,18 @@ function toResponsesTools(toolCtx, strictToolSchema) {
39
40
  oaiParams.strict = true;
40
41
  }
41
42
  return oaiParams;
42
- });
43
- const providerTools = toolCtx.flatten().filter((tool) => !import_agents.llm.isFunctionTool(tool)).map(
44
- (tool) => tool instanceof import_tools.OpenAITool ? tool.toToolConfig() : void 0
45
- ).filter((tool) => tool !== void 0);
46
- const tools = [...functionTools, ...providerTools];
43
+ }
44
+ return tool instanceof import_tools.OpenAITool ? tool.toToolConfig() : void 0;
45
+ }
46
+ function toResponsesTools(toolCtx, strictToolSchema) {
47
+ const functionTools = import_agents.llm.sortedToolEntries(toolCtx).map(([, tool]) => tool);
48
+ const providerTools = toolCtx.flatten().filter((tool) => !import_agents.llm.isFunctionTool(tool));
49
+ const tools = [...functionTools, ...providerTools].map((tool) => toResponsesTool(tool, strictToolSchema)).filter((tool) => tool !== void 0);
47
50
  return tools.length > 0 ? tools : void 0;
48
51
  }
49
52
  // Annotate the CommonJS export names for ESM import in node:
50
53
  0 && (module.exports = {
54
+ toResponsesTool,
51
55
  toResponsesTools
52
56
  });
53
57
  //# sourceMappingURL=tool_utils.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tool_utils.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { llm } from '@livekit/agents';\nimport type OpenAI from 'openai';\nimport { OpenAITool } from './tools.js';\n\nexport function toResponsesTools(\n toolCtx: llm.ToolContext,\n strictToolSchema: boolean,\n): OpenAI.Responses.Tool[] | undefined {\n // Function tools are emitted first, sorted by name for deterministic payloads; provider\n // tools follow in registration order.\n const functionTools = llm.sortedToolEntries(toolCtx).map(([name, tool]) => {\n const oaiParams = {\n type: 'function' as const,\n name,\n description: tool.description,\n parameters: llm.toJsonSchema(\n tool.parameters,\n true,\n strictToolSchema,\n ) as unknown as OpenAI.Responses.FunctionTool['parameters'],\n } as OpenAI.Responses.FunctionTool;\n\n if (strictToolSchema) {\n oaiParams.strict = true;\n }\n\n return oaiParams;\n });\n\n const providerTools = toolCtx\n .flatten()\n .filter((tool) => !llm.isFunctionTool(tool))\n .map((tool) =>\n tool instanceof OpenAITool\n ? (tool.toToolConfig() as unknown as OpenAI.Responses.Tool)\n : undefined,\n )\n .filter((tool): tool is OpenAI.Responses.Tool => tool !== undefined);\n\n const tools = [...functionTools, ...providerTools];\n\n return tools.length > 0 ? tools : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAAoB;AAEpB,mBAA2B;AAEpB,SAAS,iBACd,SACA,kBACqC;AAGrC,QAAM,gBAAgB,kBAAI,kBAAkB,OAAO,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM;AACzE,UAAM,YAAY;AAAA,MAChB,MAAM;AAAA,MACN;AAAA,MACA,aAAa,KAAK;AAAA,MAClB,YAAY,kBAAI;AAAA,QACd,KAAK;AAAA,QACL;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,QAAI,kBAAkB;AACpB,gBAAU,SAAS;AAAA,IACrB;AAEA,WAAO;AAAA,EACT,CAAC;AAED,QAAM,gBAAgB,QACnB,QAAQ,EACR,OAAO,CAAC,SAAS,CAAC,kBAAI,eAAe,IAAI,CAAC,EAC1C;AAAA,IAAI,CAAC,SACJ,gBAAgB,0BACX,KAAK,aAAa,IACnB;AAAA,EACN,EACC,OAAO,CAAC,SAAwC,SAAS,MAAS;AAErE,QAAM,QAAQ,CAAC,GAAG,eAAe,GAAG,aAAa;AAEjD,SAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;","names":[]}
1
+ {"version":3,"sources":["../src/tool_utils.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { llm } from '@livekit/agents';\nimport type OpenAI from 'openai';\nimport { OpenAITool } from './tools.js';\n\nexport function toResponsesTool(\n tool: llm.Tool,\n strictToolSchema: boolean,\n): OpenAI.Responses.Tool | undefined {\n if (llm.isFunctionTool(tool)) {\n const oaiParams = {\n type: 'function' as const,\n name: tool.name,\n description: tool.description,\n parameters: llm.toJsonSchema(\n tool.parameters,\n true,\n strictToolSchema,\n ) as unknown as OpenAI.Responses.FunctionTool['parameters'],\n } as OpenAI.Responses.FunctionTool;\n\n if (strictToolSchema) {\n oaiParams.strict = true;\n }\n\n return oaiParams;\n }\n\n return tool instanceof OpenAITool\n ? (tool.toToolConfig() as unknown as OpenAI.Responses.Tool)\n : undefined;\n}\n\nexport function toResponsesTools(\n toolCtx: llm.ToolContext,\n strictToolSchema: boolean,\n): OpenAI.Responses.Tool[] | undefined {\n // Function tools are emitted first, sorted by name for deterministic payloads; provider\n // tools follow in registration order.\n const functionTools = llm.sortedToolEntries(toolCtx).map(([, tool]) => tool);\n const providerTools = toolCtx.flatten().filter((tool) => !llm.isFunctionTool(tool));\n const tools = [...functionTools, ...providerTools]\n .map((tool) => toResponsesTool(tool, strictToolSchema))\n .filter((tool): tool is OpenAI.Responses.Tool => tool !== undefined);\n\n return tools.length > 0 ? tools : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAAoB;AAEpB,mBAA2B;AAEpB,SAAS,gBACd,MACA,kBACmC;AACnC,MAAI,kBAAI,eAAe,IAAI,GAAG;AAC5B,UAAM,YAAY;AAAA,MAChB,MAAM;AAAA,MACN,MAAM,KAAK;AAAA,MACX,aAAa,KAAK;AAAA,MAClB,YAAY,kBAAI;AAAA,QACd,KAAK;AAAA,QACL;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,QAAI,kBAAkB;AACpB,gBAAU,SAAS;AAAA,IACrB;AAEA,WAAO;AAAA,EACT;AAEA,SAAO,gBAAgB,0BAClB,KAAK,aAAa,IACnB;AACN;AAEO,SAAS,iBACd,SACA,kBACqC;AAGrC,QAAM,gBAAgB,kBAAI,kBAAkB,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,IAAI,MAAM,IAAI;AAC3E,QAAM,gBAAgB,QAAQ,QAAQ,EAAE,OAAO,CAAC,SAAS,CAAC,kBAAI,eAAe,IAAI,CAAC;AAClF,QAAM,QAAQ,CAAC,GAAG,eAAe,GAAG,aAAa,EAC9C,IAAI,CAAC,SAAS,gBAAgB,MAAM,gBAAgB,CAAC,EACrD,OAAO,CAAC,SAAwC,SAAS,MAAS;AAErE,SAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;","names":[]}
@@ -1,4 +1,5 @@
1
1
  import { llm } from '@livekit/agents';
2
2
  import type OpenAI from 'openai';
3
+ export declare function toResponsesTool(tool: llm.Tool, strictToolSchema: boolean): OpenAI.Responses.Tool | undefined;
3
4
  export declare function toResponsesTools(toolCtx: llm.ToolContext, strictToolSchema: boolean): OpenAI.Responses.Tool[] | undefined;
4
5
  //# sourceMappingURL=tool_utils.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { llm } from '@livekit/agents';
2
2
  import type OpenAI from 'openai';
3
+ export declare function toResponsesTool(tool: llm.Tool, strictToolSchema: boolean): OpenAI.Responses.Tool | undefined;
3
4
  export declare function toResponsesTools(toolCtx: llm.ToolContext, strictToolSchema: boolean): OpenAI.Responses.Tool[] | undefined;
4
5
  //# sourceMappingURL=tool_utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool_utils.d.ts","sourceRoot":"","sources":["../src/tool_utils.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AACtC,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAGjC,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,GAAG,CAAC,WAAW,EACxB,gBAAgB,EAAE,OAAO,GACxB,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,GAAG,SAAS,CAmCrC"}
1
+ {"version":3,"file":"tool_utils.d.ts","sourceRoot":"","sources":["../src/tool_utils.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AACtC,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAGjC,wBAAgB,eAAe,CAC7B,IAAI,EAAE,GAAG,CAAC,IAAI,EACd,gBAAgB,EAAE,OAAO,GACxB,MAAM,CAAC,SAAS,CAAC,IAAI,GAAG,SAAS,CAuBnC;AAED,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,GAAG,CAAC,WAAW,EACxB,gBAAgB,EAAE,OAAO,GACxB,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,GAAG,SAAS,CAUrC"}
@@ -1,10 +1,10 @@
1
1
  import { llm } from "@livekit/agents";
2
2
  import { OpenAITool } from "./tools.js";
3
- function toResponsesTools(toolCtx, strictToolSchema) {
4
- const functionTools = llm.sortedToolEntries(toolCtx).map(([name, tool]) => {
3
+ function toResponsesTool(tool, strictToolSchema) {
4
+ if (llm.isFunctionTool(tool)) {
5
5
  const oaiParams = {
6
6
  type: "function",
7
- name,
7
+ name: tool.name,
8
8
  description: tool.description,
9
9
  parameters: llm.toJsonSchema(
10
10
  tool.parameters,
@@ -16,14 +16,17 @@ function toResponsesTools(toolCtx, strictToolSchema) {
16
16
  oaiParams.strict = true;
17
17
  }
18
18
  return oaiParams;
19
- });
20
- const providerTools = toolCtx.flatten().filter((tool) => !llm.isFunctionTool(tool)).map(
21
- (tool) => tool instanceof OpenAITool ? tool.toToolConfig() : void 0
22
- ).filter((tool) => tool !== void 0);
23
- const tools = [...functionTools, ...providerTools];
19
+ }
20
+ return tool instanceof OpenAITool ? tool.toToolConfig() : void 0;
21
+ }
22
+ function toResponsesTools(toolCtx, strictToolSchema) {
23
+ const functionTools = llm.sortedToolEntries(toolCtx).map(([, tool]) => tool);
24
+ const providerTools = toolCtx.flatten().filter((tool) => !llm.isFunctionTool(tool));
25
+ const tools = [...functionTools, ...providerTools].map((tool) => toResponsesTool(tool, strictToolSchema)).filter((tool) => tool !== void 0);
24
26
  return tools.length > 0 ? tools : void 0;
25
27
  }
26
28
  export {
29
+ toResponsesTool,
27
30
  toResponsesTools
28
31
  };
29
32
  //# sourceMappingURL=tool_utils.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tool_utils.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { llm } from '@livekit/agents';\nimport type OpenAI from 'openai';\nimport { OpenAITool } from './tools.js';\n\nexport function toResponsesTools(\n toolCtx: llm.ToolContext,\n strictToolSchema: boolean,\n): OpenAI.Responses.Tool[] | undefined {\n // Function tools are emitted first, sorted by name for deterministic payloads; provider\n // tools follow in registration order.\n const functionTools = llm.sortedToolEntries(toolCtx).map(([name, tool]) => {\n const oaiParams = {\n type: 'function' as const,\n name,\n description: tool.description,\n parameters: llm.toJsonSchema(\n tool.parameters,\n true,\n strictToolSchema,\n ) as unknown as OpenAI.Responses.FunctionTool['parameters'],\n } as OpenAI.Responses.FunctionTool;\n\n if (strictToolSchema) {\n oaiParams.strict = true;\n }\n\n return oaiParams;\n });\n\n const providerTools = toolCtx\n .flatten()\n .filter((tool) => !llm.isFunctionTool(tool))\n .map((tool) =>\n tool instanceof OpenAITool\n ? (tool.toToolConfig() as unknown as OpenAI.Responses.Tool)\n : undefined,\n )\n .filter((tool): tool is OpenAI.Responses.Tool => tool !== undefined);\n\n const tools = [...functionTools, ...providerTools];\n\n return tools.length > 0 ? tools : undefined;\n}\n"],"mappings":"AAGA,SAAS,WAAW;AAEpB,SAAS,kBAAkB;AAEpB,SAAS,iBACd,SACA,kBACqC;AAGrC,QAAM,gBAAgB,IAAI,kBAAkB,OAAO,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM;AACzE,UAAM,YAAY;AAAA,MAChB,MAAM;AAAA,MACN;AAAA,MACA,aAAa,KAAK;AAAA,MAClB,YAAY,IAAI;AAAA,QACd,KAAK;AAAA,QACL;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,QAAI,kBAAkB;AACpB,gBAAU,SAAS;AAAA,IACrB;AAEA,WAAO;AAAA,EACT,CAAC;AAED,QAAM,gBAAgB,QACnB,QAAQ,EACR,OAAO,CAAC,SAAS,CAAC,IAAI,eAAe,IAAI,CAAC,EAC1C;AAAA,IAAI,CAAC,SACJ,gBAAgB,aACX,KAAK,aAAa,IACnB;AAAA,EACN,EACC,OAAO,CAAC,SAAwC,SAAS,MAAS;AAErE,QAAM,QAAQ,CAAC,GAAG,eAAe,GAAG,aAAa;AAEjD,SAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;","names":[]}
1
+ {"version":3,"sources":["../src/tool_utils.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { llm } from '@livekit/agents';\nimport type OpenAI from 'openai';\nimport { OpenAITool } from './tools.js';\n\nexport function toResponsesTool(\n tool: llm.Tool,\n strictToolSchema: boolean,\n): OpenAI.Responses.Tool | undefined {\n if (llm.isFunctionTool(tool)) {\n const oaiParams = {\n type: 'function' as const,\n name: tool.name,\n description: tool.description,\n parameters: llm.toJsonSchema(\n tool.parameters,\n true,\n strictToolSchema,\n ) as unknown as OpenAI.Responses.FunctionTool['parameters'],\n } as OpenAI.Responses.FunctionTool;\n\n if (strictToolSchema) {\n oaiParams.strict = true;\n }\n\n return oaiParams;\n }\n\n return tool instanceof OpenAITool\n ? (tool.toToolConfig() as unknown as OpenAI.Responses.Tool)\n : undefined;\n}\n\nexport function toResponsesTools(\n toolCtx: llm.ToolContext,\n strictToolSchema: boolean,\n): OpenAI.Responses.Tool[] | undefined {\n // Function tools are emitted first, sorted by name for deterministic payloads; provider\n // tools follow in registration order.\n const functionTools = llm.sortedToolEntries(toolCtx).map(([, tool]) => tool);\n const providerTools = toolCtx.flatten().filter((tool) => !llm.isFunctionTool(tool));\n const tools = [...functionTools, ...providerTools]\n .map((tool) => toResponsesTool(tool, strictToolSchema))\n .filter((tool): tool is OpenAI.Responses.Tool => tool !== undefined);\n\n return tools.length > 0 ? tools : undefined;\n}\n"],"mappings":"AAGA,SAAS,WAAW;AAEpB,SAAS,kBAAkB;AAEpB,SAAS,gBACd,MACA,kBACmC;AACnC,MAAI,IAAI,eAAe,IAAI,GAAG;AAC5B,UAAM,YAAY;AAAA,MAChB,MAAM;AAAA,MACN,MAAM,KAAK;AAAA,MACX,aAAa,KAAK;AAAA,MAClB,YAAY,IAAI;AAAA,QACd,KAAK;AAAA,QACL;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,QAAI,kBAAkB;AACpB,gBAAU,SAAS;AAAA,IACrB;AAEA,WAAO;AAAA,EACT;AAEA,SAAO,gBAAgB,aAClB,KAAK,aAAa,IACnB;AACN;AAEO,SAAS,iBACd,SACA,kBACqC;AAGrC,QAAM,gBAAgB,IAAI,kBAAkB,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,IAAI,MAAM,IAAI;AAC3E,QAAM,gBAAgB,QAAQ,QAAQ,EAAE,OAAO,CAAC,SAAS,CAAC,IAAI,eAAe,IAAI,CAAC;AAClF,QAAM,QAAQ,CAAC,GAAG,eAAe,GAAG,aAAa,EAC9C,IAAI,CAAC,SAAS,gBAAgB,MAAM,gBAAgB,CAAC,EACrD,OAAO,CAAC,SAAwC,SAAS,MAAS;AAErE,SAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;","names":[]}
@@ -5,6 +5,33 @@ var import_zod = require("zod");
5
5
  var import_tool_utils = require("./tool_utils.cjs");
6
6
  var import_tools = require("./tools.cjs");
7
7
  (0, import_vitest.describe)("toResponsesTools", () => {
8
+ (0, import_vitest.it)("sorts function tools before provider tools without making optional parameters strict", () => {
9
+ const makeTool = (name) => import_agents.llm.tool({
10
+ name,
11
+ description: "Look up weather",
12
+ parameters: import_zod.z.object({ city: import_zod.z.string().optional() }),
13
+ execute: async () => "sunny"
14
+ });
15
+ (0, import_vitest.expect)(
16
+ (0, import_tool_utils.toResponsesTools)(
17
+ new import_agents.llm.ToolContext([makeTool("zulu"), new import_tools.WebSearch(), makeTool("alpha")]),
18
+ false
19
+ )
20
+ ).toEqual([
21
+ ...["alpha", "zulu"].map((name) => ({
22
+ type: "function",
23
+ name,
24
+ description: "Look up weather",
25
+ parameters: {
26
+ $schema: "http://json-schema.org/draft-07/schema#",
27
+ type: "object",
28
+ properties: { city: { type: "string" } },
29
+ additionalProperties: false
30
+ }
31
+ })),
32
+ { type: "web_search", search_context_size: "medium" }
33
+ ]);
34
+ });
8
35
  (0, import_vitest.it)("serializes function tools", () => {
9
36
  const fn = import_agents.llm.tool({
10
37
  name: "lookup_weather",
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tool_utils.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { llm } from '@livekit/agents';\nimport { describe, expect, it } from 'vitest';\nimport { z } from 'zod';\nimport { toResponsesTools } from './tool_utils.js';\nimport { CodeInterpreter, FileSearch, WebSearch } from './tools.js';\n\ndescribe('toResponsesTools', () => {\n it('serializes function tools', () => {\n const fn = llm.tool({\n name: 'lookup_weather',\n description: 'Look up weather',\n parameters: z.object({ city: z.string() }),\n execute: async () => 'sunny',\n });\n\n expect(toResponsesTools(new llm.ToolContext([fn]), true)).toEqual([\n {\n type: 'function',\n name: 'lookup_weather',\n description: 'Look up weather',\n parameters: {\n $schema: 'http://json-schema.org/draft-07/schema#',\n type: 'object',\n properties: { city: { type: 'string' } },\n required: ['city'],\n additionalProperties: false,\n },\n strict: true,\n },\n ]);\n });\n\n it('serializes OpenAI provider tools', () => {\n const tools = toResponsesTools(\n new llm.ToolContext([\n new WebSearch({\n filters: { allowed_domains: ['docs.livekit.io'] },\n searchContextSize: 'low',\n userLocation: { type: 'approximate', country: 'US' },\n }),\n new FileSearch({\n vectorStoreIds: ['vs_123'],\n maxNumResults: 3,\n rankingOptions: { ranker: 'auto' },\n }),\n new CodeInterpreter({ container: { type: 'auto', file_ids: ['file_123'] } }),\n ]),\n false,\n );\n\n expect(tools).toEqual([\n {\n type: 'web_search',\n search_context_size: 'low',\n filters: { allowed_domains: ['docs.livekit.io'] },\n user_location: { type: 'approximate', country: 'US' },\n },\n {\n type: 'file_search',\n vector_store_ids: ['vs_123'],\n max_num_results: 3,\n ranking_options: { ranker: 'auto' },\n },\n { type: 'code_interpreter', container: { type: 'auto', file_ids: ['file_123'] } },\n ]);\n });\n\n it('omits the code interpreter container when unset', () => {\n expect(toResponsesTools(new llm.ToolContext([new CodeInterpreter()]), false)).toEqual([\n { type: 'code_interpreter' },\n ]);\n });\n\n it('ignores non-OpenAI provider tools', () => {\n class OtherProviderTool extends llm.ProviderTool {}\n\n expect(\n toResponsesTools(new llm.ToolContext([new OtherProviderTool({ id: 'other' })]), false),\n ).toBeUndefined();\n });\n});\n"],"mappings":";AAGA,oBAAoB;AACpB,oBAAqC;AACrC,iBAAkB;AAClB,wBAAiC;AACjC,mBAAuD;AAAA,IAEvD,wBAAS,oBAAoB,MAAM;AACjC,wBAAG,6BAA6B,MAAM;AACpC,UAAM,KAAK,kBAAI,KAAK;AAAA,MAClB,MAAM;AAAA,MACN,aAAa;AAAA,MACb,YAAY,aAAE,OAAO,EAAE,MAAM,aAAE,OAAO,EAAE,CAAC;AAAA,MACzC,SAAS,YAAY;AAAA,IACvB,CAAC;AAED,kCAAO,oCAAiB,IAAI,k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AAM,QAAQ,UAAU,CAAC,UAAU,EAAE,EAAE;AAAA,IAClF,CAAC;AAAA,EACH,CAAC;AAED,wBAAG,mDAAmD,MAAM;AAC1D,kCAAO,oCAAiB,IAAI,kBAAI,YAAY,CAAC,IAAI,6BAAgB,CAAC,CAAC,GAAG,KAAK,CAAC,EAAE,QAAQ;AAAA,MACpF,EAAE,MAAM,mBAAmB;AAAA,IAC7B,CAAC;AAAA,EACH,CAAC;AAED,wBAAG,qCAAqC,MAAM;AAAA,IAC5C,MAAM,0BAA0B,kBAAI,aAAa;AAAA,IAAC;AAElD;AAAA,UACE,oCAAiB,IAAI,kBAAI,YAAY,CAAC,IAAI,kBAAkB,EAAE,IAAI,QAAQ,CAAC,CAAC,CAAC,GAAG,KAAK;AAAA,IACvF,EAAE,cAAc;AAAA,EAClB,CAAC;AACH,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/tool_utils.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { llm } from '@livekit/agents';\nimport { describe, expect, it } from 'vitest';\nimport { z } from 'zod';\nimport { toResponsesTools } from './tool_utils.js';\nimport { CodeInterpreter, FileSearch, WebSearch } from './tools.js';\n\ndescribe('toResponsesTools', () => {\n it('sorts function tools before provider tools without making optional parameters strict', () => {\n const makeTool = (name: string) =>\n llm.tool({\n name,\n description: 'Look up weather',\n parameters: z.object({ city: z.string().optional() }),\n execute: async () => 'sunny',\n });\n\n expect(\n toResponsesTools(\n new llm.ToolContext([makeTool('zulu'), new WebSearch(), makeTool('alpha')]),\n false,\n ),\n ).toEqual([\n ...['alpha', 'zulu'].map((name) => ({\n type: 'function',\n name,\n description: 'Look up weather',\n parameters: {\n $schema: 'http://json-schema.org/draft-07/schema#',\n type: 'object',\n properties: { city: { type: 'string' } },\n additionalProperties: false,\n },\n })),\n { type: 'web_search', search_context_size: 'medium' },\n ]);\n });\n\n it('serializes function tools', () => {\n const fn = llm.tool({\n name: 'lookup_weather',\n description: 'Look up weather',\n parameters: z.object({ city: z.string() }),\n execute: async () => 'sunny',\n });\n\n expect(toResponsesTools(new llm.ToolContext([fn]), true)).toEqual([\n {\n type: 'function',\n name: 'lookup_weather',\n description: 'Look up weather',\n parameters: {\n $schema: 'http://json-schema.org/draft-07/schema#',\n type: 'object',\n properties: { city: { type: 'string' } },\n required: ['city'],\n additionalProperties: false,\n },\n strict: true,\n },\n ]);\n });\n\n it('serializes OpenAI provider tools', () => {\n const tools = toResponsesTools(\n new llm.ToolContext([\n new WebSearch({\n filters: { allowed_domains: ['docs.livekit.io'] },\n searchContextSize: 'low',\n userLocation: { type: 'approximate', country: 'US' },\n }),\n new FileSearch({\n vectorStoreIds: ['vs_123'],\n maxNumResults: 3,\n rankingOptions: { ranker: 'auto' },\n }),\n new CodeInterpreter({ container: { type: 'auto', file_ids: ['file_123'] } }),\n ]),\n false,\n );\n\n expect(tools).toEqual([\n {\n type: 'web_search',\n search_context_size: 'low',\n filters: { allowed_domains: ['docs.livekit.io'] },\n user_location: { type: 'approximate', country: 'US' },\n },\n {\n type: 'file_search',\n vector_store_ids: ['vs_123'],\n max_num_results: 3,\n ranking_options: { ranker: 'auto' },\n },\n { type: 'code_interpreter', container: { type: 'auto', file_ids: ['file_123'] } },\n ]);\n });\n\n it('omits the code interpreter container when unset', () => {\n expect(toResponsesTools(new llm.ToolContext([new CodeInterpreter()]), false)).toEqual([\n { type: 'code_interpreter' },\n ]);\n });\n\n it('ignores non-OpenAI provider tools', () => {\n class OtherProviderTool extends llm.ProviderTool {}\n\n expect(\n toResponsesTools(new llm.ToolContext([new OtherProviderTool({ id: 'other' })]), false),\n ).toBeUndefined();\n });\n});\n"],"mappings":";AAGA,oBAAoB;AACpB,oBAAqC;AACrC,iBAAkB;AAClB,wBAAiC;AACjC,mBAAuD;AAAA,IAEvD,wBAAS,oBAAoB,MAAM;AACjC,wBAAG,wFAAwF,MAAM;AAC/F,UAAM,WAAW,CAAC,SAChB,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AAA,IAAC;AAElD;AAAA,UACE,oCAAiB,IAAI,kBAAI,YAAY,CAAC,IAAI,kBAAkB,EAAE,IAAI,QAAQ,CAAC,CAAC,CAAC,GAAG,KAAK;AAAA,IACvF,EAAE,cAAc;AAAA,EAClB,CAAC;AACH,CAAC;","names":[]}
@@ -4,6 +4,33 @@ import { z } from "zod";
4
4
  import { toResponsesTools } from "./tool_utils.js";
5
5
  import { CodeInterpreter, FileSearch, WebSearch } from "./tools.js";
6
6
  describe("toResponsesTools", () => {
7
+ it("sorts function tools before provider tools without making optional parameters strict", () => {
8
+ const makeTool = (name) => llm.tool({
9
+ name,
10
+ description: "Look up weather",
11
+ parameters: z.object({ city: z.string().optional() }),
12
+ execute: async () => "sunny"
13
+ });
14
+ expect(
15
+ toResponsesTools(
16
+ new llm.ToolContext([makeTool("zulu"), new WebSearch(), makeTool("alpha")]),
17
+ false
18
+ )
19
+ ).toEqual([
20
+ ...["alpha", "zulu"].map((name) => ({
21
+ type: "function",
22
+ name,
23
+ description: "Look up weather",
24
+ parameters: {
25
+ $schema: "http://json-schema.org/draft-07/schema#",
26
+ type: "object",
27
+ properties: { city: { type: "string" } },
28
+ additionalProperties: false
29
+ }
30
+ })),
31
+ { type: "web_search", search_context_size: "medium" }
32
+ ]);
33
+ });
7
34
  it("serializes function tools", () => {
8
35
  const fn = llm.tool({
9
36
  name: "lookup_weather",
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tool_utils.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { llm } from '@livekit/agents';\nimport { describe, expect, it } from 'vitest';\nimport { z } from 'zod';\nimport { toResponsesTools } from './tool_utils.js';\nimport { CodeInterpreter, FileSearch, WebSearch } from './tools.js';\n\ndescribe('toResponsesTools', () => {\n it('serializes function tools', () => {\n const fn = llm.tool({\n name: 'lookup_weather',\n description: 'Look up weather',\n parameters: z.object({ city: z.string() }),\n execute: async () => 'sunny',\n });\n\n expect(toResponsesTools(new llm.ToolContext([fn]), true)).toEqual([\n {\n type: 'function',\n name: 'lookup_weather',\n description: 'Look up weather',\n parameters: {\n $schema: 'http://json-schema.org/draft-07/schema#',\n type: 'object',\n properties: { city: { type: 'string' } },\n required: ['city'],\n additionalProperties: false,\n },\n strict: true,\n },\n ]);\n });\n\n it('serializes OpenAI provider tools', () => {\n const tools = toResponsesTools(\n new llm.ToolContext([\n new WebSearch({\n filters: { allowed_domains: ['docs.livekit.io'] },\n searchContextSize: 'low',\n userLocation: { type: 'approximate', country: 'US' },\n }),\n new FileSearch({\n vectorStoreIds: ['vs_123'],\n maxNumResults: 3,\n rankingOptions: { ranker: 'auto' },\n }),\n new CodeInterpreter({ container: { type: 'auto', file_ids: ['file_123'] } }),\n ]),\n false,\n );\n\n expect(tools).toEqual([\n {\n type: 'web_search',\n search_context_size: 'low',\n filters: { allowed_domains: ['docs.livekit.io'] },\n user_location: { type: 'approximate', country: 'US' },\n },\n {\n type: 'file_search',\n vector_store_ids: ['vs_123'],\n max_num_results: 3,\n ranking_options: { ranker: 'auto' },\n },\n { type: 'code_interpreter', container: { type: 'auto', file_ids: ['file_123'] } },\n ]);\n });\n\n it('omits the code interpreter container when unset', () => {\n expect(toResponsesTools(new llm.ToolContext([new CodeInterpreter()]), false)).toEqual([\n { type: 'code_interpreter' },\n ]);\n });\n\n it('ignores non-OpenAI provider tools', () => {\n class OtherProviderTool extends llm.ProviderTool {}\n\n expect(\n toResponsesTools(new llm.ToolContext([new OtherProviderTool({ id: 'other' })]), false),\n ).toBeUndefined();\n });\n});\n"],"mappings":"AAGA,SAAS,WAAW;AACpB,SAAS,UAAU,QAAQ,UAAU;AACrC,SAAS,SAAS;AAClB,SAAS,wBAAwB;AACjC,SAAS,iBAAiB,YAAY,iBAAiB;AAEvD,SAAS,oBAAoB,MAAM;AACjC,KAAG,6BAA6B,MAAM;AACpC,UAAM,KAAK,IAAI,KAAK;AAAA,MAClB,MAAM;AAAA,MACN,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,CAAC,QAAQ;AAAA,QAC3B,iBAAiB;AAAA,QACjB,iBAAiB,EAAE,QAAQ,OAAO;AAAA,MACpC;AAAA,MACA,EAAE,MAAM,oBAAoB,WAAW,EAAE,MAAM,QAAQ,UAAU,CAAC,UAAU,EAAE,EAAE;AAAA,IAClF,CAAC;AAAA,EACH,CAAC;AAED,KAAG,mDAAmD,MAAM;AAC1D,WAAO,iBAAiB,IAAI,IAAI,YAAY,CAAC,IAAI,gBAAgB,CAAC,CAAC,GAAG,KAAK,CAAC,EAAE,QAAQ;AAAA,MACpF,EAAE,MAAM,mBAAmB;AAAA,IAC7B,CAAC;AAAA,EACH,CAAC;AAED,KAAG,qCAAqC,MAAM;AAAA,IAC5C,MAAM,0BAA0B,IAAI,aAAa;AAAA,IAAC;AAElD;AAAA,MACE,iBAAiB,IAAI,IAAI,YAAY,CAAC,IAAI,kBAAkB,EAAE,IAAI,QAAQ,CAAC,CAAC,CAAC,GAAG,KAAK;AAAA,IACvF,EAAE,cAAc;AAAA,EAClB,CAAC;AACH,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/tool_utils.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { llm } from '@livekit/agents';\nimport { describe, expect, it } from 'vitest';\nimport { z } from 'zod';\nimport { toResponsesTools } from './tool_utils.js';\nimport { CodeInterpreter, FileSearch, WebSearch } from './tools.js';\n\ndescribe('toResponsesTools', () => {\n it('sorts function tools before provider tools without making optional parameters strict', () => {\n const makeTool = (name: string) =>\n llm.tool({\n name,\n description: 'Look up weather',\n parameters: z.object({ city: z.string().optional() }),\n execute: async () => 'sunny',\n });\n\n expect(\n toResponsesTools(\n new llm.ToolContext([makeTool('zulu'), new WebSearch(), makeTool('alpha')]),\n false,\n ),\n ).toEqual([\n ...['alpha', 'zulu'].map((name) => ({\n type: 'function',\n name,\n description: 'Look up weather',\n parameters: {\n $schema: 'http://json-schema.org/draft-07/schema#',\n type: 'object',\n properties: { city: { type: 'string' } },\n additionalProperties: false,\n },\n })),\n { type: 'web_search', search_context_size: 'medium' },\n ]);\n });\n\n it('serializes function tools', () => {\n const fn = llm.tool({\n name: 'lookup_weather',\n description: 'Look up weather',\n parameters: z.object({ city: z.string() }),\n execute: async () => 'sunny',\n });\n\n expect(toResponsesTools(new llm.ToolContext([fn]), true)).toEqual([\n {\n type: 'function',\n name: 'lookup_weather',\n description: 'Look up weather',\n parameters: {\n $schema: 'http://json-schema.org/draft-07/schema#',\n type: 'object',\n properties: { city: { type: 'string' } },\n required: ['city'],\n additionalProperties: false,\n },\n strict: true,\n },\n ]);\n });\n\n it('serializes OpenAI provider tools', () => {\n const tools = toResponsesTools(\n new llm.ToolContext([\n new WebSearch({\n filters: { allowed_domains: ['docs.livekit.io'] },\n searchContextSize: 'low',\n userLocation: { type: 'approximate', country: 'US' },\n }),\n new FileSearch({\n vectorStoreIds: ['vs_123'],\n maxNumResults: 3,\n rankingOptions: { ranker: 'auto' },\n }),\n new CodeInterpreter({ container: { type: 'auto', file_ids: ['file_123'] } }),\n ]),\n false,\n );\n\n expect(tools).toEqual([\n {\n type: 'web_search',\n search_context_size: 'low',\n filters: { allowed_domains: ['docs.livekit.io'] },\n user_location: { type: 'approximate', country: 'US' },\n },\n {\n type: 'file_search',\n vector_store_ids: ['vs_123'],\n max_num_results: 3,\n ranking_options: { ranker: 'auto' },\n },\n { type: 'code_interpreter', container: { type: 'auto', file_ids: ['file_123'] } },\n ]);\n });\n\n it('omits the code interpreter container when unset', () => {\n expect(toResponsesTools(new llm.ToolContext([new CodeInterpreter()]), false)).toEqual([\n { type: 'code_interpreter' },\n ]);\n });\n\n it('ignores non-OpenAI provider tools', () => {\n class OtherProviderTool extends llm.ProviderTool {}\n\n expect(\n toResponsesTools(new llm.ToolContext([new OtherProviderTool({ id: 'other' })]), false),\n ).toBeUndefined();\n });\n});\n"],"mappings":"AAGA,SAAS,WAAW;AACpB,SAAS,UAAU,QAAQ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AAE,QAAQ;AAAA,MACpF,EAAE,MAAM,mBAAmB;AAAA,IAC7B,CAAC;AAAA,EACH,CAAC;AAED,KAAG,qCAAqC,MAAM;AAAA,IAC5C,MAAM,0BAA0B,IAAI,aAAa;AAAA,IAAC;AAElD;AAAA,MACE,iBAAiB,IAAI,IAAI,YAAY,CAAC,IAAI,kBAAkB,EAAE,IAAI,QAAQ,CAAC,CAAC,CAAC,GAAG,KAAK;AAAA,IACvF,EAAE,cAAc;AAAA,EAClB,CAAC;AACH,CAAC;","names":[]}
package/dist/ws/llm.cjs CHANGED
@@ -59,7 +59,7 @@ class ResponsesWebSocket {
59
59
  if (!parsed.success) return;
60
60
  const event = parsed.data;
61
61
  void current.write(event);
62
- if (event.type === "response.completed" || event.type === "response.failed" || event.type === "error") {
62
+ if (event.type === "response.completed" || event.type === "response.failed" || event.type === "response.incomplete" || event.type === "error") {
63
63
  void current.close();
64
64
  this.#outputQueue.shift();
65
65
  }
@@ -165,9 +165,9 @@ class WSLLM extends import_agents.llm.LLM {
165
165
  async aclose() {
166
166
  await this.close();
167
167
  }
168
- /** Called by LLMStream once response.created fires to atomically persist both the
168
+ /** Called by LLMStream once response.completed fires to atomically persist both the
169
169
  * response ID and its corresponding chat context for the next turn's diff. */
170
- _onResponseCreated(responseId, chatCtx) {
170
+ _onResponseCompleted(responseId, chatCtx) {
171
171
  this.#prevResponseId = responseId;
172
172
  this.#prevChatCtx = chatCtx;
173
173
  }
@@ -286,14 +286,23 @@ class WSLLMStream extends import_agents.llm.LLMStream {
286
286
  }
287
287
  async run() {
288
288
  this.#retryable = true;
289
+ let responseError;
289
290
  try {
290
291
  await this.#pool.withConnection(async (conn) => {
291
- const needsRetry = await this.#runWithConn(conn, this.chatCtx, this.#prevResponseId);
292
- if (needsRetry) {
292
+ const result = await this.#runWithConn(conn, this.chatCtx, this.#prevResponseId);
293
+ if (result instanceof import_agents.APIStatusError) {
294
+ responseError = result;
295
+ return;
296
+ }
297
+ if (result) {
293
298
  this.#retryable = true;
294
- await this.#runWithConn(conn, this.#fullChatCtx, void 0);
299
+ const retryResult = await this.#runWithConn(conn, this.#fullChatCtx, void 0);
300
+ if (retryResult instanceof import_agents.APIStatusError) {
301
+ responseError = retryResult;
302
+ }
295
303
  }
296
304
  });
305
+ if (responseError) throw responseError;
297
306
  } catch (error) {
298
307
  if (error instanceof import_agents.APIStatusError || error instanceof import_agents.APITimeoutError || error instanceof import_agents.APIConnectionError) {
299
308
  throw error;
@@ -363,6 +372,8 @@ class WSLLMStream extends import_agents.llm.LLMStream {
363
372
  case "response.failed":
364
373
  this.#handleResponseFailed(event);
365
374
  break;
375
+ case "response.incomplete":
376
+ return this.#handleResponseIncomplete(event);
366
377
  default:
367
378
  break;
368
379
  }
@@ -406,7 +417,6 @@ class WSLLMStream extends import_agents.llm.LLMStream {
406
417
  }
407
418
  #handleResponseCreated(event) {
408
419
  this.#responseId = event.response.id;
409
- this.#llm._onResponseCreated(event.response.id, this.#fullChatCtx);
410
420
  }
411
421
  #handleOutputItemDone(event) {
412
422
  if (event.item.type === "function_call") {
@@ -447,6 +457,7 @@ class WSLLMStream extends import_agents.llm.LLMStream {
447
457
  };
448
458
  }
449
459
  #handleResponseCompleted(event) {
460
+ this.#llm._onResponseCompleted(event.response.id, this.#fullChatCtx);
450
461
  this.#llm._setPendingToolCalls(this.#pendingToolCalls);
451
462
  if (event.response.usage) {
452
463
  return {
@@ -469,6 +480,13 @@ class WSLLMStream extends import_agents.llm.LLMStream {
469
480
  options: { statusCode: -1, retryable: false }
470
481
  });
471
482
  }
483
+ #handleResponseIncomplete(event) {
484
+ var _a;
485
+ return new import_agents.APIStatusError({
486
+ message: `response incomplete: ${((_a = event.response.incomplete_details) == null ? void 0 : _a.reason) ?? "reason unavailable"}`,
487
+ options: { statusCode: -1, retryable: false }
488
+ });
489
+ }
472
490
  }
473
491
  async function connectWs(url, apiKey, timeoutMs) {
474
492
  return new Promise((resolve, reject) => {