-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtyping.ts
More file actions
450 lines (383 loc) · 9.71 KB
/
typing.ts
File metadata and controls
450 lines (383 loc) · 9.71 KB
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// Copyright 2025 Flower Labs GmbH. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { ALLOWED_ROLES } from './constants';
export type JsonValue =
| string
| number
| boolean
| JsonValue[]
| { [key: string]: JsonValue }
| null;
/**
* Represents a message in a chat session.
*/
export interface Message {
/**
* The role of the sender (e.g., "user", "system", "assistant").
*/
role: (typeof ALLOWED_ROLES)[number];
/**
* The content of the message.
*/
content: string;
/**
* An optional list of calls to specific tools
*/
toolCalls?: ToolCall[];
}
/**
* The usage statistics for a chat message.
*/
export interface Usage {
/*
* The number of tokens in the prompt, if available.
*/
promptTokens?: number;
/*
* The number of tokens contained in the response, if available.
*/
completionTokens?: number;
/*
* The total number of tokens used (prompt + completion), if available.
*/
totalTokens?: number;
}
/**
* Represents a call to a specific tool with its name and arguments.
*/
export type ToolCall = Record<
string,
{
/**
* The name of the tool being called.
*/
name: string;
/**
* The arguments passed to the tool as key-value pairs.
*/
arguments: Record<string, JsonValue>;
}
>;
/**
* Represents a property of a tool's function parameter.
*/
export interface ToolParameterProperty {
/**
* The data type of the property (e.g., "string", "number").
*/
type: string;
/**
* A description of the property.
*/
description: string;
/**
* An optional list of allowed values for the property.
*/
enum?: string[];
}
export type Embedding = number[];
export type EmbeddingInput = string | string[] | number[] | number[][];
/**
* Represents the parameters required for a tool's function.
*/
export interface ToolFunctionParameters {
/**
* The data type of the parameters (e.g., "object").
*/
type: string;
/**
* A record defining the properties of each parameter.
*/
properties: Record<string, ToolParameterProperty>;
/**
* A list of parameter names that are required.
*/
required: string[];
}
/**
* Represents the function provided by a tool.
*/
export interface ToolFunction {
/**
* The name of the function provided by the tool.
*/
name: string;
/**
* A brief description of what the function does.
*/
description: string;
/**
* The parameters required for invoking the function.
*/
parameters: ToolFunctionParameters;
}
/**
* Represents a tool with details about its type, function, and parameters.
*/
export interface Tool {
/**
* The type of the tool (e.g., "function" or "plugin").
*/
type: string;
/**
* Details about the function provided by the tool.
*/
function: ToolFunction;
}
/**
* Represents the choice of tool to be used in a chat interaction.
*/
export type ToolChoice = string | { type: 'function'; function: { name: string } };
/**
* Represents a single event in a streaming response.
*/
export interface StreamEvent {
/**
* The chunk of text data received in the stream event.
*/
chunk?: string;
toolCall?: {
index: string;
name: string;
arguments: string | Record<string, string>;
complete: boolean;
};
}
/**
* Enum representing failure codes for different error scenarios.
*/
export enum FailureCode {
/**
* Indicates a local error (e.g., client-side issues).
*/
LocalError = 100,
/**
* Indicates a chat error coming from a local engine.
*/
LocalEngineChatError,
/**
* Indicates a fetch error coming from a local engine.
*/
LocalEngineFetchError,
/**
* Indicates an missing provider for a local model.
*/
NoLocalProviderError,
/**
* Indicates that a model requires more RAM than currently available to be loaded.
*/
InsufficientRAMError,
/**
* Indicates a remote error (e.g., server-side issues).
*/
RemoteError = 200,
/**
* Indicates an authentication error (e.g., HTTP 401, 403, 407).
*/
AuthenticationError,
/**
* Indicates that the service is unavailable (e.g., HTTP 404, 502, 503).
*/
UnavailableError,
/**
* Indicates a timeout error (e.g., HTTP 408, 504).
*/
TimeoutError,
/**
* Indicates a connection error (e.g., network issues).
*/
ConnectionError,
/**
* Indicates an engine-specific error.
*/
EngineSpecificError = 300,
/**
* Indicates that a model is not supported by a given engine.
*/
UnsupportedModelError,
/**
* Indicates a error related to the encryption protocol for remote inference.
*/
EncryptionError,
/**
* Indicates an error caused by a misconfigured state.
*/
ConfigError = 400,
/**
* Indicates that invalid arguments were provided.
*/
InvalidArgumentsError,
/**
* Indicates misconfigured config options for remote inference.
*/
InvalidRemoteConfigError,
/**
* Indicates an unknown model error (e.g., unavailable or invalid model).
*/
UnknownModelError,
/**
* Indicates that the requested feature is not implemented.
*/
NotImplementedError,
/**
* Indicates an error that occurred during inference
*/
RuntimeError = 500,
/**
* Indicates that the user aborted the request.
*/
RequestAborted,
}
/**
* Represents a failure response with a code and description.
*/
export interface Failure {
/**
* The failure code indicating the type of error.
*/
code: FailureCode;
/**
* A description of the failure.
*/
description: string;
}
export interface ProviderMapping {
onnx?: string;
webllm?: string;
}
export interface Progress {
totalBytes?: number;
loadedBytes?: number;
percentage?: number;
description?: string;
}
export interface JsonSchema {
$defs?: Record<
string,
{
enum: string[];
title: string;
type: string;
}
>;
properties: Record<
string,
{
title: string;
type: string;
$ref?: string;
}
>;
required: string[];
title: string;
type: string;
}
export interface JsonSchemaPayload {
name: string;
schema: JsonSchema;
}
export interface ResponseFormat {
type: 'json_schema';
json_schema: JsonSchemaPayload;
}
/**
* Options to configure the chat interaction.
*/
export interface ChatOptions {
/**
* The model name to use for the chat. Defaults to a predefined model if not specified.
*/
model?: string;
/**
* Controls the creativity of the response. Typically a value between 0 and 1.
*/
temperature?: number;
/**
* Maximum number of tokens to generate in the response.
*/
maxCompletionTokens?: number;
/**
* An alternative to sampling with temperature, called nucleus sampling,
* where the model considers the results of the tokens with top_p
* probability mass. So 0.1 means only the tokens comprising the top 10%
* probability mass are considered.
* We generally recommend altering this or temperature but not both.
*/
topP?: number;
/**
* An object specifying the format that the model must output.
* Setting to { "type": "json_schema", "json_schema": {...} }
* enables Structured Outputs which ensures the model will match
* your supplied JSON schema. Learn more in the OpenAI API
* [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).
*/
responseFormat?: ResponseFormat;
/**
* If true, the response will be streamed.
*/
stream?: boolean;
/**
* Optional callback invoked when a stream event occurs.
* @param event The {@link StreamEvent} data from the stream.
*/
onStreamEvent?: (event: StreamEvent) => void;
/**
* Optional array of tools available for the chat.
*/
tools?: Tool[];
/**
* Optional, if set to `auto`, the model will decide when to use one of the provided tools.
* If set to `none`, the model will not use any tools.
* If set to `require`, the model must use one of the provided tools.
* If set to a specific tool name, the model will use that tool.
* If set to a function, the model will use that function tool.
*/
toolChoice?: ToolChoice;
/**
* If true and remote handoff is enabled, forces the use of a remote engine.
*/
forceRemote?: boolean;
/**
* If true, forces the use of a local engine.
*/
forceLocal?: boolean;
/**
* If true, enables end-to-end encryption for processing the request.
*/
encrypt?: boolean;
/**
* Optional AbortSignal to cancel in-flight generation.
*/
signal?: AbortSignal;
}
export type Result<T> = { ok: true; value: T } | { ok: false; failure: Failure };
/**
* Represents the result of a chat operation.
*
* This union type encapsulates both successful and failed chat outcomes.
*
* - **Success:**
* When the operation is successful, the result is an object with:
* - `ok: true` indicating success.
* - `message: {@link Message}` containing the chat response.
*
* - **Failure:**
* When the operation fails, the result is an object with:
* - `ok: false` indicating failure.
* - `failure: {@link Failure}` providing details about the error.
*/
export type ChatResponseResult =
| { ok: true; message: Message; usage?: Usage }
| { ok: false; failure: Failure };