@meistrari/tela-sdk-js 0.0.3 → 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.
@@ -1,482 +0,0 @@
1
- import type { RequestOptions } from '../base-client';
2
- import type { Stream } from '../streaming';
3
- import { TelaFile } from '../file';
4
- import { Resource } from '../resource';
5
- /**
6
- * Manages chat completion operations.
7
- *
8
- * Provides methods to create chat completions, handle streaming responses,
9
- * and manage file uploads associated with chat completions.
10
- *
11
- * @example
12
- * ```typescript
13
- * const tela = new TelaSDK({
14
- * apiKey: 'your-api-key',
15
- * });
16
- * const response = await tela.completions.create({
17
- * canvasId: "your-canvas-id",
18
- * messages: [{ role: "user", content: "Hello!" }],
19
- * });
20
- * console.log(response.choices[0].message.content);
21
- * ```
22
- */
23
- export declare class ChatCompletions extends Resource {
24
- /**
25
- * Creates a chat completion with various input options and response formats.
26
- *
27
- * This method supports synchronous responses, streaming responses, and webhook-based asynchronous processing.
28
- *
29
- * @param body - The parameters for creating a chat completion.
30
- * @param opts - Additional request options.
31
- * @returns A Promise that resolves to either a stream of chat completion responses,
32
- * a single chat completion response, or a webhook response, depending on the input parameters.
33
- *
34
- * @example
35
- * ```typescript
36
- * // Synchronous response
37
- * const response = await tela.completions.create({
38
- * canvasId: "your-canvas-id",
39
- * messages: [{ role: "user", content: "Tell me a joke." }],
40
- * });
41
- *
42
- * // Streaming response
43
- * const stream = await tela.completions.create({
44
- * canvasId: "your-canvas-id",
45
- * messages: [{ role: "user", content: "Tell me a story." }],
46
- * stream: true,
47
- * });
48
- *
49
- * // Webhook response
50
- * const webhookResponse = await tela.completions.create({
51
- * canvasId: "your-canvas-id",
52
- * messages: [{ role: "user", content: "Generate a report." }],
53
- * webhookUrl: "https://example.com/webhook",
54
- * });
55
- * ```
56
- */
57
- create<Variables = ChatCompletionVariables, CompletionContent = string>(body: ChatCompletionCreateWebhookParams<Variables>, opts?: RequestOptions<ChatCompletionCreateParams<Variables>>): Promise<ChatCompletionWebhookResponse<CompletionContent>>;
58
- create<Variables = ChatCompletionVariables, CompletionContent = string>(body: CompletionCreateParamsNonStreaming<Variables>, opts?: RequestOptions<ChatCompletionCreateParams<Variables>>): Promise<ChatCompletionCreateResponse<CompletionContent>>;
59
- create<Variables = ChatCompletionVariables, CompletionContent = string>(body: CompletionCreateParamsStreaming<Variables>, opts?: RequestOptions<ChatCompletionCreateParams<Variables>>): Promise<Stream<ChatCompletionCreateStreamingResponse<CompletionContent>>>;
60
- create<Variables = ChatCompletionVariables, CompletionContent = string>(body: ChatCompletionCreateParamsBase<Variables>, opts?: RequestOptions<ChatCompletionCreateParams<Variables>>): Promise<Stream<ChatCompletionCreateStreamingResponse<CompletionContent>> | ChatCompletionCreateResponse<CompletionContent> | ChatCompletionWebhookResponse<CompletionContent>>;
61
- /**
62
- * Uploads a file and returns its URL and options.
63
- *
64
- * This is used internally to handle file uploads associated with chat completions.
65
- *
66
- * @param file - The TelaFile to be uploaded.
67
- * @returns A Promise that resolves to an object containing the file URL and options.
68
- * @throws {FileUploadError} If the file upload fails.
69
- *
70
- * @example
71
- * ```typescript
72
- * const file = new TelaFile({ /* file options *\/ });
73
- * const uploadedFile = await this.uploadFile(file);
74
- * console.log(uploadedFile.file_url);
75
- * ```
76
- */
77
- private uploadFile;
78
- }
79
- type ChatCompletionVariablesValue = string | number | boolean | TelaFile;
80
- /**
81
- * Represents the variables available in the canvas.
82
- * Keys are strings, and values can be strings, numbers, booleans, or TelaFile instances.
83
- */
84
- type ChatCompletionVariables = Record<string, ChatCompletionVariablesValue>;
85
- /**
86
- * Represents the processed variables with file URLs.
87
- * Similar to ChatCompletionVariables, but TelaFile instances are replaced with their URLs.
88
- */
89
- type ChatCompletionVariablesWithFileURL = Record<string, string | number | boolean | {
90
- fileUrl: string;
91
- }>;
92
- /**
93
- * Base parameters for creating a chat completion.
94
- */
95
- export interface ChatCompletionCreateParamsBase<Variables = ChatCompletionVariables> {
96
- /**
97
- * The version ID of the canvas to use for this chat completion.
98
- * If not provided, the latest version of the specified canvas will be used.
99
- */
100
- versionId?: string;
101
- /**
102
- * The ID of the canvas to use for this chat completion.
103
- * This is required if an applicationId is not provided.
104
- */
105
- canvasId?: string;
106
- /**
107
- * The ID of the deployed application to use for this chat completion.
108
- * This is required if a canvasId is not provided.
109
- */
110
- applicationId?: string;
111
- /**
112
- * The URL to receive a webhook notification when the chat completion is finished.
113
- * If provided, the completion will be processed asynchronously.
114
- */
115
- webhookUrl?: string | null | undefined;
116
- /**
117
- * Variables to be passed to the canvas for this chat completion.
118
- * These can be used to customize the behavior of the canvas for this specific request.
119
- */
120
- variables?: Variables;
121
- /**
122
- * An array of previous messages in the conversation.
123
- * Each message should have a 'role' (e.g., 'user', 'assistant') and 'content'.
124
- */
125
- messages?: Array<{
126
- role: string;
127
- content: string;
128
- }>;
129
- /**
130
- * Override default settings specified in the canvas.
131
- * This allows for fine-tuning the completion behavior for this specific request.
132
- */
133
- override?: {
134
- /**
135
- * The specific model to use for this completion.
136
- * If not specified, the default model set in the canvas will be used.
137
- */
138
- model?: string;
139
- /**
140
- * Controls randomness in the output. Values between 0 and 1.
141
- * Lower values make the output more focused and deterministic.
142
- */
143
- temperature?: number;
144
- /**
145
- * Specifies whether to use a chat or completion model.
146
- */
147
- type: 'chat' | 'completion';
148
- /**
149
- * An array of functions that the model can call.
150
- * This allows for more structured and interactive completions.
151
- */
152
- functions?: Array<{
153
- id: string;
154
- name: string;
155
- description?: string;
156
- parameters?: {
157
- type: 'object';
158
- properties: Record<string, unknown>;
159
- required?: string[];
160
- };
161
- }>;
162
- /**
163
- * Configuration for generating structured output.
164
- */
165
- structuredOutput?: {
166
- /**
167
- * Whether to enable structured output for this completion.
168
- */
169
- enabled: boolean;
170
- /**
171
- * The schema defining the structure of the output.
172
- * This is used when structured output is enabled.
173
- */
174
- schema?: {
175
- properties: Record<string, unknown>;
176
- type: 'object';
177
- title: string;
178
- description: string;
179
- required: string[];
180
- };
181
- };
182
- };
183
- }
184
- /**
185
- * Parameters for creating a streaming chat completion.
186
- */
187
- export interface CompletionCreateParamsStreaming<T> extends ChatCompletionCreateParamsBase<T> {
188
- /**
189
- * Whether the response should be streamed.
190
- */
191
- stream: true;
192
- /**
193
- * The webhook URL, if you want to receive a webhook when the completion is completed.
194
- */
195
- webhookUrl?: undefined | null;
196
- }
197
- /**
198
- * Parameters for creating a non-streaming chat completion.
199
- */
200
- export interface CompletionCreateParamsNonStreaming<T> extends ChatCompletionCreateParamsBase<T> {
201
- /**
202
- * Whether the response should be streamed.
203
- */
204
- stream?: false | undefined | null;
205
- }
206
- /**
207
- * Parameters for creating a chat completion with a webhook.
208
- */
209
- export interface ChatCompletionCreateWebhookParams<T> extends CompletionCreateParamsNonStreaming<T> {
210
- /**
211
- * The webhook URL, if you want to receive a webhook when the completion is completed.
212
- */
213
- webhookUrl: string;
214
- }
215
- /**
216
- * Union type for all possible chat completion creation parameters.
217
- */
218
- export type ChatCompletionCreateParams<T> = CompletionCreateParamsStreaming<T> | CompletionCreateParamsNonStreaming<T> | ChatCompletionCreateWebhookParams<T>;
219
- /**
220
- * Response structure for a created chat completion.
221
- */
222
- export type ChatCompletionCreateResponse<T> = {
223
- /**
224
- * The ID of the completion.
225
- */
226
- id: string;
227
- /**
228
- * The object of the completion.
229
- */
230
- object: string;
231
- /**
232
- * The created time of the completion.
233
- */
234
- created: number;
235
- /**
236
- * The choices of the completion.
237
- */
238
- choices: Array<{
239
- message: {
240
- role: string;
241
- content: T;
242
- };
243
- }>;
244
- };
245
- /**
246
- * Response structure for a chat completion streaming response.
247
- */
248
- export type ChatCompletionCreateStreamingResponse<T> = {
249
- /**
250
- * The ID of the completion.
251
- */
252
- id: string;
253
- /**
254
- * The object of the completion.
255
- */
256
- object: string;
257
- /**
258
- * The created time of the completion.
259
- */
260
- created: number;
261
- /**
262
- * The model of the completion.
263
- */
264
- model: string;
265
- /**
266
- * The choices of the completion.
267
- */
268
- choices: Array<{
269
- delta: {
270
- role: string | null;
271
- content: string | null;
272
- functionCall: {
273
- name: string | null;
274
- arguments: string | null;
275
- } | null;
276
- };
277
- finishReason: string | null;
278
- index: number;
279
- logprobs: number | null;
280
- }>;
281
- /**
282
- * The message of the completion.
283
- */
284
- message: {
285
- role: string;
286
- content: string | null;
287
- functionCall: {
288
- name: string | null;
289
- arguments: string | null;
290
- } | null;
291
- toolCalls: Array<{
292
- name: string;
293
- arguments: string;
294
- }>;
295
- structuredContent: T;
296
- };
297
- };
298
- /**
299
- * Response structure for a chat completion webhook.
300
- * This interface represents the data sent to the webhook URL when a chat completion is finished.
301
- */
302
- interface ChatCompletionWebhookResponse<T> {
303
- /**
304
- * Unique identifier for this chat completion response.
305
- */
306
- id: string;
307
- /**
308
- * The current status of the chat completion.
309
- * - 'created': The request has been received but processing hasn't started.
310
- * - 'running': The chat completion is currently being processed.
311
- * - 'succeeded': The chat completion has finished successfully.
312
- * - 'failed': The chat completion encountered an error and couldn't complete.
313
- */
314
- status: 'created' | 'failed' | 'running' | 'succeeded';
315
- /**
316
- * Contains information about the input provided for this chat completion.
317
- */
318
- inputContent: {
319
- /**
320
- * Variables passed to the chat completion, including any file URLs.
321
- */
322
- variables: ChatCompletionVariablesWithFileURL;
323
- /**
324
- * Array of messages that were part of the input.
325
- */
326
- messages: Array<{
327
- /**
328
- * The role of the message sender (e.g., 'user', 'assistant', 'system').
329
- */
330
- role: string;
331
- /**
332
- * The content of the message. Can be a string for text messages,
333
- * or an object for more complex content types like images.
334
- */
335
- content: string | {
336
- type: 'text';
337
- text: string;
338
- } | {
339
- type: 'image_url';
340
- imageUrl: {
341
- url: string;
342
- detail?: 'auto' | 'high' | 'low';
343
- };
344
- };
345
- /**
346
- * Optional. Information about a function call, if applicable.
347
- */
348
- functionCall?: {
349
- name: string;
350
- arguments: string;
351
- };
352
- }>;
353
- /**
354
- * Information about files used in the chat completion.
355
- */
356
- files: Array<{
357
- name: string;
358
- usedAt: 'variables' | 'messages';
359
- parsedContent: string;
360
- url: string;
361
- type: 'image' | 'file';
362
- }>;
363
- };
364
- /**
365
- * Contains the output generated by the chat completion.
366
- */
367
- outputContent: {
368
- /**
369
- * The role of the entity providing the output.
370
- */
371
- role: 'system' | 'user' | 'assistant' | 'function';
372
- /**
373
- * Optional. Information about tool calls made during the completion.
374
- */
375
- toolCalls?: Array<{
376
- name: string;
377
- arguments: string;
378
- }>;
379
- /**
380
- * Optional. Additional information about the completion process.
381
- */
382
- information?: {
383
- duration: number;
384
- cost?: number;
385
- inputTokens?: number;
386
- outputTokens?: number;
387
- };
388
- /**
389
- * Indicates whether the output has a structured format.
390
- */
391
- hasStructuredOutput?: boolean;
392
- /**
393
- * The main content of the chat completion output.
394
- */
395
- content: T;
396
- /**
397
- * Optional. The input messages in a string format.
398
- */
399
- inputMessages?: string | undefined;
400
- };
401
- /**
402
- * The original input parameters provided for this chat completion.
403
- */
404
- rawInput: {
405
- versionId?: string;
406
- canvasId?: string;
407
- applicationId?: string;
408
- webhookUrl?: string;
409
- variables?: ChatCompletionVariablesWithFileURL;
410
- messages?: Array<{
411
- role: string;
412
- content: string | {
413
- type: 'text';
414
- text: string;
415
- } | {
416
- type: 'image_url';
417
- imageUrl: {
418
- url: string;
419
- detail?: 'auto' | 'high' | 'low';
420
- };
421
- };
422
- }>;
423
- override?: {
424
- model?: string;
425
- temperature?: number;
426
- type: 'chat' | 'completion';
427
- functions?: Array<{
428
- id: string;
429
- name: string;
430
- description?: string;
431
- parameters?: {
432
- type: 'object';
433
- properties: Record<string, unknown>;
434
- required?: string[];
435
- };
436
- }>;
437
- structuredOutput?: {
438
- enabled: boolean;
439
- schema?: {
440
- properties: Record<string, unknown>;
441
- type: 'object';
442
- title: string;
443
- description: string;
444
- required: string[];
445
- };
446
- };
447
- };
448
- } | null;
449
- /**
450
- * The raw output from the chat completion process.
451
- */
452
- rawOutput: Record<string, unknown>;
453
- /**
454
- * The date used for compatibility checks.
455
- */
456
- compatibilityDate: Date;
457
- /**
458
- * The ID of the prompt version used for this chat completion.
459
- */
460
- promptVersionId: string;
461
- /**
462
- * The ID of the prompt application, if applicable.
463
- */
464
- promptApplicationId: string | null;
465
- /**
466
- * The ID of the workspace where this chat completion was executed.
467
- */
468
- workspaceId: string;
469
- /**
470
- * The timestamp when this chat completion was created.
471
- */
472
- createdAt: string;
473
- /**
474
- * The timestamp when this chat completion was last updated.
475
- */
476
- updatedAt: string;
477
- /**
478
- * The timestamp when this chat completion was deleted, if applicable.
479
- */
480
- deletedAt: string | null;
481
- }
482
- export {};
@@ -1,86 +0,0 @@
1
- import { FileUploadError } from '../errors';
2
- import { TelaFile } from '../file';
3
- import { Resource } from '../resource';
4
- /**
5
- * Manages chat completion operations.
6
- *
7
- * Provides methods to create chat completions, handle streaming responses,
8
- * and manage file uploads associated with chat completions.
9
- *
10
- * @example
11
- * ```typescript
12
- * const tela = new TelaSDK({
13
- * apiKey: 'your-api-key',
14
- * });
15
- * const response = await tela.completions.create({
16
- * canvasId: "your-canvas-id",
17
- * messages: [{ role: "user", content: "Hello!" }],
18
- * });
19
- * console.log(response.choices[0].message.content);
20
- * ```
21
- */
22
- export class ChatCompletions extends Resource {
23
- async create(body, opts) {
24
- const processedBody = { ...body };
25
- if (body.variables) {
26
- const processedVariables = {};
27
- for await (const [key, value] of Object.entries(body.variables)) {
28
- if (value instanceof TelaFile) {
29
- const fileWithUrl = await this.uploadFile(value);
30
- processedVariables[key] = fileWithUrl;
31
- }
32
- else {
33
- processedVariables[key] = value;
34
- }
35
- }
36
- processedBody.variables = processedVariables;
37
- }
38
- return this._client.post('/v2/chat/completions', {
39
- body: processedBody,
40
- ...opts,
41
- stream: body.stream ?? false,
42
- });
43
- }
44
- /**
45
- * Uploads a file and returns its URL and options.
46
- *
47
- * This is used internally to handle file uploads associated with chat completions.
48
- *
49
- * @param file - The TelaFile to be uploaded.
50
- * @returns A Promise that resolves to an object containing the file URL and options.
51
- * @throws {FileUploadError} If the file upload fails.
52
- *
53
- * @example
54
- * ```typescript
55
- * const file = new TelaFile({ /* file options *\/ });
56
- * const uploadedFile = await this.uploadFile(file);
57
- * console.log(uploadedFile.file_url);
58
- * ```
59
- */
60
- async uploadFile(file) {
61
- const content = await file.getUploadableContent();
62
- if (file.isURL && typeof content === 'string') {
63
- return { fileUrl: content, options: file.options };
64
- }
65
- const response = await this._client.post('/v2/file');
66
- const { uploadUrl, downloadUrl } = response;
67
- let contentType = 'application/octet-stream';
68
- if (content instanceof File || content instanceof Blob) {
69
- contentType = content.type;
70
- }
71
- const uploadResponse = await fetch(uploadUrl, {
72
- method: 'PUT',
73
- body: content,
74
- headers: {
75
- 'Content-Type': contentType,
76
- ...(file.size ? { 'Content-Length': file.size.toString() } : {}),
77
- },
78
- // @ts-expect-error: duplex is not supported
79
- duplex: 'half',
80
- });
81
- if (!uploadResponse.ok) {
82
- throw new FileUploadError(await uploadResponse.text());
83
- }
84
- return { fileUrl: downloadUrl, options: file.options };
85
- }
86
- }
@@ -1 +0,0 @@
1
- export * from './chat-completions';
@@ -1 +0,0 @@
1
- export * from './chat-completions';
@@ -1,81 +0,0 @@
1
- import { ReadableStream } from 'node:stream/web';
2
- /**
3
- * Represents a server-sent event.
4
- */
5
- export type ServerSentEvent = {
6
- /**
7
- * The event type, or null if not specified.
8
- */
9
- event: string | null;
10
- /**
11
- * The event data.
12
- */
13
- data: string;
14
- /**
15
- * The raw event data as an array of strings.
16
- */
17
- raw: string[];
18
- };
19
- /**
20
- * Represents a stream of items that can be asynchronously iterated over.
21
- */
22
- export declare class Stream<Item> implements AsyncIterable<Item> {
23
- private iterator;
24
- /**
25
- * The AbortController associated with this stream.
26
- */
27
- controller: AbortController;
28
- /**
29
- * Creates a new Stream instance.
30
- *
31
- * @param iterator - A function that returns an AsyncIterator<Item>.
32
- * @param controller - The AbortController for this stream.
33
- */
34
- constructor(iterator: () => AsyncIterator<Item>, controller: AbortController);
35
- /**
36
- * Creates a Stream from a server-sent events (SSE) Response.
37
- *
38
- * @param response - The Response object containing the SSE data.
39
- * @param controller - The AbortController for this stream.
40
- * @returns A new Stream instance.
41
- * @throws {Error} If the stream is consumed more than once.
42
- * @throws {APIError} If the SSE data contains an error.
43
- */
44
- static fromSSEResponse<Item>(response: Response, controller: AbortController): Stream<Item>;
45
- /**
46
- * Creates a Stream from a newline-separated ReadableStream where each item is a JSON value.
47
- *
48
- * @param readableStream - The ReadableStream containing newline-separated JSON data.
49
- * @param controller - The AbortController for this stream.
50
- * @returns A new Stream instance.
51
- * @throws {Error} If the stream is consumed more than once.
52
- */
53
- static fromReadableStream<Item>(readableStream: ReadableStream, controller: AbortController): Stream<Item>;
54
- /**
55
- * Implements the AsyncIterable interface, allowing the Stream to be used in a for-await-of loop.
56
- *
57
- * @returns An AsyncIterator for the stream items.
58
- */
59
- [Symbol.asyncIterator](): AsyncIterator<Item>;
60
- /**
61
- * Splits the stream into two streams which can be independently read from at different speeds.
62
- *
63
- * @returns A tuple containing two new Stream instances.
64
- */
65
- tee(): [Stream<Item>, Stream<Item>];
66
- /**
67
- * Converts this stream to a newline-separated ReadableStream of JSON stringified values.
68
- * The resulting stream can be converted back to a Stream using `Stream.fromReadableStream()`.
69
- *
70
- * @returns A ReadableStream containing newline-separated JSON data.
71
- */
72
- toReadableStream(): ReadableStream;
73
- }
74
- export declare function _iterSSEMessages(response: Response, controller: AbortController): AsyncGenerator<ServerSentEvent, void, unknown>;
75
- /**
76
- * Most browsers don't yet have async iterable support for ReadableStream,
77
- * and Node has a very different way of reading bytes from its "ReadableStream".
78
- *
79
- * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
80
- */
81
- export declare function readableStreamAsyncIterable<T>(stream: any): AsyncIterableIterator<T>;