-
Notifications
You must be signed in to change notification settings - Fork 39
/
api.ts
384 lines (344 loc) 路 9.72 KB
/
api.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import type { AIPromptConfig, AIServiceOptions } from '../../text/types.js';
import type {
AITextChatRequest,
AITextEmbedRequest
} from '../../tracing/types.js';
import type { API } from '../../util/apicall.js';
import { BaseAI } from '../base.js';
import type { EmbedResponse, TextModelConfig, TextResponse } from '../types.js';
import { modelInfoOpenAI } from './info.js';
import {
OpenAIAudioModel,
type OpenAIChatRequest,
type OpenAIChatResponse,
type OpenAIChatResponseDelta,
type OpenAIConfig,
OpenAIEmbedModels,
type OpenAIEmbedRequest,
type OpenAIEmbedResponse,
OpenAIModel
} from './types.js';
/**
* OpenAI: Default Model options for text generation
* @export
*/
export const OpenAIDefaultConfig = (): OpenAIConfig => ({
model: OpenAIModel.GPT35Turbo,
embedModel: OpenAIEmbedModels.TextEmbedding3Small,
audioModel: OpenAIAudioModel.Whisper1,
stream: false,
suffix: null,
maxTokens: 500,
temperature: 0.0,
topP: 0.0,
frequencyPenalty: 0.5
});
/**
* OpenAI: Default model options to use the more advanced model
* @export
*/
export const OpenAIBestConfig = (): OpenAIConfig => ({
...OpenAIDefaultConfig(),
model: OpenAIModel.GPT4Turbo
});
/**
* OpenAI: Default model options for more creative text generation
* @export
*/
export const OpenAICreativeConfig = (): OpenAIConfig => ({
...OpenAIDefaultConfig(),
model: OpenAIModel.GPT35Turbo,
temperature: 0.9
});
/**
* OpenAI: Default model options for more fast text generation
* @export
*/
export const OpenAIFastConfig = (): OpenAIConfig => ({
...OpenAIDefaultConfig(),
model: OpenAIModel.GPT35Turbo
});
export interface OpenAIArgs {
apiKey: string;
apiURL?: string;
config?: Readonly<OpenAIConfig>;
options?: Readonly<AIServiceOptions>;
}
/**
* OpenAI: AI Service
* @export
*/
export class OpenAI extends BaseAI<
OpenAIChatRequest,
OpenAIEmbedRequest,
OpenAIChatResponse,
OpenAIChatResponseDelta,
OpenAIEmbedResponse
> {
private config: OpenAIConfig;
constructor({
apiKey,
config = OpenAIDefaultConfig(),
options,
apiURL
}: Readonly<OpenAIArgs>) {
if (!apiKey || apiKey === '') {
throw new Error('OpenAI API key not set');
}
super({
name: 'OpenAI',
apiURL: apiURL ? apiURL : 'https://api.openai.com/v1',
headers: { Authorization: `Bearer ${apiKey}` },
modelInfo: modelInfoOpenAI,
models: { model: config.model, embedModel: config.embedModel },
options,
supportFor: { functions: true }
});
this.config = config;
}
override getModelConfig(): TextModelConfig {
const { config } = this;
return {
maxTokens: config.maxTokens,
temperature: config.temperature,
topP: config.topP,
n: config.n,
stream: config.stream,
logprobs: config.logprobs,
echo: config.echo,
presencePenalty: config.presencePenalty,
frequencyPenalty: config.frequencyPenalty,
bestOf: config.bestOf,
logitBias: config.logitBias,
stop: config.stop
};
}
override generateChatReq = (
req: Readonly<AITextChatRequest>,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_config: Readonly<AIPromptConfig>
): [API, OpenAIChatRequest] => {
const model = req.modelInfo?.name ?? this.config.model;
if (!req.chatPrompt || req.chatPrompt.length === 0) {
throw new Error('Chat prompt is empty');
}
const apiConfig = {
name: '/chat/completions',
headers: {
...(req.identity?.organization
? { 'OpenAI-Organization': req.identity?.organization }
: null)
}
};
const tools = req.functions?.map((v) => ({
type: 'function' as const,
function: {
name: v.name,
description: v.description,
parameters: v.parameters
}
}));
const toolsChoice =
!req.functionCall && req.functions && req.functions.length > 0
? 'auto'
: req.functionCall;
const messages = req.chatPrompt.map((v) => {
switch (v.role) {
case 'system':
return { role: 'system' as const, content: v.content };
case 'user':
return { role: 'user' as const, content: v.content, name: v.name };
case 'assistant':
return {
role: 'assistant' as const,
content: v.content,
name: v.name,
tool_calls: v.functionCalls?.map((v) => ({
id: v.id,
type: 'function' as const,
function: {
name: v.function.name,
arguments:
typeof v.function.arguments === 'object'
? JSON.stringify(v.function.arguments)
: v.function.arguments
}
}))
};
case 'function':
return {
role: 'tool' as const,
content: v.content,
tool_call_id: v.functionId
};
default:
throw new Error('Invalid role');
}
});
const frequencyPenalty =
req.modelConfig?.frequencyPenalty ?? this.config.frequencyPenalty;
const reqValue: OpenAIChatRequest = {
model,
messages,
response_format: this.config?.responseFormat
? { type: this.config?.responseFormat }
: undefined,
tools,
tool_choice: toolsChoice,
max_tokens: req.modelConfig?.maxTokens ?? this.config.maxTokens ?? 500,
temperature: req.modelConfig?.temperature ?? this.config.temperature,
top_p: req.modelConfig?.topP ?? this.config.topP ?? 1,
n: req.modelConfig?.n ?? this.config.n,
stream: req.modelConfig?.stream ?? this.config.stream,
stop: req.modelConfig?.stop ?? this.config.stop,
presence_penalty:
req.modelConfig?.presencePenalty ?? this.config.presencePenalty,
logit_bias: req.modelConfig?.logitBias ?? this.config.logitBias,
user: req.identity?.user ?? this.config.user,
organization: req.identity?.organization,
...(frequencyPenalty ? { frequency_penalty: frequencyPenalty } : {})
};
return [apiConfig, reqValue];
};
override generateEmbedReq = (
req: Readonly<AITextEmbedRequest>
): [API, OpenAIEmbedRequest] => {
const model = req.embedModelInfo?.name ?? this.config.embedModel;
if (!model) {
throw new Error('Embed model not set');
}
if (!req.texts || req.texts.length === 0) {
throw new Error('Embed texts is empty');
}
const apiConfig = {
name: '/embeddings',
headers: {
...(req.identity?.organization
? { 'OpenAI-Organization': req.identity?.organization }
: null)
}
};
const reqValue = {
model: model,
input: req.texts
};
return [apiConfig, reqValue];
};
override generateChatResp = (
resp: Readonly<OpenAIChatResponse>
): TextResponse => {
const { id, usage, choices, error } = resp;
if (error) {
throw error;
}
const modelUsage = usage
? {
promptTokens: usage.prompt_tokens,
completionTokens: usage.completion_tokens,
totalTokens: usage.total_tokens
}
: undefined;
const results = choices.map((choice) => {
const finishReason =
choice.finish_reason as TextResponse['results'][0]['finishReason'];
return {
id: `${choice.index}`,
content: choice.message.content,
role: choice.message.role,
functionCalls: choice.message.tool_calls,
finishReason
};
});
return {
modelUsage,
results,
remoteId: id
};
};
override generateChatStreamResp = (
resp: Readonly<OpenAIChatResponseDelta>
): TextResponse => {
const { id, usage, choices } = resp;
const modelUsage = usage
? {
promptTokens: usage.prompt_tokens,
completionTokens: usage.completion_tokens,
totalTokens: usage.total_tokens
}
: undefined;
const results = choices.map(
({ delta: { content, role, tool_calls }, finish_reason }) => {
const finishReason =
finish_reason as TextResponse['results'][0]['finishReason'];
return {
content,
role: role,
functionCalls: tool_calls,
finishReason,
id
};
}
);
return {
results,
modelUsage
};
};
override generateEmbedResp = (
resp: Readonly<OpenAIEmbedResponse>
): EmbedResponse => {
const { data, usage } = resp;
const modelUsage = usage
? {
promptTokens: usage.prompt_tokens,
completionTokens: usage.completion_tokens,
totalTokens: usage.total_tokens
}
: undefined;
return {
embeddings: data.map((v) => v.embedding),
modelUsage
};
};
// async _transcribe(
// file: string,
// prompt?: string,
// options?: Readonly<AITranscribeConfig>
// ): Promise<TranscriptResponse> {
// const res = await this.apiCallWithUpload<
// OpenAIAudioRequest,
// OpenAIAudioResponse,
// OpenAIApiConfig
// >(
// this.createAPI(OpenAIApi.Transcribe),
// generateAudioReq(this.options, prompt, options?.language),
// file
// );
// const { duration, segments } = res;
// return {
// duration,
// segments: segments.map((v) => ({
// id: v.id,
// start: v.start,
// end: v.end,
// text: v.text,
// })),
// };
// }
}
// export const generateAudioReq = (
// opt: Readonly<OpenAIConfig>,
// prompt?: string,
// language?: string
// ): OpenAIAudioRequest => {
// if (!opt.audioModel) {
// throw new Error('OpenAI audio model not set');
// }
// return {
// model: opt.audioModel,
// prompt,
// temperature: opt.temperature,
// language,
// response_format: 'verbose_json',
// };
// };