pendra 0.12.2 → 0.13.1
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/README.md +5 -0
- package/dist/index.d.mts +70 -3
- package/dist/index.d.ts +70 -3
- package/dist/index.js +178 -32
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +176 -32
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -8
package/README.md
CHANGED
|
@@ -154,6 +154,11 @@ Image generation is non-streaming — the response is returned as a single JSON
|
|
|
154
154
|
| `baseURL` | — | `https://api.pendra.ai` |
|
|
155
155
|
| `timeout` | — | `120000` (ms) |
|
|
156
156
|
|
|
157
|
+
For a streaming request, `timeout` covers waiting for the response to start and
|
|
158
|
+
then any gap between chunks, not the length of the whole stream, so long
|
|
159
|
+
generations are not cut off. Breaking out of a stream's `for await` loop early
|
|
160
|
+
cancels the request.
|
|
161
|
+
|
|
157
162
|
## Migrating from OpenAI
|
|
158
163
|
|
|
159
164
|
```diff
|
package/dist/index.d.mts
CHANGED
|
@@ -370,6 +370,20 @@ interface ChatCompletionCreateParams {
|
|
|
370
370
|
* rather than filtering lines — so a frame the server tags with a named
|
|
371
371
|
* `event:` is dropped in one piece instead of having its `data:` line mistaken
|
|
372
372
|
* for a chat chunk (issue #1398).
|
|
373
|
+
*
|
|
374
|
+
* Each surviving frame goes through {@link parseStreamFrame}, which throws on
|
|
375
|
+
* the API's in-band `{"error": …}` failure reports and on a frame that isn't a
|
|
376
|
+
* chunk. The error frames used to be yielded *as* chunks (`JSON.parse` succeeds
|
|
377
|
+
* on them), so a worker crash surfaced as a `TypeError` on `chunk.choices[0]`
|
|
378
|
+
* rather than as something a caller could catch and read (issue #2252).
|
|
379
|
+
*
|
|
380
|
+
* `idleTimeoutMs` bounds the gap between reads, not the whole stream: the API
|
|
381
|
+
* sends a keep-alive comment every 15 s, so a healthy stream never goes quiet
|
|
382
|
+
* for long however long it runs, while a stalled one fails with an
|
|
383
|
+
* `APIConnectionError` rather than hanging (#2185). Leaving the loop before the
|
|
384
|
+
* stream ends — a `break`, or a frame that throws — aborts the request, so the
|
|
385
|
+
* connection is released and the worker stops generating tokens nobody will
|
|
386
|
+
* read (#2216).
|
|
373
387
|
*/
|
|
374
388
|
declare class Stream implements AsyncIterable<ChatCompletionChunk> {
|
|
375
389
|
private reader;
|
|
@@ -377,7 +391,8 @@ declare class Stream implements AsyncIterable<ChatCompletionChunk> {
|
|
|
377
391
|
private sse;
|
|
378
392
|
private done;
|
|
379
393
|
private controller;
|
|
380
|
-
|
|
394
|
+
private idleTimeoutMs;
|
|
395
|
+
constructor(response: Response, controller: AbortController, idleTimeoutMs?: number);
|
|
381
396
|
[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk>;
|
|
382
397
|
abort(): void;
|
|
383
398
|
}
|
|
@@ -693,7 +708,6 @@ declare class Pendra {
|
|
|
693
708
|
_fetch(path: string, options: {
|
|
694
709
|
method: string;
|
|
695
710
|
body?: Record<string, unknown>;
|
|
696
|
-
stream?: boolean;
|
|
697
711
|
headers?: Record<string, string>;
|
|
698
712
|
}): Promise<{
|
|
699
713
|
response: Response;
|
|
@@ -729,5 +743,58 @@ declare class AuthenticationError extends APIStatusError {
|
|
|
729
743
|
declare class RateLimitError extends APIStatusError {
|
|
730
744
|
constructor(message?: string);
|
|
731
745
|
}
|
|
746
|
+
/**
|
|
747
|
+
* Raised when a response arrives but isn't the shape the SDK expects.
|
|
748
|
+
*
|
|
749
|
+
* A server or proxy problem, not a transport one: the request reached Pendra
|
|
750
|
+
* and came back, but the body could not be read as the documented type — a 200
|
|
751
|
+
* missing a required field, a captive-portal HTML page from a corporate proxy,
|
|
752
|
+
* a truncated body.
|
|
753
|
+
*
|
|
754
|
+
* Deliberately NOT an `APIConnectionError`: retrying a response that will never
|
|
755
|
+
* parse just burns the retry budget, so callers that retry on connection
|
|
756
|
+
* failures should let this one through. `body` holds a short excerpt of what
|
|
757
|
+
* actually came back.
|
|
758
|
+
*/
|
|
759
|
+
declare class APIResponseValidationError extends APIError {
|
|
760
|
+
/** How much of the offending body to keep in the message. */
|
|
761
|
+
static readonly BODY_EXCERPT_CHARS = 200;
|
|
762
|
+
readonly body: string | undefined;
|
|
763
|
+
constructor(message: string, options?: {
|
|
764
|
+
status?: number;
|
|
765
|
+
body?: string;
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Raised when a stream reports a failure in-band, after HTTP 200.
|
|
770
|
+
*
|
|
771
|
+
* A streaming response commits its status line before the worker has done any
|
|
772
|
+
* work, so anything that goes wrong afterwards — the worker crashing, the
|
|
773
|
+
* request timing out, the fleet being at capacity — can only be described in
|
|
774
|
+
* the body. The API sends `data: {"error": {…}}` followed by `data: [DONE]`,
|
|
775
|
+
* and this error is how the SDK surfaces that instead of ending the stream as
|
|
776
|
+
* though it had succeeded.
|
|
777
|
+
*
|
|
778
|
+
* `requestId` and `workerId` identify the failed inference to Pendra support.
|
|
779
|
+
*
|
|
780
|
+
* Note this extends `APIError`, not `APIStatusError`, because the API omits
|
|
781
|
+
* `code` on some frames (the timeout and the generic catch-all) — so `status`
|
|
782
|
+
* is genuinely optional here, which `APIStatusError`'s always-present `status`
|
|
783
|
+
* cannot express. Check `status` for undefined before comparing it.
|
|
784
|
+
*/
|
|
785
|
+
declare class APIStreamError extends APIError {
|
|
786
|
+
readonly type: string | undefined;
|
|
787
|
+
readonly code: number | undefined;
|
|
788
|
+
readonly requestId: string | undefined;
|
|
789
|
+
readonly workerId: string | undefined;
|
|
790
|
+
readonly workerName: string | undefined;
|
|
791
|
+
constructor(message: string, options?: {
|
|
792
|
+
type?: string;
|
|
793
|
+
code?: number;
|
|
794
|
+
requestId?: string;
|
|
795
|
+
workerId?: string;
|
|
796
|
+
workerName?: string;
|
|
797
|
+
});
|
|
798
|
+
}
|
|
732
799
|
|
|
733
|
-
export { APIConnectionError, APIError, APIStatusError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
|
|
800
|
+
export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, APIStreamError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
|
package/dist/index.d.ts
CHANGED
|
@@ -370,6 +370,20 @@ interface ChatCompletionCreateParams {
|
|
|
370
370
|
* rather than filtering lines — so a frame the server tags with a named
|
|
371
371
|
* `event:` is dropped in one piece instead of having its `data:` line mistaken
|
|
372
372
|
* for a chat chunk (issue #1398).
|
|
373
|
+
*
|
|
374
|
+
* Each surviving frame goes through {@link parseStreamFrame}, which throws on
|
|
375
|
+
* the API's in-band `{"error": …}` failure reports and on a frame that isn't a
|
|
376
|
+
* chunk. The error frames used to be yielded *as* chunks (`JSON.parse` succeeds
|
|
377
|
+
* on them), so a worker crash surfaced as a `TypeError` on `chunk.choices[0]`
|
|
378
|
+
* rather than as something a caller could catch and read (issue #2252).
|
|
379
|
+
*
|
|
380
|
+
* `idleTimeoutMs` bounds the gap between reads, not the whole stream: the API
|
|
381
|
+
* sends a keep-alive comment every 15 s, so a healthy stream never goes quiet
|
|
382
|
+
* for long however long it runs, while a stalled one fails with an
|
|
383
|
+
* `APIConnectionError` rather than hanging (#2185). Leaving the loop before the
|
|
384
|
+
* stream ends — a `break`, or a frame that throws — aborts the request, so the
|
|
385
|
+
* connection is released and the worker stops generating tokens nobody will
|
|
386
|
+
* read (#2216).
|
|
373
387
|
*/
|
|
374
388
|
declare class Stream implements AsyncIterable<ChatCompletionChunk> {
|
|
375
389
|
private reader;
|
|
@@ -377,7 +391,8 @@ declare class Stream implements AsyncIterable<ChatCompletionChunk> {
|
|
|
377
391
|
private sse;
|
|
378
392
|
private done;
|
|
379
393
|
private controller;
|
|
380
|
-
|
|
394
|
+
private idleTimeoutMs;
|
|
395
|
+
constructor(response: Response, controller: AbortController, idleTimeoutMs?: number);
|
|
381
396
|
[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk>;
|
|
382
397
|
abort(): void;
|
|
383
398
|
}
|
|
@@ -693,7 +708,6 @@ declare class Pendra {
|
|
|
693
708
|
_fetch(path: string, options: {
|
|
694
709
|
method: string;
|
|
695
710
|
body?: Record<string, unknown>;
|
|
696
|
-
stream?: boolean;
|
|
697
711
|
headers?: Record<string, string>;
|
|
698
712
|
}): Promise<{
|
|
699
713
|
response: Response;
|
|
@@ -729,5 +743,58 @@ declare class AuthenticationError extends APIStatusError {
|
|
|
729
743
|
declare class RateLimitError extends APIStatusError {
|
|
730
744
|
constructor(message?: string);
|
|
731
745
|
}
|
|
746
|
+
/**
|
|
747
|
+
* Raised when a response arrives but isn't the shape the SDK expects.
|
|
748
|
+
*
|
|
749
|
+
* A server or proxy problem, not a transport one: the request reached Pendra
|
|
750
|
+
* and came back, but the body could not be read as the documented type — a 200
|
|
751
|
+
* missing a required field, a captive-portal HTML page from a corporate proxy,
|
|
752
|
+
* a truncated body.
|
|
753
|
+
*
|
|
754
|
+
* Deliberately NOT an `APIConnectionError`: retrying a response that will never
|
|
755
|
+
* parse just burns the retry budget, so callers that retry on connection
|
|
756
|
+
* failures should let this one through. `body` holds a short excerpt of what
|
|
757
|
+
* actually came back.
|
|
758
|
+
*/
|
|
759
|
+
declare class APIResponseValidationError extends APIError {
|
|
760
|
+
/** How much of the offending body to keep in the message. */
|
|
761
|
+
static readonly BODY_EXCERPT_CHARS = 200;
|
|
762
|
+
readonly body: string | undefined;
|
|
763
|
+
constructor(message: string, options?: {
|
|
764
|
+
status?: number;
|
|
765
|
+
body?: string;
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Raised when a stream reports a failure in-band, after HTTP 200.
|
|
770
|
+
*
|
|
771
|
+
* A streaming response commits its status line before the worker has done any
|
|
772
|
+
* work, so anything that goes wrong afterwards — the worker crashing, the
|
|
773
|
+
* request timing out, the fleet being at capacity — can only be described in
|
|
774
|
+
* the body. The API sends `data: {"error": {…}}` followed by `data: [DONE]`,
|
|
775
|
+
* and this error is how the SDK surfaces that instead of ending the stream as
|
|
776
|
+
* though it had succeeded.
|
|
777
|
+
*
|
|
778
|
+
* `requestId` and `workerId` identify the failed inference to Pendra support.
|
|
779
|
+
*
|
|
780
|
+
* Note this extends `APIError`, not `APIStatusError`, because the API omits
|
|
781
|
+
* `code` on some frames (the timeout and the generic catch-all) — so `status`
|
|
782
|
+
* is genuinely optional here, which `APIStatusError`'s always-present `status`
|
|
783
|
+
* cannot express. Check `status` for undefined before comparing it.
|
|
784
|
+
*/
|
|
785
|
+
declare class APIStreamError extends APIError {
|
|
786
|
+
readonly type: string | undefined;
|
|
787
|
+
readonly code: number | undefined;
|
|
788
|
+
readonly requestId: string | undefined;
|
|
789
|
+
readonly workerId: string | undefined;
|
|
790
|
+
readonly workerName: string | undefined;
|
|
791
|
+
constructor(message: string, options?: {
|
|
792
|
+
type?: string;
|
|
793
|
+
code?: number;
|
|
794
|
+
requestId?: string;
|
|
795
|
+
workerId?: string;
|
|
796
|
+
workerName?: string;
|
|
797
|
+
});
|
|
798
|
+
}
|
|
732
799
|
|
|
733
|
-
export { APIConnectionError, APIError, APIStatusError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
|
|
800
|
+
export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, APIStreamError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
|
package/dist/index.js
CHANGED
|
@@ -32,7 +32,9 @@ var index_exports = {};
|
|
|
32
32
|
__export(index_exports, {
|
|
33
33
|
APIConnectionError: () => APIConnectionError,
|
|
34
34
|
APIError: () => APIError,
|
|
35
|
+
APIResponseValidationError: () => APIResponseValidationError,
|
|
35
36
|
APIStatusError: () => APIStatusError,
|
|
37
|
+
APIStreamError: () => APIStreamError,
|
|
36
38
|
AuthenticationError: () => AuthenticationError,
|
|
37
39
|
Pendra: () => Pendra,
|
|
38
40
|
PrivateInferenceError: () => PrivateInferenceError,
|
|
@@ -75,6 +77,33 @@ var RateLimitError = class extends APIStatusError {
|
|
|
75
77
|
this.name = "RateLimitError";
|
|
76
78
|
}
|
|
77
79
|
};
|
|
80
|
+
var _APIResponseValidationError = class _APIResponseValidationError extends APIError {
|
|
81
|
+
constructor(message, options = {}) {
|
|
82
|
+
const { status, body } = options;
|
|
83
|
+
let text = message;
|
|
84
|
+
if (body) {
|
|
85
|
+
const max = _APIResponseValidationError.BODY_EXCERPT_CHARS;
|
|
86
|
+
text = `${message} (body: ${body.slice(0, max)}${body.length > max ? "\u2026" : ""})`;
|
|
87
|
+
}
|
|
88
|
+
super(text, status);
|
|
89
|
+
this.name = "APIResponseValidationError";
|
|
90
|
+
this.body = body;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
/** How much of the offending body to keep in the message. */
|
|
94
|
+
_APIResponseValidationError.BODY_EXCERPT_CHARS = 200;
|
|
95
|
+
var APIResponseValidationError = _APIResponseValidationError;
|
|
96
|
+
var APIStreamError = class extends APIError {
|
|
97
|
+
constructor(message, options = {}) {
|
|
98
|
+
super(message, typeof options.code === "number" ? options.code : void 0);
|
|
99
|
+
this.name = "APIStreamError";
|
|
100
|
+
this.type = options.type;
|
|
101
|
+
this.code = options.code;
|
|
102
|
+
this.requestId = options.requestId;
|
|
103
|
+
this.workerId = options.workerId;
|
|
104
|
+
this.workerName = options.workerName;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
78
107
|
|
|
79
108
|
// src/resources/audio/transcriptions.ts
|
|
80
109
|
var MAX_FILE_SIZE = 25 * 1024 * 1024;
|
|
@@ -204,6 +233,89 @@ var Audio = class {
|
|
|
204
233
|
}
|
|
205
234
|
};
|
|
206
235
|
|
|
236
|
+
// src/_parsing.ts
|
|
237
|
+
function asString(v) {
|
|
238
|
+
return typeof v === "string" ? v : void 0;
|
|
239
|
+
}
|
|
240
|
+
function throwIfInBandError(parsed) {
|
|
241
|
+
if (typeof parsed !== "object" || parsed === null) return;
|
|
242
|
+
const err = parsed.error;
|
|
243
|
+
if (typeof err !== "object" || err === null || Array.isArray(err)) return;
|
|
244
|
+
const e = err;
|
|
245
|
+
throw new APIStreamError(
|
|
246
|
+
asString(e.message) ?? "The server reported an error mid-stream",
|
|
247
|
+
{
|
|
248
|
+
type: asString(e.type),
|
|
249
|
+
code: typeof e.code === "number" ? e.code : void 0,
|
|
250
|
+
requestId: asString(e.request_id),
|
|
251
|
+
workerId: asString(e.worker_id),
|
|
252
|
+
workerName: asString(e.worker_name)
|
|
253
|
+
}
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
function isChunkShaped(parsed) {
|
|
257
|
+
if (typeof parsed !== "object" || parsed === null) return false;
|
|
258
|
+
const c = parsed;
|
|
259
|
+
return typeof c.id === "string" && typeof c.model === "string" && Array.isArray(c.choices);
|
|
260
|
+
}
|
|
261
|
+
function parseStreamFrame(data, label = "Stream frame") {
|
|
262
|
+
let parsed;
|
|
263
|
+
try {
|
|
264
|
+
parsed = JSON.parse(data);
|
|
265
|
+
} catch {
|
|
266
|
+
throw new APIResponseValidationError(`${label} was not valid JSON`, { body: data });
|
|
267
|
+
}
|
|
268
|
+
throwIfInBandError(parsed);
|
|
269
|
+
if (!isChunkShaped(parsed)) {
|
|
270
|
+
throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {
|
|
271
|
+
body: data
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
return parsed;
|
|
275
|
+
}
|
|
276
|
+
function completionFrom(parsed, body, status) {
|
|
277
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
278
|
+
throw new APIResponseValidationError("Response was not a chat completion", { status, body });
|
|
279
|
+
}
|
|
280
|
+
const c = parsed;
|
|
281
|
+
if (typeof c.id !== "string" || typeof c.model !== "string" || !Array.isArray(c.choices)) {
|
|
282
|
+
throw new APIResponseValidationError("Response was not a chat completion", { status, body });
|
|
283
|
+
}
|
|
284
|
+
return parsed;
|
|
285
|
+
}
|
|
286
|
+
async function parseCompletion(response) {
|
|
287
|
+
const body = await response.text();
|
|
288
|
+
let parsed;
|
|
289
|
+
try {
|
|
290
|
+
parsed = JSON.parse(body);
|
|
291
|
+
} catch {
|
|
292
|
+
throw new APIResponseValidationError("Response was not valid JSON", {
|
|
293
|
+
status: response.status,
|
|
294
|
+
body
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
return completionFrom(parsed, body, response.status);
|
|
298
|
+
}
|
|
299
|
+
function parseDecryptedCompletion(json, status) {
|
|
300
|
+
let parsed;
|
|
301
|
+
try {
|
|
302
|
+
parsed = JSON.parse(json);
|
|
303
|
+
} catch {
|
|
304
|
+
throw new APIResponseValidationError("Decrypted response was not valid JSON", {
|
|
305
|
+
status,
|
|
306
|
+
body: json
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
try {
|
|
310
|
+
return completionFrom(parsed, json, status);
|
|
311
|
+
} catch {
|
|
312
|
+
throw new APIResponseValidationError("Decrypted response was not a chat completion", {
|
|
313
|
+
status,
|
|
314
|
+
body: json
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
207
319
|
// src/_sse.ts
|
|
208
320
|
var DEFAULT_EVENT = "message";
|
|
209
321
|
function fieldValue(line, name) {
|
|
@@ -273,7 +385,7 @@ var SseDecoder = class {
|
|
|
273
385
|
|
|
274
386
|
// src/streaming.ts
|
|
275
387
|
var Stream = class {
|
|
276
|
-
constructor(response, controller) {
|
|
388
|
+
constructor(response, controller, idleTimeoutMs) {
|
|
277
389
|
this.decoder = new TextDecoder();
|
|
278
390
|
this.sse = new SseDecoder();
|
|
279
391
|
this.done = false;
|
|
@@ -282,21 +394,22 @@ var Stream = class {
|
|
|
282
394
|
}
|
|
283
395
|
this.reader = response.body.getReader();
|
|
284
396
|
this.controller = controller;
|
|
397
|
+
this.idleTimeoutMs = idleTimeoutMs;
|
|
285
398
|
}
|
|
286
399
|
async *[Symbol.asyncIterator]() {
|
|
287
400
|
try {
|
|
288
401
|
while (!this.done) {
|
|
289
|
-
const { value, done: readerDone } = await
|
|
402
|
+
const { value, done: readerDone } = await readWithIdleTimeout(
|
|
403
|
+
this.reader,
|
|
404
|
+
this.idleTimeoutMs
|
|
405
|
+
);
|
|
290
406
|
const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
|
|
291
407
|
for (const data of payloads) {
|
|
292
408
|
if (data === "[DONE]") {
|
|
293
409
|
this.done = true;
|
|
294
410
|
return;
|
|
295
411
|
}
|
|
296
|
-
|
|
297
|
-
yield JSON.parse(data);
|
|
298
|
-
} catch {
|
|
299
|
-
}
|
|
412
|
+
yield parseStreamFrame(data);
|
|
300
413
|
}
|
|
301
414
|
if (readerDone) {
|
|
302
415
|
this.done = true;
|
|
@@ -304,7 +417,7 @@ var Stream = class {
|
|
|
304
417
|
}
|
|
305
418
|
}
|
|
306
419
|
} finally {
|
|
307
|
-
this.reader.
|
|
420
|
+
releaseReader(this.reader, this.controller, this.done);
|
|
308
421
|
}
|
|
309
422
|
}
|
|
310
423
|
abort() {
|
|
@@ -312,11 +425,34 @@ var Stream = class {
|
|
|
312
425
|
this.controller.abort();
|
|
313
426
|
}
|
|
314
427
|
};
|
|
428
|
+
async function readWithIdleTimeout(reader, idleTimeoutMs) {
|
|
429
|
+
if (!idleTimeoutMs) return reader.read();
|
|
430
|
+
let timer;
|
|
431
|
+
const idle = new Promise((_, reject) => {
|
|
432
|
+
timer = setTimeout(
|
|
433
|
+
() => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),
|
|
434
|
+
idleTimeoutMs
|
|
435
|
+
);
|
|
436
|
+
});
|
|
437
|
+
try {
|
|
438
|
+
return await Promise.race([reader.read(), idle]);
|
|
439
|
+
} finally {
|
|
440
|
+
clearTimeout(timer);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
function releaseReader(reader, controller, finished) {
|
|
444
|
+
if (!finished) {
|
|
445
|
+
controller.abort();
|
|
446
|
+
reader.cancel().catch(() => {
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
reader.releaseLock();
|
|
450
|
+
}
|
|
315
451
|
|
|
316
452
|
// src/_privateStreaming.ts
|
|
317
453
|
var DECODER = new TextDecoder();
|
|
318
454
|
var EncryptedStream = class {
|
|
319
|
-
constructor(response, controller, decryptor) {
|
|
455
|
+
constructor(response, controller, decryptor, idleTimeoutMs) {
|
|
320
456
|
this.decoder = new TextDecoder();
|
|
321
457
|
this.sse = new SseDecoder();
|
|
322
458
|
this.done = false;
|
|
@@ -326,26 +462,31 @@ var EncryptedStream = class {
|
|
|
326
462
|
this.reader = response.body.getReader();
|
|
327
463
|
this.controller = controller;
|
|
328
464
|
this.decryptor = decryptor;
|
|
465
|
+
this.idleTimeoutMs = idleTimeoutMs;
|
|
329
466
|
}
|
|
330
467
|
async *[Symbol.asyncIterator]() {
|
|
331
468
|
try {
|
|
332
469
|
while (!this.done) {
|
|
333
|
-
const { value, done: readerDone } = await
|
|
470
|
+
const { value, done: readerDone } = await readWithIdleTimeout(
|
|
471
|
+
this.reader,
|
|
472
|
+
this.idleTimeoutMs
|
|
473
|
+
);
|
|
334
474
|
const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
|
|
335
475
|
for (const data of payloads) {
|
|
336
476
|
if (data === "[DONE]") {
|
|
337
477
|
this.done = true;
|
|
338
478
|
return;
|
|
339
479
|
}
|
|
340
|
-
let
|
|
480
|
+
let inner;
|
|
341
481
|
try {
|
|
342
|
-
|
|
482
|
+
inner = JSON.parse(data).pendra_encrypted;
|
|
343
483
|
} catch {
|
|
344
|
-
|
|
484
|
+
throw new APIResponseValidationError("Stream frame was not valid JSON", {
|
|
485
|
+
body: data
|
|
486
|
+
});
|
|
345
487
|
}
|
|
346
|
-
const inner = parsed.pendra_encrypted;
|
|
347
488
|
if (!inner) {
|
|
348
|
-
yield
|
|
489
|
+
yield parseStreamFrame(data);
|
|
349
490
|
continue;
|
|
350
491
|
}
|
|
351
492
|
const plain = this.decryptor.openChunk(inner);
|
|
@@ -357,10 +498,7 @@ var EncryptedStream = class {
|
|
|
357
498
|
}
|
|
358
499
|
continue;
|
|
359
500
|
}
|
|
360
|
-
|
|
361
|
-
yield JSON.parse(chunkJson);
|
|
362
|
-
} catch {
|
|
363
|
-
}
|
|
501
|
+
yield parseStreamFrame(chunkJson, "Decrypted stream frame");
|
|
364
502
|
}
|
|
365
503
|
if (readerDone) {
|
|
366
504
|
this.done = true;
|
|
@@ -368,7 +506,7 @@ var EncryptedStream = class {
|
|
|
368
506
|
}
|
|
369
507
|
}
|
|
370
508
|
} finally {
|
|
371
|
-
this.reader.
|
|
509
|
+
releaseReader(this.reader, this.controller, this.done);
|
|
372
510
|
}
|
|
373
511
|
}
|
|
374
512
|
abort() {
|
|
@@ -397,15 +535,15 @@ var Completions = class {
|
|
|
397
535
|
if (params.stream) {
|
|
398
536
|
const { response: response2, controller } = await this.client._fetch(
|
|
399
537
|
"/api/v1/chat/completions",
|
|
400
|
-
{ method: "POST", body,
|
|
538
|
+
{ method: "POST", body, headers }
|
|
401
539
|
);
|
|
402
|
-
return new Stream(response2, controller);
|
|
540
|
+
return new Stream(response2, controller, this.client.timeout);
|
|
403
541
|
}
|
|
404
542
|
const { response } = await this.client._fetch(
|
|
405
543
|
"/api/v1/chat/completions",
|
|
406
544
|
{ method: "POST", body, headers }
|
|
407
545
|
);
|
|
408
|
-
return
|
|
546
|
+
return parseCompletion(response);
|
|
409
547
|
}
|
|
410
548
|
async createEncrypted(params, body, headers) {
|
|
411
549
|
const engine = await this.client._privateEngine();
|
|
@@ -420,20 +558,29 @@ var Completions = class {
|
|
|
420
558
|
if (stream) {
|
|
421
559
|
const { response: response2, controller } = await this.client._fetch(
|
|
422
560
|
"/api/v1/chat/completions",
|
|
423
|
-
{ method: "POST", body: topLevel,
|
|
561
|
+
{ method: "POST", body: topLevel, headers }
|
|
424
562
|
);
|
|
425
|
-
return new EncryptedStream(response2, controller, decryptor);
|
|
563
|
+
return new EncryptedStream(response2, controller, decryptor, this.client.timeout);
|
|
426
564
|
}
|
|
427
565
|
const { response } = await this.client._fetch(
|
|
428
566
|
"/api/v1/chat/completions",
|
|
429
567
|
{ method: "POST", body: topLevel, headers }
|
|
430
568
|
);
|
|
431
|
-
const
|
|
569
|
+
const raw = await response.text();
|
|
570
|
+
let wrapper;
|
|
571
|
+
try {
|
|
572
|
+
wrapper = JSON.parse(raw);
|
|
573
|
+
} catch {
|
|
574
|
+
throw new APIResponseValidationError("Response was not valid JSON", {
|
|
575
|
+
status: response.status,
|
|
576
|
+
body: raw
|
|
577
|
+
});
|
|
578
|
+
}
|
|
432
579
|
if (!wrapper.pendra_encrypted) {
|
|
433
|
-
return
|
|
580
|
+
return parseDecryptedCompletion(raw, response.status);
|
|
434
581
|
}
|
|
435
582
|
const plain = decryptor.openResult(wrapper.pendra_encrypted);
|
|
436
|
-
return
|
|
583
|
+
return parseDecryptedCompletion(DECODER2.decode(plain), response.status);
|
|
437
584
|
}
|
|
438
585
|
};
|
|
439
586
|
|
|
@@ -667,7 +814,7 @@ var Rerank = class {
|
|
|
667
814
|
};
|
|
668
815
|
|
|
669
816
|
// src/version.ts
|
|
670
|
-
var VERSION = "0.
|
|
817
|
+
var VERSION = "0.13.1";
|
|
671
818
|
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
672
819
|
|
|
673
820
|
// src/_hpke.ts
|
|
@@ -1358,11 +1505,8 @@ var Pendra = class {
|
|
|
1358
1505
|
err instanceof Error ? err.message : "Failed to connect to the Pendra API"
|
|
1359
1506
|
);
|
|
1360
1507
|
}
|
|
1361
|
-
|
|
1362
|
-
clearTimeout(timeoutId);
|
|
1363
|
-
}
|
|
1508
|
+
clearTimeout(timeoutId);
|
|
1364
1509
|
if (!response.ok) {
|
|
1365
|
-
clearTimeout(timeoutId);
|
|
1366
1510
|
this.invalidateKeyCacheIfRekeyed(response);
|
|
1367
1511
|
let message;
|
|
1368
1512
|
try {
|
|
@@ -1405,7 +1549,9 @@ var index_default = Pendra;
|
|
|
1405
1549
|
0 && (module.exports = {
|
|
1406
1550
|
APIConnectionError,
|
|
1407
1551
|
APIError,
|
|
1552
|
+
APIResponseValidationError,
|
|
1408
1553
|
APIStatusError,
|
|
1554
|
+
APIStreamError,
|
|
1409
1555
|
AuthenticationError,
|
|
1410
1556
|
Pendra,
|
|
1411
1557
|
PrivateInferenceError,
|