@livekit/agents-plugin-openai 1.4.11 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/index.cjs +4 -2
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +1 -0
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +2 -1
  7. package/dist/index.js.map +1 -1
  8. package/dist/llm.cjs +8 -2
  9. package/dist/llm.cjs.map +1 -1
  10. package/dist/llm.d.cts +4 -3
  11. package/dist/llm.d.ts +4 -3
  12. package/dist/llm.d.ts.map +1 -1
  13. package/dist/llm.js +8 -2
  14. package/dist/llm.js.map +1 -1
  15. package/dist/models.cjs +12 -3
  16. package/dist/models.cjs.map +1 -1
  17. package/dist/models.d.cts +7 -1
  18. package/dist/models.d.ts +7 -1
  19. package/dist/models.d.ts.map +1 -1
  20. package/dist/models.js +11 -3
  21. package/dist/models.js.map +1 -1
  22. package/dist/realtime/realtime_model.cjs +24 -19
  23. package/dist/realtime/realtime_model.cjs.map +1 -1
  24. package/dist/realtime/realtime_model.d.cts +1 -1
  25. package/dist/realtime/realtime_model.d.ts +1 -1
  26. package/dist/realtime/realtime_model.d.ts.map +1 -1
  27. package/dist/realtime/realtime_model.js +24 -19
  28. package/dist/realtime/realtime_model.js.map +1 -1
  29. package/dist/realtime/realtime_model.test.cjs +28 -0
  30. package/dist/realtime/realtime_model.test.cjs.map +1 -1
  31. package/dist/realtime/realtime_model.test.js +28 -0
  32. package/dist/realtime/realtime_model.test.js.map +1 -1
  33. package/dist/responses/llm.cjs +15 -18
  34. package/dist/responses/llm.cjs.map +1 -1
  35. package/dist/responses/llm.d.cts +4 -2
  36. package/dist/responses/llm.d.ts +4 -2
  37. package/dist/responses/llm.d.ts.map +1 -1
  38. package/dist/responses/llm.js +15 -18
  39. package/dist/responses/llm.js.map +1 -1
  40. package/dist/tool_utils.cjs +53 -0
  41. package/dist/tool_utils.cjs.map +1 -0
  42. package/dist/tool_utils.d.cts +4 -0
  43. package/dist/tool_utils.d.ts +4 -0
  44. package/dist/tool_utils.d.ts.map +1 -0
  45. package/dist/tool_utils.js +29 -0
  46. package/dist/tool_utils.js.map +1 -0
  47. package/dist/tool_utils.test.cjs +77 -0
  48. package/dist/tool_utils.test.cjs.map +1 -0
  49. package/dist/tool_utils.test.d.cts +2 -0
  50. package/dist/tool_utils.test.d.ts +2 -0
  51. package/dist/tool_utils.test.d.ts.map +1 -0
  52. package/dist/tool_utils.test.js +76 -0
  53. package/dist/tool_utils.test.js.map +1 -0
  54. package/dist/tools.cjs +117 -0
  55. package/dist/tools.cjs.map +1 -0
  56. package/dist/tools.d.cts +88 -0
  57. package/dist/tools.d.ts +88 -0
  58. package/dist/tools.d.ts.map +1 -0
  59. package/dist/tools.js +90 -0
  60. package/dist/tools.js.map +1 -0
  61. package/dist/ws/llm.cjs +15 -18
  62. package/dist/ws/llm.cjs.map +1 -1
  63. package/dist/ws/llm.d.cts +5 -3
  64. package/dist/ws/llm.d.ts +5 -3
  65. package/dist/ws/llm.d.ts.map +1 -1
  66. package/dist/ws/llm.js +15 -18
  67. package/dist/ws/llm.js.map +1 -1
  68. package/package.json +7 -7
  69. package/src/index.ts +1 -0
  70. package/src/llm.ts +16 -3
  71. package/src/models.ts +18 -3
  72. package/src/realtime/realtime_model.test.ts +38 -0
  73. package/src/realtime/realtime_model.ts +29 -19
  74. package/src/responses/llm.ts +27 -23
  75. package/src/tool_utils.test.ts +84 -0
  76. package/src/tool_utils.ts +46 -0
  77. package/src/tools.ts +166 -0
  78. package/src/ws/llm.ts +25 -24
