@llmrtc/llmrtc-provider-openai 1.0.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.
- package/LICENSE +201 -0
- package/README.md +51 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +294 -0
- package/dist/index.js.map +1 -0
- package/dist/tool-adapter.d.ts +58 -0
- package/dist/tool-adapter.js +122 -0
- package/dist/tool-adapter.js.map +1 -0
- package/package.json +37 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# @llmrtc/llmrtc-provider-openai
|
|
2
|
+
|
|
3
|
+
OpenAI LLM, STT (Whisper), and TTS providers for LLMRTC.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @llmrtc/llmrtc-provider-openai
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Providers
|
|
12
|
+
|
|
13
|
+
### LLM
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { OpenAILLMProvider } from '@llmrtc/llmrtc-provider-openai';
|
|
17
|
+
|
|
18
|
+
const llm = new OpenAILLMProvider({
|
|
19
|
+
apiKey: process.env.OPENAI_API_KEY!,
|
|
20
|
+
model: 'gpt-4o'
|
|
21
|
+
});
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
### STT (Whisper)
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
import { OpenAIWhisperProvider } from '@llmrtc/llmrtc-provider-openai';
|
|
28
|
+
|
|
29
|
+
const stt = new OpenAIWhisperProvider({
|
|
30
|
+
apiKey: process.env.OPENAI_API_KEY!
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### TTS
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
import { OpenAITTSProvider } from '@llmrtc/llmrtc-provider-openai';
|
|
38
|
+
|
|
39
|
+
const tts = new OpenAITTSProvider({
|
|
40
|
+
apiKey: process.env.OPENAI_API_KEY!,
|
|
41
|
+
voice: 'alloy'
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Documentation
|
|
46
|
+
|
|
47
|
+
Full documentation: [https://www.llmrtc.org](https://www.llmrtc.org)
|
|
48
|
+
|
|
49
|
+
## License
|
|
50
|
+
|
|
51
|
+
Apache-2.0
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { LLMChunk, LLMProvider, LLMRequest, LLMResult, STTProvider, STTResult, TTSProvider, TTSConfig, TTSResult } from '@llmrtc/llmrtc-core';
|
|
2
|
+
export interface OpenAILLMConfig {
|
|
3
|
+
apiKey: string;
|
|
4
|
+
baseURL?: string;
|
|
5
|
+
model?: string;
|
|
6
|
+
}
|
|
7
|
+
export declare class OpenAILLMProvider implements LLMProvider {
|
|
8
|
+
private readonly config;
|
|
9
|
+
readonly name = "openai-llm";
|
|
10
|
+
private client;
|
|
11
|
+
private model;
|
|
12
|
+
constructor(config: OpenAILLMConfig);
|
|
13
|
+
complete(request: LLMRequest): Promise<LLMResult>;
|
|
14
|
+
stream(request: LLMRequest): AsyncIterable<LLMChunk>;
|
|
15
|
+
}
|
|
16
|
+
export interface OpenAIWhisperConfig {
|
|
17
|
+
apiKey: string;
|
|
18
|
+
baseURL?: string;
|
|
19
|
+
model?: string;
|
|
20
|
+
language?: string;
|
|
21
|
+
}
|
|
22
|
+
export declare class OpenAIWhisperProvider implements STTProvider {
|
|
23
|
+
readonly name = "openai-whisper";
|
|
24
|
+
private client;
|
|
25
|
+
private model;
|
|
26
|
+
private language?;
|
|
27
|
+
constructor(config: OpenAIWhisperConfig);
|
|
28
|
+
transcribe(audio: Buffer): Promise<STTResult>;
|
|
29
|
+
}
|
|
30
|
+
export type OpenAITTSVoice = 'alloy' | 'echo' | 'fable' | 'onyx' | 'nova' | 'shimmer';
|
|
31
|
+
export type OpenAITTSFormat = 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm';
|
|
32
|
+
export interface OpenAITTSConfig {
|
|
33
|
+
/** OpenAI API key */
|
|
34
|
+
apiKey: string;
|
|
35
|
+
/** Base URL for API (optional, for Azure OpenAI or proxies) */
|
|
36
|
+
baseURL?: string;
|
|
37
|
+
/** TTS model (default: 'tts-1') */
|
|
38
|
+
model?: 'tts-1' | 'tts-1-hd' | 'gpt-4o-mini-tts';
|
|
39
|
+
/** Default voice (default: 'alloy') */
|
|
40
|
+
voice?: OpenAITTSVoice;
|
|
41
|
+
/** Speech speed multiplier 0.25-4.0 (default: 1.0) */
|
|
42
|
+
speed?: number;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* OpenAI Text-to-Speech Provider.
|
|
46
|
+
*
|
|
47
|
+
* Available voices: alloy, echo, fable, onyx, nova, shimmer
|
|
48
|
+
* Available models: tts-1 (fast), tts-1-hd (quality), gpt-4o-mini-tts (instructable)
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```typescript
|
|
52
|
+
* const provider = new OpenAITTSProvider({
|
|
53
|
+
* apiKey: 'sk-...',
|
|
54
|
+
* model: 'tts-1',
|
|
55
|
+
* voice: 'nova'
|
|
56
|
+
* });
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export declare class OpenAITTSProvider implements TTSProvider {
|
|
60
|
+
private readonly config;
|
|
61
|
+
readonly name = "openai-tts";
|
|
62
|
+
private client;
|
|
63
|
+
private model;
|
|
64
|
+
private voice;
|
|
65
|
+
private speed;
|
|
66
|
+
constructor(config: OpenAITTSConfig);
|
|
67
|
+
speak(text: string, overrideConfig?: TTSConfig): Promise<TTSResult>;
|
|
68
|
+
/**
|
|
69
|
+
* Streaming TTS - returns audio chunks as they are generated.
|
|
70
|
+
* Uses HTTP chunked transfer encoding.
|
|
71
|
+
*
|
|
72
|
+
* When using format: 'pcm', output is 24kHz, 16-bit signed LE, mono.
|
|
73
|
+
* This is the recommended format for lowest latency (no decode step needed).
|
|
74
|
+
*/
|
|
75
|
+
speakStream(text: string, overrideConfig?: TTSConfig): AsyncIterable<Buffer>;
|
|
76
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import OpenAI, { toFile } from 'openai';
|
|
2
|
+
import { mapToolsToOpenAI, mapToolChoiceToOpenAI, parseToolCallsFromOpenAI, mapStopReasonFromOpenAI, processToolCallDelta, finalizeToolCalls, } from './tool-adapter.js';
|
|
3
|
+
export class OpenAILLMProvider {
|
|
4
|
+
constructor(config) {
|
|
5
|
+
Object.defineProperty(this, "config", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
configurable: true,
|
|
8
|
+
writable: true,
|
|
9
|
+
value: config
|
|
10
|
+
});
|
|
11
|
+
Object.defineProperty(this, "name", {
|
|
12
|
+
enumerable: true,
|
|
13
|
+
configurable: true,
|
|
14
|
+
writable: true,
|
|
15
|
+
value: 'openai-llm'
|
|
16
|
+
});
|
|
17
|
+
Object.defineProperty(this, "client", {
|
|
18
|
+
enumerable: true,
|
|
19
|
+
configurable: true,
|
|
20
|
+
writable: true,
|
|
21
|
+
value: void 0
|
|
22
|
+
});
|
|
23
|
+
Object.defineProperty(this, "model", {
|
|
24
|
+
enumerable: true,
|
|
25
|
+
configurable: true,
|
|
26
|
+
writable: true,
|
|
27
|
+
value: void 0
|
|
28
|
+
});
|
|
29
|
+
this.client = new OpenAI({ apiKey: config.apiKey, baseURL: config.baseURL });
|
|
30
|
+
this.model = config.model ?? 'gpt-4o-mini';
|
|
31
|
+
}
|
|
32
|
+
async complete(request) {
|
|
33
|
+
const completion = await this.client.chat.completions.create({
|
|
34
|
+
model: this.model,
|
|
35
|
+
messages: mapMessages(request.messages),
|
|
36
|
+
temperature: request.config?.temperature,
|
|
37
|
+
top_p: request.config?.topP,
|
|
38
|
+
max_tokens: request.config?.maxTokens,
|
|
39
|
+
stream: false,
|
|
40
|
+
...(request.tools?.length && {
|
|
41
|
+
tools: mapToolsToOpenAI(request.tools),
|
|
42
|
+
tool_choice: mapToolChoiceToOpenAI(request.toolChoice),
|
|
43
|
+
}),
|
|
44
|
+
});
|
|
45
|
+
const choice = completion.choices?.[0];
|
|
46
|
+
const fullText = choice?.message?.content ?? '';
|
|
47
|
+
const toolCalls = parseToolCallsFromOpenAI(choice?.message?.tool_calls);
|
|
48
|
+
const stopReason = mapStopReasonFromOpenAI(choice?.finish_reason);
|
|
49
|
+
return { fullText, raw: completion, toolCalls, stopReason };
|
|
50
|
+
}
|
|
51
|
+
async *stream(request) {
|
|
52
|
+
const stream = await this.client.chat.completions.create({
|
|
53
|
+
model: this.model,
|
|
54
|
+
messages: mapMessages(request.messages),
|
|
55
|
+
temperature: request.config?.temperature,
|
|
56
|
+
top_p: request.config?.topP,
|
|
57
|
+
max_tokens: request.config?.maxTokens,
|
|
58
|
+
stream: true,
|
|
59
|
+
...(request.tools?.length && {
|
|
60
|
+
tools: mapToolsToOpenAI(request.tools),
|
|
61
|
+
tool_choice: mapToolChoiceToOpenAI(request.toolChoice),
|
|
62
|
+
}),
|
|
63
|
+
});
|
|
64
|
+
// Accumulate tool calls across streaming chunks
|
|
65
|
+
const toolCallAccumulators = new Map();
|
|
66
|
+
let finishReason = null;
|
|
67
|
+
for await (const part of stream) {
|
|
68
|
+
const choice = part.choices?.[0];
|
|
69
|
+
const delta = choice?.delta;
|
|
70
|
+
// Accumulate tool call deltas
|
|
71
|
+
if (delta?.tool_calls) {
|
|
72
|
+
for (const toolCallDelta of delta.tool_calls) {
|
|
73
|
+
processToolCallDelta(toolCallAccumulators, toolCallDelta);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
// Track finish reason
|
|
77
|
+
if (choice?.finish_reason) {
|
|
78
|
+
finishReason = choice.finish_reason;
|
|
79
|
+
}
|
|
80
|
+
// Yield content delta
|
|
81
|
+
const content = delta?.content ?? '';
|
|
82
|
+
yield { content, done: false, raw: part };
|
|
83
|
+
}
|
|
84
|
+
// Final chunk with accumulated tool calls
|
|
85
|
+
const toolCalls = toolCallAccumulators.size > 0
|
|
86
|
+
? finalizeToolCalls(toolCallAccumulators)
|
|
87
|
+
: undefined;
|
|
88
|
+
const stopReason = mapStopReasonFromOpenAI(finishReason);
|
|
89
|
+
yield { content: '', done: true, toolCalls, stopReason };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export class OpenAIWhisperProvider {
|
|
93
|
+
constructor(config) {
|
|
94
|
+
Object.defineProperty(this, "name", {
|
|
95
|
+
enumerable: true,
|
|
96
|
+
configurable: true,
|
|
97
|
+
writable: true,
|
|
98
|
+
value: 'openai-whisper'
|
|
99
|
+
});
|
|
100
|
+
Object.defineProperty(this, "client", {
|
|
101
|
+
enumerable: true,
|
|
102
|
+
configurable: true,
|
|
103
|
+
writable: true,
|
|
104
|
+
value: void 0
|
|
105
|
+
});
|
|
106
|
+
Object.defineProperty(this, "model", {
|
|
107
|
+
enumerable: true,
|
|
108
|
+
configurable: true,
|
|
109
|
+
writable: true,
|
|
110
|
+
value: void 0
|
|
111
|
+
});
|
|
112
|
+
Object.defineProperty(this, "language", {
|
|
113
|
+
enumerable: true,
|
|
114
|
+
configurable: true,
|
|
115
|
+
writable: true,
|
|
116
|
+
value: void 0
|
|
117
|
+
});
|
|
118
|
+
this.client = new OpenAI({ apiKey: config.apiKey, baseURL: config.baseURL });
|
|
119
|
+
this.model = config.model ?? 'whisper-1';
|
|
120
|
+
this.language = config.language;
|
|
121
|
+
}
|
|
122
|
+
async transcribe(audio) {
|
|
123
|
+
// Use OpenAI SDK's toFile helper for cross-platform compatibility
|
|
124
|
+
const file = await toFile(audio, 'audio.webm', { type: 'audio/webm' });
|
|
125
|
+
const res = await this.client.audio.transcriptions.create({
|
|
126
|
+
file: file,
|
|
127
|
+
model: this.model,
|
|
128
|
+
language: this.language
|
|
129
|
+
});
|
|
130
|
+
return { text: res.text ?? '', isFinal: true, raw: res };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function mapMessages(messages) {
|
|
134
|
+
return messages.map((m) => {
|
|
135
|
+
// Handle tool result messages
|
|
136
|
+
if (m.role === 'tool') {
|
|
137
|
+
return {
|
|
138
|
+
role: 'tool',
|
|
139
|
+
content: m.content,
|
|
140
|
+
tool_call_id: m.toolCallId ?? '',
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
// Handle assistant messages (may contain tool_calls reference for context)
|
|
144
|
+
if (m.role === 'assistant') {
|
|
145
|
+
const assistantMsg = {
|
|
146
|
+
role: 'assistant',
|
|
147
|
+
content: m.content || null,
|
|
148
|
+
};
|
|
149
|
+
// Include tool_calls if present (required for tool result messages to work)
|
|
150
|
+
if (m.toolCalls?.length) {
|
|
151
|
+
assistantMsg.tool_calls = m.toolCalls.map(tc => ({
|
|
152
|
+
id: tc.callId,
|
|
153
|
+
type: 'function',
|
|
154
|
+
function: {
|
|
155
|
+
name: tc.name,
|
|
156
|
+
arguments: JSON.stringify(tc.arguments),
|
|
157
|
+
},
|
|
158
|
+
}));
|
|
159
|
+
}
|
|
160
|
+
return assistantMsg;
|
|
161
|
+
}
|
|
162
|
+
// Handle system and user messages
|
|
163
|
+
if (!m.attachments?.length) {
|
|
164
|
+
return { role: m.role, content: m.content };
|
|
165
|
+
}
|
|
166
|
+
const imageParts = m.attachments.map((att) => ({ type: 'image_url', image_url: { url: att.data } }));
|
|
167
|
+
return { role: m.role, content: [{ type: 'text', text: m.content }, ...imageParts] };
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* OpenAI Text-to-Speech Provider.
|
|
172
|
+
*
|
|
173
|
+
* Available voices: alloy, echo, fable, onyx, nova, shimmer
|
|
174
|
+
* Available models: tts-1 (fast), tts-1-hd (quality), gpt-4o-mini-tts (instructable)
|
|
175
|
+
*
|
|
176
|
+
* @example
|
|
177
|
+
* ```typescript
|
|
178
|
+
* const provider = new OpenAITTSProvider({
|
|
179
|
+
* apiKey: 'sk-...',
|
|
180
|
+
* model: 'tts-1',
|
|
181
|
+
* voice: 'nova'
|
|
182
|
+
* });
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
export class OpenAITTSProvider {
|
|
186
|
+
constructor(config) {
|
|
187
|
+
Object.defineProperty(this, "config", {
|
|
188
|
+
enumerable: true,
|
|
189
|
+
configurable: true,
|
|
190
|
+
writable: true,
|
|
191
|
+
value: config
|
|
192
|
+
});
|
|
193
|
+
Object.defineProperty(this, "name", {
|
|
194
|
+
enumerable: true,
|
|
195
|
+
configurable: true,
|
|
196
|
+
writable: true,
|
|
197
|
+
value: 'openai-tts'
|
|
198
|
+
});
|
|
199
|
+
Object.defineProperty(this, "client", {
|
|
200
|
+
enumerable: true,
|
|
201
|
+
configurable: true,
|
|
202
|
+
writable: true,
|
|
203
|
+
value: void 0
|
|
204
|
+
});
|
|
205
|
+
Object.defineProperty(this, "model", {
|
|
206
|
+
enumerable: true,
|
|
207
|
+
configurable: true,
|
|
208
|
+
writable: true,
|
|
209
|
+
value: void 0
|
|
210
|
+
});
|
|
211
|
+
Object.defineProperty(this, "voice", {
|
|
212
|
+
enumerable: true,
|
|
213
|
+
configurable: true,
|
|
214
|
+
writable: true,
|
|
215
|
+
value: void 0
|
|
216
|
+
});
|
|
217
|
+
Object.defineProperty(this, "speed", {
|
|
218
|
+
enumerable: true,
|
|
219
|
+
configurable: true,
|
|
220
|
+
writable: true,
|
|
221
|
+
value: void 0
|
|
222
|
+
});
|
|
223
|
+
this.client = new OpenAI({ apiKey: config.apiKey, baseURL: config.baseURL });
|
|
224
|
+
this.model = config.model ?? 'tts-1';
|
|
225
|
+
this.voice = config.voice ?? 'alloy';
|
|
226
|
+
this.speed = config.speed ?? 1.0;
|
|
227
|
+
}
|
|
228
|
+
async speak(text, overrideConfig) {
|
|
229
|
+
const voice = overrideConfig?.voice ?? this.voice;
|
|
230
|
+
const format = mapFormat(overrideConfig?.format);
|
|
231
|
+
const response = await this.client.audio.speech.create({
|
|
232
|
+
model: this.model,
|
|
233
|
+
voice,
|
|
234
|
+
input: text,
|
|
235
|
+
response_format: format,
|
|
236
|
+
speed: this.speed
|
|
237
|
+
});
|
|
238
|
+
const buffer = Buffer.from(await response.arrayBuffer());
|
|
239
|
+
return {
|
|
240
|
+
audio: buffer,
|
|
241
|
+
format: overrideConfig?.format ?? 'mp3',
|
|
242
|
+
raw: response
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Streaming TTS - returns audio chunks as they are generated.
|
|
247
|
+
* Uses HTTP chunked transfer encoding.
|
|
248
|
+
*
|
|
249
|
+
* When using format: 'pcm', output is 24kHz, 16-bit signed LE, mono.
|
|
250
|
+
* This is the recommended format for lowest latency (no decode step needed).
|
|
251
|
+
*/
|
|
252
|
+
async *speakStream(text, overrideConfig) {
|
|
253
|
+
const voice = overrideConfig?.voice ?? this.voice;
|
|
254
|
+
const format = mapFormat(overrideConfig?.format);
|
|
255
|
+
const response = await this.client.audio.speech.create({
|
|
256
|
+
model: this.model,
|
|
257
|
+
voice,
|
|
258
|
+
input: text,
|
|
259
|
+
response_format: format,
|
|
260
|
+
speed: this.speed
|
|
261
|
+
});
|
|
262
|
+
// Response is a Response-like object with body stream
|
|
263
|
+
const reader = response.body?.getReader();
|
|
264
|
+
if (!reader) {
|
|
265
|
+
// Fallback: return the whole buffer if streaming not available
|
|
266
|
+
const buffer = Buffer.from(await response.arrayBuffer());
|
|
267
|
+
yield buffer;
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
while (true) {
|
|
271
|
+
const { done, value } = await reader.read();
|
|
272
|
+
if (done)
|
|
273
|
+
break;
|
|
274
|
+
yield Buffer.from(value);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Map core format to OpenAI format
|
|
280
|
+
*/
|
|
281
|
+
function mapFormat(format) {
|
|
282
|
+
switch (format) {
|
|
283
|
+
case 'ogg':
|
|
284
|
+
return 'opus'; // OpenAI uses 'opus' for Ogg container
|
|
285
|
+
case 'wav':
|
|
286
|
+
return 'wav';
|
|
287
|
+
case 'pcm':
|
|
288
|
+
return 'pcm';
|
|
289
|
+
case 'mp3':
|
|
290
|
+
default:
|
|
291
|
+
return 'mp3';
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAkBxC,OAAO,EACL,gBAAgB,EAChB,qBAAqB,EACrB,wBAAwB,EACxB,uBAAuB,EACvB,oBAAoB,EACpB,iBAAiB,GAElB,MAAM,mBAAmB,CAAC;AAQ3B,MAAM,OAAO,iBAAiB;IAK5B,YAA6B,MAAuB;QAAxC;;;;mBAAiB,MAAM;WAAiB;QAJ3C;;;;mBAAO,YAAY;WAAC;QACrB;;;;;WAAe;QACf;;;;;WAAc;QAGpB,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;QAC7E,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,aAAa,CAAC;IAC7C,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,OAAmB;QAChC,MAAM,UAAU,GAAG,MAAM,IAAI,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ACf,KAAK,KAAK,CAAC;QACX;YACE,OAAO,KAAK,CAAC;IACjB,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Tool Adapter
|
|
3
|
+
*
|
|
4
|
+
* Converts provider-agnostic tool definitions to OpenAI's format and
|
|
5
|
+
* parses tool calls from OpenAI responses.
|
|
6
|
+
*/
|
|
7
|
+
import type { ChatCompletionTool, ChatCompletionToolChoiceOption } from 'openai/resources/chat/completions';
|
|
8
|
+
import type { ToolDefinition, ToolCallRequest, ToolChoice } from '@llmrtc/llmrtc-core';
|
|
9
|
+
/**
|
|
10
|
+
* Convert provider-agnostic tool definitions to OpenAI format
|
|
11
|
+
*/
|
|
12
|
+
export declare function mapToolsToOpenAI(tools: ToolDefinition[]): ChatCompletionTool[];
|
|
13
|
+
/**
|
|
14
|
+
* Convert provider-agnostic tool choice to OpenAI format
|
|
15
|
+
*/
|
|
16
|
+
export declare function mapToolChoiceToOpenAI(choice?: ToolChoice): ChatCompletionToolChoiceOption | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* Parse tool calls from OpenAI response
|
|
19
|
+
*/
|
|
20
|
+
export declare function parseToolCallsFromOpenAI(toolCalls?: Array<{
|
|
21
|
+
id: string;
|
|
22
|
+
type: 'function';
|
|
23
|
+
function: {
|
|
24
|
+
name: string;
|
|
25
|
+
arguments: string;
|
|
26
|
+
};
|
|
27
|
+
}>): ToolCallRequest[] | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Accumulate streaming tool call deltas
|
|
30
|
+
*/
|
|
31
|
+
export interface StreamingToolCallAccumulator {
|
|
32
|
+
/** Tool call ID */
|
|
33
|
+
id: string;
|
|
34
|
+
/** Tool name */
|
|
35
|
+
name: string;
|
|
36
|
+
/** Accumulated arguments string */
|
|
37
|
+
arguments: string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Process a streaming delta and update accumulators
|
|
41
|
+
*/
|
|
42
|
+
export declare function processToolCallDelta(accumulators: Map<number, StreamingToolCallAccumulator>, delta: {
|
|
43
|
+
index: number;
|
|
44
|
+
id?: string;
|
|
45
|
+
type?: 'function';
|
|
46
|
+
function?: {
|
|
47
|
+
name?: string;
|
|
48
|
+
arguments?: string;
|
|
49
|
+
};
|
|
50
|
+
}): void;
|
|
51
|
+
/**
|
|
52
|
+
* Finalize accumulated tool calls
|
|
53
|
+
*/
|
|
54
|
+
export declare function finalizeToolCalls(accumulators: Map<number, StreamingToolCallAccumulator>): ToolCallRequest[];
|
|
55
|
+
/**
|
|
56
|
+
* Map stop reason from OpenAI to provider-agnostic format
|
|
57
|
+
*/
|
|
58
|
+
export declare function mapStopReasonFromOpenAI(finishReason: string | null | undefined): 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | undefined;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Tool Adapter
|
|
3
|
+
*
|
|
4
|
+
* Converts provider-agnostic tool definitions to OpenAI's format and
|
|
5
|
+
* parses tool calls from OpenAI responses.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Convert provider-agnostic tool definitions to OpenAI format
|
|
9
|
+
*/
|
|
10
|
+
export function mapToolsToOpenAI(tools) {
|
|
11
|
+
return tools.map(tool => ({
|
|
12
|
+
type: 'function',
|
|
13
|
+
function: {
|
|
14
|
+
name: tool.name,
|
|
15
|
+
description: tool.description,
|
|
16
|
+
parameters: tool.parameters,
|
|
17
|
+
},
|
|
18
|
+
}));
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Convert provider-agnostic tool choice to OpenAI format
|
|
22
|
+
*/
|
|
23
|
+
export function mapToolChoiceToOpenAI(choice) {
|
|
24
|
+
if (!choice)
|
|
25
|
+
return undefined;
|
|
26
|
+
if (typeof choice === 'string') {
|
|
27
|
+
switch (choice) {
|
|
28
|
+
case 'auto':
|
|
29
|
+
return 'auto';
|
|
30
|
+
case 'none':
|
|
31
|
+
return 'none';
|
|
32
|
+
case 'required':
|
|
33
|
+
return 'required';
|
|
34
|
+
default:
|
|
35
|
+
return 'auto';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// Force specific tool
|
|
39
|
+
return {
|
|
40
|
+
type: 'function',
|
|
41
|
+
function: { name: choice.name },
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Parse tool calls from OpenAI response
|
|
46
|
+
*/
|
|
47
|
+
export function parseToolCallsFromOpenAI(toolCalls) {
|
|
48
|
+
if (!toolCalls || toolCalls.length === 0) {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
return toolCalls.map(call => ({
|
|
52
|
+
callId: call.id,
|
|
53
|
+
name: call.function.name,
|
|
54
|
+
arguments: safeParseJSON(call.function.arguments),
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Process a streaming delta and update accumulators
|
|
59
|
+
*/
|
|
60
|
+
export function processToolCallDelta(accumulators, delta) {
|
|
61
|
+
const { index, id, function: fn } = delta;
|
|
62
|
+
if (!accumulators.has(index)) {
|
|
63
|
+
accumulators.set(index, {
|
|
64
|
+
id: id ?? '',
|
|
65
|
+
name: fn?.name ?? '',
|
|
66
|
+
arguments: '',
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
const accumulator = accumulators.get(index);
|
|
70
|
+
if (id) {
|
|
71
|
+
accumulator.id = id;
|
|
72
|
+
}
|
|
73
|
+
if (fn?.name) {
|
|
74
|
+
accumulator.name = fn.name;
|
|
75
|
+
}
|
|
76
|
+
if (fn?.arguments) {
|
|
77
|
+
accumulator.arguments += fn.arguments;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Finalize accumulated tool calls
|
|
82
|
+
*/
|
|
83
|
+
export function finalizeToolCalls(accumulators) {
|
|
84
|
+
const calls = [];
|
|
85
|
+
for (const [_, acc] of Array.from(accumulators.entries()).sort(([a], [b]) => a - b)) {
|
|
86
|
+
calls.push({
|
|
87
|
+
callId: acc.id,
|
|
88
|
+
name: acc.name,
|
|
89
|
+
arguments: safeParseJSON(acc.arguments),
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return calls;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Safely parse JSON, returning empty object on failure
|
|
96
|
+
*/
|
|
97
|
+
function safeParseJSON(str) {
|
|
98
|
+
try {
|
|
99
|
+
return JSON.parse(str);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return {};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Map stop reason from OpenAI to provider-agnostic format
|
|
107
|
+
*/
|
|
108
|
+
export function mapStopReasonFromOpenAI(finishReason) {
|
|
109
|
+
switch (finishReason) {
|
|
110
|
+
case 'stop':
|
|
111
|
+
return 'end_turn';
|
|
112
|
+
case 'tool_calls':
|
|
113
|
+
return 'tool_use';
|
|
114
|
+
case 'length':
|
|
115
|
+
return 'max_tokens';
|
|
116
|
+
case 'content_filter':
|
|
117
|
+
return 'stop_sequence';
|
|
118
|
+
default:
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
//# sourceMappingURL=tool-adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-adapter.js","sourceRoot":"","sources":["../src/tool-adapter.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AASH;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAAuB;IACtD,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACxB,IAAI,EAAE,UAAmB;QACzB,QAAQ,EAAE;YACR,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,UAAU,EAAE,IAAI,CAAC,UAA2C;SAC7D;KACF,CAAC,CAAC,CA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EvC,QAAQ,YAAY,EAAE,CAAC;QACrB,KAAK,MAAM;YACT,OAAO,UAAU,CAAC;QACpB,KAAK,YAAY;YACf,OAAO,UAAU,CAAC;QACpB,KAAK,QAAQ;YACX,OAAO,YAAY,CAAC;QACtB,KAAK,gBAAgB;YACnB,OAAO,eAAe,CAAC;QACzB;YACE,OAAO,SAAS,CAAC;IACrB,CAAC;AACH,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@llmrtc/llmrtc-provider-openai",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "OpenAI/compatible LLM + Whisper adapters for @llmrtc/LLMRTC",
|
|
5
|
+
"homepage": "https://www.llmrtc.org",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "dist/index.js",
|
|
9
|
+
"types": "dist/index.d.ts",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/llmrtc/llmrtc.git",
|
|
13
|
+
"directory": "packages/providers/openai"
|
|
14
|
+
},
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/llmrtc/llmrtc/issues",
|
|
17
|
+
"email": "contact@llmrtc.org"
|
|
18
|
+
},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"README.md",
|
|
25
|
+
"LICENSE"
|
|
26
|
+
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "tsc -b",
|
|
29
|
+
"clean": "rimraf dist",
|
|
30
|
+
"prepublishOnly": "npm run build"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@llmrtc/llmrtc-core": "^1.0.0",
|
|
34
|
+
"openai": "^4.72.0",
|
|
35
|
+
"zod": "^3.23.8"
|
|
36
|
+
}
|
|
37
|
+
}
|