@@ -13,9 +13,15 @@ import {
13
13
 
14
14
  type RealtimeSessionInternals = {
15
15
  generateReply: RealtimeSession['generateReply'];
16
+ updateInstructions: RealtimeSession['updateInstructions'];
16
17
  responseCreatedFutures: Record<string, unknown>;
17
18
  sendEvent: ReturnType<typeof vi.fn>;
18
19
  textModeRecoveryRetries: number;
20
+ instructions?: string;
21
+ _options: {
22
+ isAzure?: boolean;
23
+ apiVersion?: string;
24
+ };
19
25
  };
20
26
 
21
27
  type ResponseDoneSessionInternals = {
@@ -36,6 +42,7 @@ function createSessionForTest(): RealtimeSessionInternals {
36
42
  session.responseCreatedFutures = {};
37
43
  session.sendEvent = vi.fn();
38
44
  session.textModeRecoveryRetries = 0;
45
+ session._options = {};
39
46
  return session;
40
47
  }
41
48
 
@@ -49,6 +56,37 @@ function stubTaskRuntime(): void {
49
56
  }
50
57
 
51
58
  describe('RealtimeSession.generateReply', () => {
59
+ it('preserves session instructions when generating with per-response instructions', async () => {
60
+ const session = createSessionForTest();
61
+ await session.updateInstructions('Your name is Kelly. Always respond in English.');
62
+
63
+ const abortController = new AbortController();
64
+ const promise = session.generateReply('Tell the user what your name is.', {
65
+ signal: abortController.signal,
66
+ });
67
+ abortController.abort();
68
+
69
+ await expect(promise).rejects.toThrow('generateReply aborted');
70
+ expect(session.instructions).toBe('Your name is Kelly. Always respond in English.');
71
+ expect(session.sendEvent).toHaveBeenCalledWith(
72
+ expect.objectContaining({
73
+ type: 'session.update',
74
+ session: expect.objectContaining({
75
+ instructions: 'Your name is Kelly. Always respond in English.',
76
+ }),
77
+ }),
78
+ );
79
+ expect(session.sendEvent).toHaveBeenCalledWith(
80
+ expect.objectContaining({
81
+ type: 'response.create',
82
+ response: expect.objectContaining({
83
+ instructions:
84
+ 'Your name is Kelly. Always respond in English.\nTell the user what your name is.',
85
+ }),
86
+ }),
87
+ );
88
+ });
89
+
52
90
  it('cancels an in-flight response when aborted before response.created', async () => {
53
91
  const session = createSessionForTest();
54
92
  const abortController = new AbortController();
@@ -429,7 +429,7 @@ export function processBaseURL({
429
429
  * - openai_client_event_queued: expose the raw client events sent to the OpenAI Realtime API
430
430
  */
431
431
  export class RealtimeSession extends llm.RealtimeSession {
432
- private _tools: llm.ToolContext = {};
432
+ private _tools: llm.ToolContext = llm.ToolContext.empty();
433
433
  private remoteChatCtx: llm.RemoteChatContext = new llm.RemoteChatContext();
434
434
  private messageChannel = new Queue<api_proto.ClientEvent>();
435
435
  private inputResampler?: AudioResampler;
@@ -557,7 +557,7 @@ export class RealtimeSession extends llm.RealtimeSession {
557
557
  }
558
558
 
559
559
  get tools() {
560
- return { ...this._tools } as llm.ToolContext;
560
+ return this._tools.copy();
561
561
  }
562
562
 
563
563
  async updateChatCtx(_chatCtx: llm.ChatContext): Promise<void> {
@@ -724,13 +724,12 @@ export class RealtimeSession extends llm.RealtimeSession {
724
724
 
725
725
  // TODO(brian): these logics below are noops I think; remove them later.
726
726
  const retainedToolNames = new Set(ev.session.tools.map((tool) => tool.name));
727
- const retainedTools = Object.fromEntries(
728
- Object.entries(_tools).filter(
729
- ([name, tool]) => llm.isFunctionTool(tool) && retainedToolNames.has(name),
730
- ),
727
+ // Keep provider tools and Toolsets as-is; only drop function tools the server didn't accept.
728
+ const retainedEntries = _tools.tools.filter(
729
+ (entry) => !llm.isFunctionTool(entry) || retainedToolNames.has(entry.name),
731
730
  );
732
731
 
733
- this._tools = retainedTools as llm.ToolContext;
732
+ this._tools = new llm.ToolContext(retainedEntries);
734
733
 
735
734
  unlock();
736
735
  }
@@ -738,26 +737,26 @@ export class RealtimeSession extends llm.RealtimeSession {
738
737
  private createToolsUpdateEvent(_tools: llm.ToolContext): api_proto.SessionUpdateEvent {
739
738
  const oaiTools: api_proto.Tool[] = [];
740
739
 
741
- for (const [name, tool] of Object.entries(_tools)) {
742
- if (!llm.isFunctionTool(tool)) {
743
- this.#logger.error({ name, tool }, "OpenAI Realtime API doesn't support this tool type");
744
- continue;
745
- }
740
+ for (const t of _tools.flatten()) {
741
+ // TODO: support provider tools in the Realtime session-update schema.
742
+ if (!llm.isFunctionTool(t)) continue;
746
743
 
747
- const { parameters: toolParameters, description } = tool;
748
744
  try {
749
745
  const parameters = llm.toJsonSchema(
750
- toolParameters,
746
+ t.parameters,
751
747
  ) as unknown as api_proto.Tool['parameters'];
752
748
 
753
749
  oaiTools.push({
754
- name,
755
- description,
750
+ name: t.name,
751
+ description: t.description,
756
752
  parameters: parameters,
757
753
  type: 'function',
758
754
  });
759
755
  } catch (e) {
760
- this.#logger.error({ name, tool }, "OpenAI Realtime API doesn't support this tool type");
756
+ this.#logger.error(
757
+ { name: t.name, tool: t },
758
+ "OpenAI Realtime API doesn't support this tool type",
759
+ );
761
760
  continue;
762
761
  }
763
762
  }
@@ -847,7 +846,18 @@ export class RealtimeSession extends llm.RealtimeSession {
847
846
  instructions?: string,
848
847
  options: { signal?: AbortSignal } = {},
849
848
  ): Promise<llm.GenerationCreatedEvent> {
850
- const handle = this.createResponse({ instructions, userInitiated: true });
849
+ // In OpenAI realtime, the session-level instructions are completely replaced by the
850
+ // per-response instructions for this response. Prepend the session instructions so they
851
+ // are preserved (parity with the Python implementation).
852
+ let responseInstructions = instructions;
853
+ if (instructions && this.instructions) {
854
+ responseInstructions = `${this.instructions}\n${instructions}`;
855
+ }
856
+
857
+ const handle = this.createResponse({
858
+ instructions: responseInstructions,
859
+ userInitiated: true,
860
+ });
851
861
  this.textModeRecoveryRetries = 0;
852
862
 
853
863
  const onAbort = () => {
@@ -1065,7 +1075,7 @@ export class RealtimeSession extends llm.RealtimeSession {
1065
1075
  events.push(this.createSessionUpdateEvent());
1066
1076
 
1067
1077
  // tools
1068
- if (Object.keys(this._tools).length > 0) {
1078
+ if (Object.keys(this._tools.functionTools).length > 0) {
1069
1079
  events.push(this.createToolsUpdateEvent(this._tools));
1070
1080
  }
1071
1081
 
@@ -12,7 +12,9 @@ import {
12
12
  toError,
13
13
  } from '@livekit/agents';
14
14
  import OpenAI from 'openai';
15
- import type { ChatModels } from '../models.js';
15
+ import type { ChatModels, Reasoning } from '../models.js';
16
+ import { defaultReasoningEffort } from '../models.js';
17
+ import { toResponsesTools } from '../tool_utils.js';
16
18
  import { WSLLM } from '../ws/llm.js';
17
19
 
18
20
  export interface LLMOptions {
@@ -30,6 +32,8 @@ export interface LLMOptions {
30
32
  serviceTier?: string;
31
33
  /** Upper bound for the number of tokens that can be generated for a response. */
32
34
  maxOutputTokens?: number;
35
+ /** Configuration options for reasoning models. */
36
+ reasoning?: Reasoning | null;
33
37
 
34
38
  /**
35
39
  * Whether to use the WebSocket API.
@@ -55,6 +59,13 @@ class ResponsesHttpLLM extends llm.LLM {
55
59
  super();
56
60
 
57
61
  this.#opts = { ...defaultLLMOptions, ...opts };
62
+ if (this.#opts.reasoning === undefined) {
63
+ const effort = defaultReasoningEffort(this.#opts.model);
64
+ if (effort !== undefined) {
65
+ this.#opts.reasoning = { effort };
66
+ }
67
+ }
68
+
58
69
  if (this.#opts.apiKey === undefined && this.#opts.client === undefined) {
59
70
  throw new Error('OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY');
60
71
  }
@@ -77,25 +88,30 @@ class ResponsesHttpLLM extends llm.LLM {
77
88
 
78
89
  override chat({
79
90
  chatCtx,
80
- toolCtx,
91
+ toolCtx: toolCtxInput,
81
92
  connOptions = DEFAULT_API_CONNECT_OPTIONS,
82
93
  parallelToolCalls,
83
94
  toolChoice,
84
95
  extraKwargs,
85
96
  }: {
86
97
  chatCtx: llm.ChatContext;
87
- toolCtx?: llm.ToolContext;
98
+ toolCtx?: llm.ToolContextLike;
88
99
  connOptions?: APIConnectOptions;
89
100
  parallelToolCalls?: boolean;
90
101
  toolChoice?: llm.ToolChoice;
91
102
  extraKwargs?: Record<string, unknown>;
92
103
  }): ResponsesHttpLLMStream {
104
+ const toolCtx = llm.toToolContext(toolCtxInput);
93
105
  const modelOptions: Record<string, unknown> = { ...(extraKwargs || {}) };
94
106
 
95
107
  parallelToolCalls =
96
108
  parallelToolCalls !== undefined ? parallelToolCalls : this.#opts.parallelToolCalls;
97
109
 
98
- if (toolCtx && Object.keys(toolCtx).length > 0 && parallelToolCalls !== undefined) {
110
+ if (
111
+ toolCtx &&
112
+ Object.keys(toolCtx.functionTools).length > 0 &&
113
+ parallelToolCalls !== undefined
114
+ ) {
99
115
  modelOptions.parallel_tool_calls = parallelToolCalls;
100
116
  }
101
117
 
@@ -126,6 +142,10 @@ class ResponsesHttpLLM extends llm.LLM {
126
142
  modelOptions.max_output_tokens = this.#opts.maxOutputTokens;
127
143
  }
128
144
 
145
+ if (this.#opts.reasoning !== undefined) {
146
+ modelOptions.reasoning = this.#opts.reasoning;
147
+ }
148
+
129
149
  return new ResponsesHttpLLMStream(this, {
130
150
  model: this.#opts.model,
131
151
  client: this.#client,
@@ -181,25 +201,9 @@ class ResponsesHttpLLMStream extends llm.LLMStream {
181
201
  'openai.responses',
182
202
  )) as OpenAI.Responses.ResponseInputItem[];
183
203
 
204
+ // TODO: support provider tools in the Responses schema.
184
205
  const tools = this.toolCtx
185
- ? llm.sortedToolEntries(this.toolCtx).map(([name, func]) => {
186
- const oaiParams = {
187
- type: 'function' as const,
188
- name: name,
189
- description: func.description,
190
- parameters: llm.toJsonSchema(
191
- func.parameters,
192
- true,
193
- this.strictToolSchema,
194
- ) as unknown as OpenAI.Responses.FunctionTool['parameters'],
195
- } as OpenAI.Responses.FunctionTool;
196
-
197
- if (this.strictToolSchema) {
198
- oaiParams.strict = true;
199
- }
200
-
201
- return oaiParams;
202
- })
206
+ ? toResponsesTools(this.toolCtx, this.strictToolSchema)
203
207
  : undefined;
204
208
 
205
209
  const requestOptions: Record<string, unknown> = { ...this.modelOptions };
@@ -430,7 +434,7 @@ export class LLM extends llm.LLM {
430
434
  extraKwargs,
431
435
  }: {
432
436
  chatCtx: llm.ChatContext;
433
- toolCtx?: llm.ToolContext;
437
+ toolCtx?: llm.ToolContextLike;
434
438
  connOptions?: APIConnectOptions;
435
439
  parallelToolCalls?: boolean;
436
440
  toolChoice?: llm.ToolChoice;
@@ -0,0 +1,84 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { llm } from '@livekit/agents';
5
+ import { describe, expect, it } from 'vitest';
6
+ import { z } from 'zod';
7
+ import { toResponsesTools } from './tool_utils.js';
8
+ import { CodeInterpreter, FileSearch, WebSearch } from './tools.js';
9
+
10
+ describe('toResponsesTools', () => {
11
+ it('serializes function tools', () => {
12
+ const fn = llm.tool({
13
+ name: 'lookup_weather',
14
+ description: 'Look up weather',
15
+ parameters: z.object({ city: z.string() }),
16
+ execute: async () => 'sunny',
17
+ });
18
+
19
+ expect(toResponsesTools(new llm.ToolContext([fn]), true)).toEqual([
20
+ {
21
+ type: 'function',
22
+ name: 'lookup_weather',
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
+ required: ['city'],
29
+ additionalProperties: false,
30
+ },
31
+ strict: true,
32
+ },
33
+ ]);
34
+ });
35
+
36
+ it('serializes OpenAI provider tools', () => {
37
+ const tools = toResponsesTools(
38
+ new llm.ToolContext([
39
+ new WebSearch({
40
+ filters: { allowed_domains: ['docs.livekit.io'] },
41
+ searchContextSize: 'low',
42
+ userLocation: { type: 'approximate', country: 'US' },
43
+ }),
44
+ new FileSearch({
45
+ vectorStoreIds: ['vs_123'],
46
+ maxNumResults: 3,
47
+ rankingOptions: { ranker: 'auto' },
48
+ }),
49
+ new CodeInterpreter({ container: { type: 'auto', file_ids: ['file_123'] } }),
50
+ ]),
51
+ false,
52
+ );
53
+
54
+ expect(tools).toEqual([
55
+ {
56
+ type: 'web_search',
57
+ search_context_size: 'low',
58
+ filters: { allowed_domains: ['docs.livekit.io'] },
59
+ user_location: { type: 'approximate', country: 'US' },
60
+ },
61
+ {
62
+ type: 'file_search',
63
+ vector_store_ids: ['vs_123'],
64
+ max_num_results: 3,
65
+ ranking_options: { ranker: 'auto' },
66
+ },
67
+ { type: 'code_interpreter', container: { type: 'auto', file_ids: ['file_123'] } },
68
+ ]);
69
+ });
70
+
71
+ it('omits the code interpreter container when unset', () => {
72
+ expect(toResponsesTools(new llm.ToolContext([new CodeInterpreter()]), false)).toEqual([
73
+ { type: 'code_interpreter' },
74
+ ]);
75
+ });
76
+
77
+ it('ignores non-OpenAI provider tools', () => {
78
+ class OtherProviderTool extends llm.ProviderTool {}
79
+
80
+ expect(
81
+ toResponsesTools(new llm.ToolContext([new OtherProviderTool({ id: 'other' })]), false),
82
+ ).toBeUndefined();
83
+ });
84
+ });
@@ -0,0 +1,46 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { llm } from '@livekit/agents';
5
+ import type OpenAI from 'openai';
6
+ import { OpenAITool } from './tools.js';
7
+
8
+ export function toResponsesTools(
9
+ toolCtx: llm.ToolContext,
10
+ strictToolSchema: boolean,
11
+ ): OpenAI.Responses.Tool[] | undefined {
12
+ // Function tools are emitted first, sorted by name for deterministic payloads; provider
13
+ // tools follow in registration order.
14
+ const functionTools = llm.sortedToolEntries(toolCtx).map(([name, tool]) => {
15
+ const oaiParams = {
16
+ type: 'function' as const,
17
+ name,
18
+ description: tool.description,
19
+ parameters: llm.toJsonSchema(
20
+ tool.parameters,
21
+ true,
22
+ strictToolSchema,
23
+ ) as unknown as OpenAI.Responses.FunctionTool['parameters'],
24
+ } as OpenAI.Responses.FunctionTool;
25
+
26
+ if (strictToolSchema) {
27
+ oaiParams.strict = true;
28
+ }
29
+
30
+ return oaiParams;
31
+ });
32
+
33
+ const providerTools = toolCtx
34
+ .flatten()
35
+ .filter((tool) => !llm.isFunctionTool(tool))
36
+ .map((tool) =>
37
+ tool instanceof OpenAITool
38
+ ? (tool.toToolConfig() as unknown as OpenAI.Responses.Tool)
39
+ : undefined,
40
+ )
41
+ .filter((tool): tool is OpenAI.Responses.Tool => tool !== undefined);
42
+
43
+ const tools = [...functionTools, ...providerTools];
44
+
45
+ return tools.length > 0 ? tools : undefined;
46
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,166 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { llm } from '@livekit/agents';
5
+ import type OpenAI from 'openai';
6
+
7
+ /** Base class for OpenAI Responses API provider tools. */
8
+ export abstract class OpenAITool extends llm.ProviderTool {
9
+ /** Convert this provider tool to the OpenAI Responses API tool configuration. */
10
+ abstract toToolConfig(): Record<string, unknown>;
11
+ }
12
+
13
+ /**
14
+ * High-level guidance for the amount of context window space to use for web search.
15
+ * OpenAI defaults this to `medium`.
16
+ */
17
+ export type WebSearchContextSize = 'low' | 'medium' | 'high';
18
+
19
+ /** Options for the OpenAI web search tool. */
20
+ export interface WebSearchOptions {
21
+ /**
22
+ * Filters for the search, such as allowed domains. If not provided, all domains are allowed.
23
+ */
24
+ filters?: OpenAI.Responses.WebSearchTool['filters'];
25
+
26
+ /**
27
+ * Amount of context window space to use for the search. Defaults to `medium`.
28
+ */
29
+ searchContextSize?: WebSearchContextSize | null;
30
+
31
+ /** Approximate location of the user, such as city, region, country, or timezone. */
32
+ userLocation?: OpenAI.Responses.WebSearchTool['user_location'];
33
+ }
34
+
35
+ /**
36
+ * Search the Internet for sources related to the prompt.
37
+ *
38
+ * @see https://platform.openai.com/docs/guides/tools-web-search
39
+ */
40
+ export class WebSearch extends OpenAITool {
41
+ /** Filters for the search, such as allowed domains. */
42
+ readonly filters: OpenAI.Responses.WebSearchTool['filters'] | undefined;
43
+
44
+ /** Amount of context window space to use for the search. */
45
+ readonly searchContextSize: WebSearchContextSize | null;
46
+
47
+ /** Approximate location of the user. */
48
+ readonly userLocation: OpenAI.Responses.WebSearchTool['user_location'] | undefined;
49
+
50
+ constructor({ filters, searchContextSize = 'medium', userLocation }: WebSearchOptions = {}) {
51
+ super({ id: 'openai_web_search' });
52
+ this.filters = filters;
53
+ this.searchContextSize = searchContextSize;
54
+ this.userLocation = userLocation;
55
+ }
56
+
57
+ toToolConfig(): Record<string, unknown> {
58
+ const result: Record<string, unknown> = {
59
+ type: 'web_search',
60
+ search_context_size: this.searchContextSize,
61
+ };
62
+ if (this.userLocation !== undefined) {
63
+ result.user_location = this.userLocation;
64
+ }
65
+ if (this.filters !== undefined) {
66
+ result.filters = this.filters;
67
+ }
68
+ return result;
69
+ }
70
+ }
71
+
72
+ /** Options for the OpenAI file search tool. */
73
+ export interface FileSearchOptions {
74
+ /** IDs of the vector stores to search. */
75
+ vectorStoreIds?: string[];
76
+
77
+ /** Filter to apply to file search results. */
78
+ filters?: OpenAI.Responses.FileSearchTool['filters'];
79
+
80
+ /** Maximum number of results to return. This should be between 1 and 50 inclusive. */
81
+ maxNumResults?: number;
82
+
83
+ /** Ranking options for search, including ranker and score threshold. */
84
+ rankingOptions?: OpenAI.Responses.FileSearchTool.RankingOptions;
85
+ }
86
+
87
+ /**
88
+ * Search for relevant content from uploaded files.
89
+ *
90
+ * @see https://platform.openai.com/docs/guides/tools-file-search
91
+ */
92
+ export class FileSearch extends OpenAITool {
93
+ /** IDs of the vector stores to search. */
94
+ readonly vectorStoreIds: string[];
95
+
96
+ /** Filter to apply to file search results. */
97
+ readonly filters: OpenAI.Responses.FileSearchTool['filters'] | undefined;
98
+
99
+ /** Maximum number of results to return. */
100
+ readonly maxNumResults: number | undefined;
101
+
102
+ /** Ranking options for search. */
103
+ readonly rankingOptions: OpenAI.Responses.FileSearchTool.RankingOptions | undefined;
104
+
105
+ constructor({
106
+ vectorStoreIds = [],
107
+ filters,
108
+ maxNumResults,
109
+ rankingOptions,
110
+ }: FileSearchOptions = {}) {
111
+ super({ id: 'openai_file_search' });
112
+ this.vectorStoreIds = [...vectorStoreIds];
113
+ this.filters = filters;
114
+ this.maxNumResults = maxNumResults;
115
+ this.rankingOptions = rankingOptions;
116
+ }
117
+
118
+ toToolConfig(): Record<string, unknown> {
119
+ const result: Record<string, unknown> = {
120
+ type: 'file_search',
121
+ vector_store_ids: this.vectorStoreIds,
122
+ };
123
+ if (this.filters !== undefined) {
124
+ result.filters = this.filters;
125
+ }
126
+ if (this.maxNumResults !== undefined) {
127
+ result.max_num_results = this.maxNumResults;
128
+ }
129
+ if (this.rankingOptions !== undefined) {
130
+ result.ranking_options = this.rankingOptions;
131
+ }
132
+ return result;
133
+ }
134
+ }
135
+
136
+ /** Options for the OpenAI code interpreter tool. */
137
+ export interface CodeInterpreterOptions {
138
+ /**
139
+ * Code interpreter container. Can be a container ID or an object that specifies uploaded file IDs
140
+ * to make available to the code.
141
+ */
142
+ container?: OpenAI.Responses.Tool.CodeInterpreter['container'] | null;
143
+ }
144
+
145
+ /**
146
+ * Run Python code to help generate a response to a prompt.
147
+ *
148
+ * @see https://platform.openai.com/docs/guides/tools-code-interpreter
149
+ */
150
+ export class CodeInterpreter extends OpenAITool {
151
+ /** Code interpreter container ID or configuration. */
152
+ readonly container: OpenAI.Responses.Tool.CodeInterpreter['container'] | null;
153
+
154
+ constructor({ container = null }: CodeInterpreterOptions = {}) {
155
+ super({ id: 'openai_code_interpreter' });
156
+ this.container = container;
157
+ }
158
+
159
+ toToolConfig(): Record<string, unknown> {
160
+ const result: Record<string, unknown> = { type: 'code_interpreter' };
161
+ if (this.container !== null) {
162
+ result.container = this.container;
163
+ }
164
+ return result;
165
+ }
166
+ }
package/src/ws/llm.ts CHANGED
@@ -14,7 +14,9 @@ import {
14
14
  } from '@livekit/agents';
15
15
  import type OpenAI from 'openai';
16
16
  import { WebSocket } from 'ws';
17
- import type { ChatModels } from '../models.js';
17
+ import type { ChatModels, Reasoning } from '../models.js';
18
+ import { defaultReasoningEffort } from '../models.js';
19
+ import { toResponsesTools } from '../tool_utils.js';
18
20
  import type {
19
21
  WsOutputItemDoneEvent,
20
22
  WsOutputTextDeltaEvent,
@@ -169,6 +171,8 @@ export interface WSLLMOptions {
169
171
  serviceTier?: string;
170
172
  /** Upper bound for the number of tokens that can be generated for a response. */
171
173
  maxOutputTokens?: number;
174
+ /** Configuration options for reasoning models. */
175
+ reasoning?: Reasoning | null;
172
176
  }
173
177
 
174
178
  const defaultLLMOptions: WSLLMOptions = {
@@ -203,6 +207,13 @@ export class WSLLM extends llm.LLM {
203
207
  super();
204
208
 
205
209
  this.#opts = { ...defaultLLMOptions, ...opts };
210
+ if (this.#opts.reasoning === undefined) {
211
+ const effort = defaultReasoningEffort(this.#opts.model);
212
+ if (effort !== undefined) {
213
+ this.#opts.reasoning = { effort };
214
+ }
215
+ }
216
+
206
217
  if (!this.#opts.apiKey) {
207
218
  throw new Error('OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY');
208
219
  }
@@ -253,24 +264,29 @@ export class WSLLM extends llm.LLM {
253
264
 
254
265
  chat({
255
266
  chatCtx,
256
- toolCtx,
267
+ toolCtx: toolCtxInput,
257
268
  connOptions = DEFAULT_API_CONNECT_OPTIONS,
258
269
  parallelToolCalls,
259
270
  toolChoice,
260
271
  extraKwargs,
261
272
  }: {
262
273
  chatCtx: llm.ChatContext;
263
- toolCtx?: llm.ToolContext;
274
+ toolCtx?: llm.ToolContextLike;
264
275
  connOptions?: APIConnectOptions;
265
276
  parallelToolCalls?: boolean;
266
277
  toolChoice?: llm.ToolChoice;
267
278
  extraKwargs?: Record<string, unknown>;
268
279
  }): WSLLMStream {
280
+ const toolCtx = llm.toToolContext(toolCtxInput);
269
281
  const modelOptions: Record<string, unknown> = { ...(extraKwargs ?? {}) };
270
282
 
271
283
  parallelToolCalls =
272
284
  parallelToolCalls !== undefined ? parallelToolCalls : this.#opts.parallelToolCalls;
273
- if (toolCtx && Object.keys(toolCtx).length > 0 && parallelToolCalls !== undefined) {
285
+ if (
286
+ toolCtx &&
287
+ Object.keys(toolCtx.functionTools).length > 0 &&
288
+ parallelToolCalls !== undefined
289
+ ) {
274
290
  modelOptions.parallel_tool_calls = parallelToolCalls;
275
291
  }
276
292
 
@@ -300,6 +316,10 @@ export class WSLLM extends llm.LLM {
300
316
  modelOptions.max_output_tokens = this.#opts.maxOutputTokens;
301
317
  }
302
318
 
319
+ if (this.#opts.reasoning !== undefined) {
320
+ modelOptions.reasoning = this.#opts.reasoning;
321
+ }
322
+
303
323
  let inputChatCtx = chatCtx;
304
324
  let prevResponseId: string | undefined;
305
325
  const canUseStoredResponse = modelOptions.store !== false;
@@ -446,26 +466,7 @@ export class WSLLMStream extends llm.LLMStream {
446
466
  'openai.responses',
447
467
  )) as OpenAI.Responses.ResponseInputItem[];
448
468
 
449
- const tools = this.toolCtx
450
- ? llm.sortedToolEntries(this.toolCtx).map(([name, func]) => {
451
- const oaiParams = {
452
- type: 'function' as const,
453
- name,
454
- description: func.description,
455
- parameters: llm.toJsonSchema(
456
- func.parameters,
457
- true,
458
- this.#strictToolSchema,
459
- ) as unknown as OpenAI.Responses.FunctionTool['parameters'],
460
- } as OpenAI.Responses.FunctionTool;
461
-
462
- if (this.#strictToolSchema) {
463
- oaiParams.strict = true;
464
- }
465
-
466
- return oaiParams;
467
- })
468
- : undefined;
469
+ const tools = this.toolCtx ? toResponsesTools(this.toolCtx, this.#strictToolSchema) : undefined;
469
470
 
470
471
  const requestOptions: Record<string, unknown> = { ...this.#modelOptions };
471
472
  if (!tools) {