pendra 0.1.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/README.md ADDED
@@ -0,0 +1,104 @@
1
+ # Pendra TypeScript SDK
2
+
3
+ Official TypeScript/JavaScript SDK for the [Pendra](https://pendra.ai) LLM inference API. Mirrors the OpenAI SDK interface for easy migration.
4
+
5
+ **Requires Node.js 18+** (uses native `fetch`). Zero runtime dependencies.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install pendra
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```typescript
16
+ import Pendra from 'pendra';
17
+
18
+ const client = new Pendra({
19
+ apiKey: 'pdr_sk_...', // or set PENDRA_API_KEY env var
20
+ });
21
+
22
+ const response = await client.chat.completions.create({
23
+ model: 'llama3.2',
24
+ messages: [{ role: 'user', content: 'Hello!' }],
25
+ });
26
+
27
+ console.log(response.choices[0].message.content);
28
+ ```
29
+
30
+ ## Streaming
31
+
32
+ ```typescript
33
+ const stream = await client.chat.completions.create({
34
+ model: 'llama3.2',
35
+ messages: [{ role: 'user', content: 'Write a poem' }],
36
+ stream: true,
37
+ });
38
+
39
+ for await (const chunk of stream) {
40
+ process.stdout.write(chunk.choices[0].delta.content ?? '');
41
+ }
42
+ ```
43
+
44
+ ## List Models
45
+
46
+ ```typescript
47
+ const models = await client.models.list();
48
+ models.forEach((m) => console.log(m.id));
49
+ ```
50
+
51
+ ## Configuration
52
+
53
+ | Option | Env var | Default |
54
+ | --------- | ---------------- | -------------------------- |
55
+ | `apiKey` | `PENDRA_API_KEY` | — |
56
+ | `baseURL` | — | `https://api.pendra.ai` |
57
+ | `timeout` | — | `120000` (ms) |
58
+
59
+ ## Migrating from OpenAI
60
+
61
+ ```diff
62
+ - import OpenAI from 'openai';
63
+ - const client = new OpenAI({ apiKey: '...' });
64
+ + import Pendra from 'pendra';
65
+ + const client = new Pendra({ apiKey: 'pdr_sk_...' });
66
+
67
+ // Everything else stays the same
68
+ const res = await client.chat.completions.create({
69
+ model: 'llama3.2',
70
+ messages: [{ role: 'user', content: 'Hi' }],
71
+ });
72
+ ```
73
+
74
+ ## Error Handling
75
+
76
+ ```typescript
77
+ import { AuthenticationError, RateLimitError, APIStatusError } from 'pendra';
78
+
79
+ try {
80
+ await client.chat.completions.create({ ... });
81
+ } catch (err) {
82
+ if (err instanceof AuthenticationError) {
83
+ console.error('Bad API key');
84
+ } else if (err instanceof RateLimitError) {
85
+ console.error('Slow down');
86
+ } else if (err instanceof APIStatusError) {
87
+ console.error(`API error ${err.status}: ${err.message}`);
88
+ }
89
+ }
90
+ ```
91
+
92
+ ## Self-Hosted Workers
93
+
94
+ Run inference on your own GPUs with a single command. Your prompts and completions never leave your infrastructure.
95
+
96
+ ```bash
97
+ curl -fsSL https://get.pendra.ai/worker | bash
98
+ ```
99
+
100
+ See the [Workers documentation](https://pendra.ai/docs/workers) for full setup instructions.
101
+
102
+ ## Licence
103
+
104
+ Apache-2.0
@@ -0,0 +1,134 @@
1
+ interface Usage {
2
+ prompt_tokens: number;
3
+ completion_tokens: number;
4
+ total_tokens: number;
5
+ }
6
+ interface ChatCompletionMessage {
7
+ role: string;
8
+ content: string | null;
9
+ }
10
+ interface Choice {
11
+ index: number;
12
+ message: ChatCompletionMessage;
13
+ finish_reason: string | null;
14
+ }
15
+ interface ChatCompletion {
16
+ id: string;
17
+ object: string;
18
+ created: number;
19
+ model: string;
20
+ choices: Choice[];
21
+ usage: Usage | null;
22
+ }
23
+ interface ChoiceDelta {
24
+ role?: string | null;
25
+ content?: string | null;
26
+ }
27
+ interface StreamChoice {
28
+ index: number;
29
+ delta: ChoiceDelta;
30
+ finish_reason: string | null;
31
+ }
32
+ interface ChatCompletionChunk {
33
+ id: string;
34
+ object: string;
35
+ created: number;
36
+ model: string;
37
+ choices: StreamChoice[];
38
+ }
39
+ interface ChatCompletionCreateParams {
40
+ model: string;
41
+ messages: Array<{
42
+ role: string;
43
+ content: string;
44
+ }>;
45
+ temperature?: number | null;
46
+ max_tokens?: number | null;
47
+ top_p?: number | null;
48
+ stop?: string | string[] | null;
49
+ stream?: boolean;
50
+ }
51
+
52
+ declare class Stream implements AsyncIterable<ChatCompletionChunk> {
53
+ private reader;
54
+ private decoder;
55
+ private buffer;
56
+ private done;
57
+ private controller;
58
+ constructor(response: Response, controller: AbortController);
59
+ [Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk>;
60
+ abort(): void;
61
+ }
62
+
63
+ declare class Completions {
64
+ private client;
65
+ constructor(client: Pendra);
66
+ create(params: ChatCompletionCreateParams & {
67
+ stream: true;
68
+ }): Promise<Stream>;
69
+ create(params: ChatCompletionCreateParams & {
70
+ stream?: false;
71
+ }): Promise<ChatCompletion>;
72
+ create(params: ChatCompletionCreateParams): Promise<ChatCompletion | Stream>;
73
+ }
74
+
75
+ declare class Chat {
76
+ completions: Completions;
77
+ constructor(client: Pendra);
78
+ }
79
+
80
+ interface Model {
81
+ id: string;
82
+ object: string;
83
+ created: number;
84
+ owned_by: string;
85
+ }
86
+
87
+ declare class Models {
88
+ private client;
89
+ constructor(client: Pendra);
90
+ list(): Promise<Model[]>;
91
+ }
92
+
93
+ interface PendraOptions {
94
+ apiKey?: string;
95
+ baseURL?: string;
96
+ timeout?: number;
97
+ }
98
+ declare class Pendra {
99
+ readonly apiKey: string;
100
+ readonly baseURL: string;
101
+ readonly timeout: number;
102
+ chat: Chat;
103
+ models: Models;
104
+ constructor(options?: PendraOptions);
105
+ /** @internal */
106
+ _fetch(path: string, options: {
107
+ method: string;
108
+ body?: Record<string, unknown>;
109
+ stream?: boolean;
110
+ }): Promise<{
111
+ response: Response;
112
+ controller: AbortController;
113
+ }>;
114
+ }
115
+
116
+ declare class APIError extends Error {
117
+ readonly status: number | undefined;
118
+ constructor(message: string, status?: number);
119
+ }
120
+ declare class APIConnectionError extends APIError {
121
+ constructor(message?: string);
122
+ }
123
+ declare class APIStatusError extends APIError {
124
+ readonly status: number;
125
+ constructor(message: string, status: number);
126
+ }
127
+ declare class AuthenticationError extends APIStatusError {
128
+ constructor(message?: string);
129
+ }
130
+ declare class RateLimitError extends APIStatusError {
131
+ constructor(message?: string);
132
+ }
133
+
134
+ export { APIConnectionError, APIError, APIStatusError, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionCreateParams, type ChatCompletionMessage, type Choice, type ChoiceDelta, type Model, Pendra, type PendraOptions, RateLimitError, Stream, type StreamChoice, type Usage, Pendra as default };
@@ -0,0 +1,134 @@
1
+ interface Usage {
2
+ prompt_tokens: number;
3
+ completion_tokens: number;
4
+ total_tokens: number;
5
+ }
6
+ interface ChatCompletionMessage {
7
+ role: string;
8
+ content: string | null;
9
+ }
10
+ interface Choice {
11
+ index: number;
12
+ message: ChatCompletionMessage;
13
+ finish_reason: string | null;
14
+ }
15
+ interface ChatCompletion {
16
+ id: string;
17
+ object: string;
18
+ created: number;
19
+ model: string;
20
+ choices: Choice[];
21
+ usage: Usage | null;
22
+ }
23
+ interface ChoiceDelta {
24
+ role?: string | null;
25
+ content?: string | null;
26
+ }
27
+ interface StreamChoice {
28
+ index: number;
29
+ delta: ChoiceDelta;
30
+ finish_reason: string | null;
31
+ }
32
+ interface ChatCompletionChunk {
33
+ id: string;
34
+ object: string;
35
+ created: number;
36
+ model: string;
37
+ choices: StreamChoice[];
38
+ }
39
+ interface ChatCompletionCreateParams {
40
+ model: string;
41
+ messages: Array<{
42
+ role: string;
43
+ content: string;
44
+ }>;
45
+ temperature?: number | null;
46
+ max_tokens?: number | null;
47
+ top_p?: number | null;
48
+ stop?: string | string[] | null;
49
+ stream?: boolean;
50
+ }
51
+
52
+ declare class Stream implements AsyncIterable<ChatCompletionChunk> {
53
+ private reader;
54
+ private decoder;
55
+ private buffer;
56
+ private done;
57
+ private controller;
58
+ constructor(response: Response, controller: AbortController);
59
+ [Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk>;
60
+ abort(): void;
61
+ }
62
+
63
+ declare class Completions {
64
+ private client;
65
+ constructor(client: Pendra);
66
+ create(params: ChatCompletionCreateParams & {
67
+ stream: true;
68
+ }): Promise<Stream>;
69
+ create(params: ChatCompletionCreateParams & {
70
+ stream?: false;
71
+ }): Promise<ChatCompletion>;
72
+ create(params: ChatCompletionCreateParams): Promise<ChatCompletion | Stream>;
73
+ }
74
+
75
+ declare class Chat {
76
+ completions: Completions;
77
+ constructor(client: Pendra);
78
+ }
79
+
80
+ interface Model {
81
+ id: string;
82
+ object: string;
83
+ created: number;
84
+ owned_by: string;
85
+ }
86
+
87
+ declare class Models {
88
+ private client;
89
+ constructor(client: Pendra);
90
+ list(): Promise<Model[]>;
91
+ }
92
+
93
+ interface PendraOptions {
94
+ apiKey?: string;
95
+ baseURL?: string;
96
+ timeout?: number;
97
+ }
98
+ declare class Pendra {
99
+ readonly apiKey: string;
100
+ readonly baseURL: string;
101
+ readonly timeout: number;
102
+ chat: Chat;
103
+ models: Models;
104
+ constructor(options?: PendraOptions);
105
+ /** @internal */
106
+ _fetch(path: string, options: {
107
+ method: string;
108
+ body?: Record<string, unknown>;
109
+ stream?: boolean;
110
+ }): Promise<{
111
+ response: Response;
112
+ controller: AbortController;
113
+ }>;
114
+ }
115
+
116
+ declare class APIError extends Error {
117
+ readonly status: number | undefined;
118
+ constructor(message: string, status?: number);
119
+ }
120
+ declare class APIConnectionError extends APIError {
121
+ constructor(message?: string);
122
+ }
123
+ declare class APIStatusError extends APIError {
124
+ readonly status: number;
125
+ constructor(message: string, status: number);
126
+ }
127
+ declare class AuthenticationError extends APIStatusError {
128
+ constructor(message?: string);
129
+ }
130
+ declare class RateLimitError extends APIStatusError {
131
+ constructor(message?: string);
132
+ }
133
+
134
+ export { APIConnectionError, APIError, APIStatusError, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionCreateParams, type ChatCompletionMessage, type Choice, type ChoiceDelta, type Model, Pendra, type PendraOptions, RateLimitError, Stream, type StreamChoice, type Usage, Pendra as default };
package/dist/index.js ADDED
@@ -0,0 +1,244 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ APIConnectionError: () => APIConnectionError,
24
+ APIError: () => APIError,
25
+ APIStatusError: () => APIStatusError,
26
+ AuthenticationError: () => AuthenticationError,
27
+ Pendra: () => Pendra,
28
+ RateLimitError: () => RateLimitError,
29
+ Stream: () => Stream,
30
+ default: () => index_default
31
+ });
32
+ module.exports = __toCommonJS(index_exports);
33
+
34
+ // src/streaming.ts
35
+ var Stream = class {
36
+ constructor(response, controller) {
37
+ this.decoder = new TextDecoder();
38
+ this.buffer = "";
39
+ this.done = false;
40
+ if (!response.body) {
41
+ throw new Error("Response body is null \u2014 streaming not supported");
42
+ }
43
+ this.reader = response.body.getReader();
44
+ this.controller = controller;
45
+ }
46
+ async *[Symbol.asyncIterator]() {
47
+ try {
48
+ while (!this.done) {
49
+ const { value, done: readerDone } = await this.reader.read();
50
+ if (readerDone) {
51
+ this.done = true;
52
+ break;
53
+ }
54
+ this.buffer += this.decoder.decode(value, { stream: true });
55
+ const lines = this.buffer.split("\n");
56
+ this.buffer = lines.pop() ?? "";
57
+ for (const line of lines) {
58
+ const trimmed = line.trim();
59
+ if (!trimmed || trimmed.startsWith(":")) continue;
60
+ if (!trimmed.startsWith("data: ")) continue;
61
+ const data = trimmed.slice(6);
62
+ if (data === "[DONE]") {
63
+ this.done = true;
64
+ return;
65
+ }
66
+ try {
67
+ yield JSON.parse(data);
68
+ } catch {
69
+ }
70
+ }
71
+ }
72
+ } finally {
73
+ this.reader.releaseLock();
74
+ }
75
+ }
76
+ abort() {
77
+ this.done = true;
78
+ this.controller.abort();
79
+ }
80
+ };
81
+
82
+ // src/resources/chat/completions.ts
83
+ var Completions = class {
84
+ constructor(client) {
85
+ this.client = client;
86
+ }
87
+ async create(params) {
88
+ const body = {
89
+ model: params.model,
90
+ messages: params.messages
91
+ };
92
+ if (params.stream != null) body.stream = params.stream;
93
+ if (params.temperature != null) body.temperature = params.temperature;
94
+ if (params.max_tokens != null) body.max_tokens = params.max_tokens;
95
+ if (params.top_p != null) body.top_p = params.top_p;
96
+ if (params.stop != null) body.stop = params.stop;
97
+ if (params.stream) {
98
+ const { response: response2, controller } = await this.client._fetch(
99
+ "/api/v1/chat/completions",
100
+ { method: "POST", body, stream: true }
101
+ );
102
+ return new Stream(response2, controller);
103
+ }
104
+ const { response } = await this.client._fetch(
105
+ "/api/v1/chat/completions",
106
+ { method: "POST", body }
107
+ );
108
+ return await response.json();
109
+ }
110
+ };
111
+
112
+ // src/resources/chat/index.ts
113
+ var Chat = class {
114
+ constructor(client) {
115
+ this.completions = new Completions(client);
116
+ }
117
+ };
118
+
119
+ // src/resources/models.ts
120
+ var Models = class {
121
+ constructor(client) {
122
+ this.client = client;
123
+ }
124
+ async list() {
125
+ const { response } = await this.client._fetch("/api/v1/models", {
126
+ method: "GET"
127
+ });
128
+ const data = await response.json();
129
+ return data.data;
130
+ }
131
+ };
132
+
133
+ // src/errors.ts
134
+ var APIError = class extends Error {
135
+ constructor(message, status) {
136
+ super(message);
137
+ this.name = "APIError";
138
+ this.status = status;
139
+ }
140
+ };
141
+ var APIConnectionError = class extends APIError {
142
+ constructor(message = "Failed to connect to the Pendra API") {
143
+ super(message);
144
+ this.name = "APIConnectionError";
145
+ }
146
+ };
147
+ var APIStatusError = class extends APIError {
148
+ constructor(message, status) {
149
+ super(message, status);
150
+ this.name = "APIStatusError";
151
+ this.status = status;
152
+ }
153
+ };
154
+ var AuthenticationError = class extends APIStatusError {
155
+ constructor(message = "Invalid API key \u2014 check your PENDRA_API_KEY") {
156
+ super(message, 401);
157
+ this.name = "AuthenticationError";
158
+ }
159
+ };
160
+ var RateLimitError = class extends APIStatusError {
161
+ constructor(message = "Rate limit exceeded") {
162
+ super(message, 429);
163
+ this.name = "RateLimitError";
164
+ }
165
+ };
166
+
167
+ // src/client.ts
168
+ var Pendra = class {
169
+ constructor(options = {}) {
170
+ const apiKey = options.apiKey ?? (typeof process !== "undefined" ? process.env?.PENDRA_API_KEY : void 0);
171
+ if (!apiKey) {
172
+ throw new Error(
173
+ "API key is required \u2014 pass apiKey or set the PENDRA_API_KEY environment variable"
174
+ );
175
+ }
176
+ this.apiKey = apiKey;
177
+ this.baseURL = (options.baseURL ?? "https://api.pendra.ai").replace(
178
+ /\/$/,
179
+ ""
180
+ );
181
+ this.timeout = options.timeout ?? 12e4;
182
+ this.chat = new Chat(this);
183
+ this.models = new Models(this);
184
+ }
185
+ /** @internal */
186
+ async _fetch(path, options) {
187
+ const controller = new AbortController();
188
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
189
+ const headers = {
190
+ Authorization: `Bearer ${this.apiKey}`,
191
+ "Content-Type": "application/json"
192
+ };
193
+ let response;
194
+ try {
195
+ response = await fetch(`${this.baseURL}${path}`, {
196
+ method: options.method,
197
+ headers,
198
+ body: options.body ? JSON.stringify(options.body) : void 0,
199
+ signal: controller.signal
200
+ });
201
+ } catch (err) {
202
+ clearTimeout(timeoutId);
203
+ if (err instanceof DOMException && err.name === "AbortError") {
204
+ throw new APIConnectionError(
205
+ `Request timed out after ${this.timeout}ms`
206
+ );
207
+ }
208
+ throw new APIConnectionError(
209
+ err instanceof Error ? err.message : "Failed to connect to the Pendra API"
210
+ );
211
+ }
212
+ if (!options.stream) {
213
+ clearTimeout(timeoutId);
214
+ }
215
+ if (!response.ok) {
216
+ clearTimeout(timeoutId);
217
+ let message;
218
+ try {
219
+ const body = await response.json();
220
+ message = body.detail ?? response.statusText;
221
+ } catch {
222
+ message = response.statusText;
223
+ }
224
+ if (response.status === 401) throw new AuthenticationError(message);
225
+ if (response.status === 429) throw new RateLimitError(message);
226
+ throw new APIStatusError(message, response.status);
227
+ }
228
+ return { response, controller };
229
+ }
230
+ };
231
+
232
+ // src/index.ts
233
+ var index_default = Pendra;
234
+ // Annotate the CommonJS export names for ESM import in node:
235
+ 0 && (module.exports = {
236
+ APIConnectionError,
237
+ APIError,
238
+ APIStatusError,
239
+ AuthenticationError,
240
+ Pendra,
241
+ RateLimitError,
242
+ Stream
243
+ });
244
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/streaming.ts","../src/resources/chat/completions.ts","../src/resources/chat/index.ts","../src/resources/models.ts","../src/errors.ts","../src/client.ts"],"sourcesContent":["export { Pendra } from \"./client\";\nexport type { PendraOptions } from \"./client\";\nexport { Stream } from \"./streaming\";\n\nexport type {\n ChatCompletion,\n ChatCompletionChunk,\n ChatCompletionMessage,\n ChatCompletionCreateParams,\n Choice,\n StreamChoice,\n ChoiceDelta,\n Usage,\n} from \"./types/chat\";\n\nexport type { Model } from \"./types/models\";\n\nexport {\n APIError,\n APIConnectionError,\n APIStatusError,\n AuthenticationError,\n RateLimitError,\n} from \"./errors\";\n\n// Default export for convenient usage:\n// import Pendra from 'pendra';\nimport { Pendra as _Pendra } from \"./client\";\nexport default _Pendra;\n","import type { ChatCompletionChunk } from \"./types/chat\";\n\nexport class Stream implements AsyncIterable<ChatCompletionChunk> {\n private reader: ReadableStreamDefaultReader<Uint8Array>;\n private decoder = new TextDecoder();\n private buffer = \"\";\n private done = false;\n private controller: AbortController;\n\n constructor(response: Response, controller: AbortController) {\n if (!response.body) {\n throw new Error(\"Response body is null — streaming not supported\");\n }\n this.reader = response.body.getReader();\n this.controller = controller;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {\n try {\n while (!this.done) {\n const { value, done: readerDone } = await this.reader.read();\n if (readerDone) {\n this.done = true;\n break;\n }\n\n this.buffer += this.decoder.decode(value, { stream: true });\n const lines = this.buffer.split(\"\\n\");\n this.buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\":\")) continue;\n\n if (!trimmed.startsWith(\"data: \")) continue;\n const data = trimmed.slice(6);\n\n if (data === \"[DONE]\") {\n this.done = true;\n return;\n }\n\n try {\n yield JSON.parse(data) as ChatCompletionChunk;\n } catch {\n // skip malformed JSON\n }\n }\n }\n } finally {\n this.reader.releaseLock();\n }\n }\n\n abort(): void {\n this.done = true;\n this.controller.abort();\n }\n}\n","import type { Pendra } from \"../../client\";\nimport type {\n ChatCompletion,\n ChatCompletionChunk,\n ChatCompletionCreateParams,\n} from \"../../types/chat\";\nimport { Stream } from \"../../streaming\";\n\nexport class Completions {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n create(\n params: ChatCompletionCreateParams & { stream: true },\n ): Promise<Stream>;\n create(\n params: ChatCompletionCreateParams & { stream?: false },\n ): Promise<ChatCompletion>;\n create(\n params: ChatCompletionCreateParams,\n ): Promise<ChatCompletion | Stream>;\n async create(\n params: ChatCompletionCreateParams,\n ): Promise<ChatCompletion | Stream> {\n const body: Record<string, unknown> = {\n model: params.model,\n messages: params.messages,\n };\n\n if (params.stream != null) body.stream = params.stream;\n if (params.temperature != null) body.temperature = params.temperature;\n if (params.max_tokens != null) body.max_tokens = params.max_tokens;\n if (params.top_p != null) body.top_p = params.top_p;\n if (params.stop != null) body.stop = params.stop;\n\n if (params.stream) {\n const { response, controller } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body, stream: true },\n );\n return new Stream(response, controller);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body },\n );\n return (await response.json()) as ChatCompletion;\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { Completions } from \"./completions\";\n\nexport class Chat {\n completions: Completions;\n\n constructor(client: Pendra) {\n this.completions = new Completions(client);\n }\n}\n","import type { Pendra } from \"../client\";\nimport type { Model } from \"../types/models\";\n\nexport class Models {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n async list(): Promise<Model[]> {\n const { response } = await this.client._fetch(\"/api/v1/models\", {\n method: \"GET\",\n });\n const data = (await response.json()) as { data: Model[] };\n return data.data;\n }\n}\n","export class APIError extends Error {\n readonly status: number | undefined;\n\n constructor(message: string, status?: number) {\n super(message);\n this.name = \"APIError\";\n this.status = status;\n }\n}\n\nexport class APIConnectionError extends APIError {\n constructor(message = \"Failed to connect to the Pendra API\") {\n super(message);\n this.name = \"APIConnectionError\";\n }\n}\n\nexport class APIStatusError extends APIError {\n override readonly status: number;\n\n constructor(message: string, status: number) {\n super(message, status);\n this.name = \"APIStatusError\";\n this.status = status;\n }\n}\n\nexport class AuthenticationError extends APIStatusError {\n constructor(\n message = \"Invalid API key — check your PENDRA_API_KEY\",\n ) {\n super(message, 401);\n this.name = \"AuthenticationError\";\n }\n}\n\nexport class RateLimitError extends APIStatusError {\n constructor(message = \"Rate limit exceeded\") {\n super(message, 429);\n this.name = \"RateLimitError\";\n }\n}\n","import { Chat } from \"./resources/chat/index\";\nimport { Models } from \"./resources/models\";\nimport {\n APIConnectionError,\n APIStatusError,\n AuthenticationError,\n RateLimitError,\n} from \"./errors\";\n\nexport interface PendraOptions {\n apiKey?: string;\n baseURL?: string;\n timeout?: number;\n}\n\nexport class Pendra {\n readonly apiKey: string;\n readonly baseURL: string;\n readonly timeout: number;\n\n chat: Chat;\n models: Models;\n\n constructor(options: PendraOptions = {}) {\n const apiKey =\n options.apiKey ??\n (typeof process !== \"undefined\" ? process.env?.PENDRA_API_KEY : undefined);\n\n if (!apiKey) {\n throw new Error(\n \"API key is required — pass apiKey or set the PENDRA_API_KEY environment variable\",\n );\n }\n\n this.apiKey = apiKey;\n this.baseURL = (options.baseURL ?? \"https://api.pendra.ai\").replace(\n /\\/$/,\n \"\",\n );\n this.timeout = options.timeout ?? 120_000;\n\n this.chat = new Chat(this);\n this.models = new Models(this);\n }\n\n /** @internal */\n async _fetch(\n path: string,\n options: {\n method: string;\n body?: Record<string, unknown>;\n stream?: boolean;\n },\n ): Promise<{ response: Response; controller: AbortController }> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n\n let response: Response;\n try {\n response = await fetch(`${this.baseURL}${path}`, {\n method: options.method,\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timeoutId);\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw new APIConnectionError(\n `Request timed out after ${this.timeout}ms`,\n );\n }\n throw new APIConnectionError(\n err instanceof Error ? err.message : \"Failed to connect to the Pendra API\",\n );\n }\n\n if (!options.stream) {\n clearTimeout(timeoutId);\n }\n\n if (!response.ok) {\n clearTimeout(timeoutId);\n let message: string;\n try {\n const body = (await response.json()) as { detail?: string };\n message = body.detail ?? response.statusText;\n } catch {\n message = response.statusText;\n }\n\n if (response.status === 401) throw new AuthenticationError(message);\n if (response.status === 429) throw new RateLimitError(message);\n throw new APIStatusError(message, response.status);\n }\n\n return { response, controller };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,SAAN,MAA2D;AAAA,EAOhE,YAAY,UAAoB,YAA6B;AAL7D,SAAQ,UAAU,IAAI,YAAY;AAClC,SAAQ,SAAS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,MACrB,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,mBAAa,SAAS;AACtB,UAAI,eAAe,gBAAgB,IAAI,SAAS,cAAc;AAC5D,cAAM,IAAI;AAAA,UACR,2BAA2B,KAAK,OAAO;AAAA,QACzC;AAAA,MACF;AACA,YAAM,IAAI;AAAA,QACR,eAAe,QAAQ,IAAI,UAAU;AAAA,MACvC;AAAA,IACF;AAEA,QAAI,CAAC,QAAQ,QAAQ;AACnB,mBAAa,SAAS;AAAA,IACxB;AAEA,QAAI,CAAC,SAAS,IAAI;AAChB,mBAAa,SAAS;AACtB,UAAI;AACJ,UAAI;AACF,cAAM,OAAQ,MAAM,SAAS,KAAK;AAClC,kBAAU,KAAK,UAAU,SAAS;AAAA,MACpC,QAAQ;AACN,kBAAU,SAAS;AAAA,MACrB;AAEA,UAAI,SAAS,WAAW,IAAK,OAAM,IAAI,oBAAoB,OAAO;AAClE,UAAI,SAAS,WAAW,IAAK,OAAM,IAAI,eAAe,OAAO;AAC7D,YAAM,IAAI,eAAe,SAAS,SAAS,MAAM;AAAA,IACnD;AAEA,WAAO,EAAE,UAAU,WAAW;AAAA,EAChC;AACF;;;AN3EA,IAAO,gBAAQ;","names":["response"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,211 @@
1
+ // src/streaming.ts
2
+ var Stream = class {
3
+ constructor(response, controller) {
4
+ this.decoder = new TextDecoder();
5
+ this.buffer = "";
6
+ this.done = false;
7
+ if (!response.body) {
8
+ throw new Error("Response body is null \u2014 streaming not supported");
9
+ }
10
+ this.reader = response.body.getReader();
11
+ this.controller = controller;
12
+ }
13
+ async *[Symbol.asyncIterator]() {
14
+ try {
15
+ while (!this.done) {
16
+ const { value, done: readerDone } = await this.reader.read();
17
+ if (readerDone) {
18
+ this.done = true;
19
+ break;
20
+ }
21
+ this.buffer += this.decoder.decode(value, { stream: true });
22
+ const lines = this.buffer.split("\n");
23
+ this.buffer = lines.pop() ?? "";
24
+ for (const line of lines) {
25
+ const trimmed = line.trim();
26
+ if (!trimmed || trimmed.startsWith(":")) continue;
27
+ if (!trimmed.startsWith("data: ")) continue;
28
+ const data = trimmed.slice(6);
29
+ if (data === "[DONE]") {
30
+ this.done = true;
31
+ return;
32
+ }
33
+ try {
34
+ yield JSON.parse(data);
35
+ } catch {
36
+ }
37
+ }
38
+ }
39
+ } finally {
40
+ this.reader.releaseLock();
41
+ }
42
+ }
43
+ abort() {
44
+ this.done = true;
45
+ this.controller.abort();
46
+ }
47
+ };
48
+
49
+ // src/resources/chat/completions.ts
50
+ var Completions = class {
51
+ constructor(client) {
52
+ this.client = client;
53
+ }
54
+ async create(params) {
55
+ const body = {
56
+ model: params.model,
57
+ messages: params.messages
58
+ };
59
+ if (params.stream != null) body.stream = params.stream;
60
+ if (params.temperature != null) body.temperature = params.temperature;
61
+ if (params.max_tokens != null) body.max_tokens = params.max_tokens;
62
+ if (params.top_p != null) body.top_p = params.top_p;
63
+ if (params.stop != null) body.stop = params.stop;
64
+ if (params.stream) {
65
+ const { response: response2, controller } = await this.client._fetch(
66
+ "/api/v1/chat/completions",
67
+ { method: "POST", body, stream: true }
68
+ );
69
+ return new Stream(response2, controller);
70
+ }
71
+ const { response } = await this.client._fetch(
72
+ "/api/v1/chat/completions",
73
+ { method: "POST", body }
74
+ );
75
+ return await response.json();
76
+ }
77
+ };
78
+
79
+ // src/resources/chat/index.ts
80
+ var Chat = class {
81
+ constructor(client) {
82
+ this.completions = new Completions(client);
83
+ }
84
+ };
85
+
86
+ // src/resources/models.ts
87
+ var Models = class {
88
+ constructor(client) {
89
+ this.client = client;
90
+ }
91
+ async list() {
92
+ const { response } = await this.client._fetch("/api/v1/models", {
93
+ method: "GET"
94
+ });
95
+ const data = await response.json();
96
+ return data.data;
97
+ }
98
+ };
99
+
100
+ // src/errors.ts
101
+ var APIError = class extends Error {
102
+ constructor(message, status) {
103
+ super(message);
104
+ this.name = "APIError";
105
+ this.status = status;
106
+ }
107
+ };
108
+ var APIConnectionError = class extends APIError {
109
+ constructor(message = "Failed to connect to the Pendra API") {
110
+ super(message);
111
+ this.name = "APIConnectionError";
112
+ }
113
+ };
114
+ var APIStatusError = class extends APIError {
115
+ constructor(message, status) {
116
+ super(message, status);
117
+ this.name = "APIStatusError";
118
+ this.status = status;
119
+ }
120
+ };
121
+ var AuthenticationError = class extends APIStatusError {
122
+ constructor(message = "Invalid API key \u2014 check your PENDRA_API_KEY") {
123
+ super(message, 401);
124
+ this.name = "AuthenticationError";
125
+ }
126
+ };
127
+ var RateLimitError = class extends APIStatusError {
128
+ constructor(message = "Rate limit exceeded") {
129
+ super(message, 429);
130
+ this.name = "RateLimitError";
131
+ }
132
+ };
133
+
134
+ // src/client.ts
135
+ var Pendra = class {
136
+ constructor(options = {}) {
137
+ const apiKey = options.apiKey ?? (typeof process !== "undefined" ? process.env?.PENDRA_API_KEY : void 0);
138
+ if (!apiKey) {
139
+ throw new Error(
140
+ "API key is required \u2014 pass apiKey or set the PENDRA_API_KEY environment variable"
141
+ );
142
+ }
143
+ this.apiKey = apiKey;
144
+ this.baseURL = (options.baseURL ?? "https://api.pendra.ai").replace(
145
+ /\/$/,
146
+ ""
147
+ );
148
+ this.timeout = options.timeout ?? 12e4;
149
+ this.chat = new Chat(this);
150
+ this.models = new Models(this);
151
+ }
152
+ /** @internal */
153
+ async _fetch(path, options) {
154
+ const controller = new AbortController();
155
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
156
+ const headers = {
157
+ Authorization: `Bearer ${this.apiKey}`,
158
+ "Content-Type": "application/json"
159
+ };
160
+ let response;
161
+ try {
162
+ response = await fetch(`${this.baseURL}${path}`, {
163
+ method: options.method,
164
+ headers,
165
+ body: options.body ? JSON.stringify(options.body) : void 0,
166
+ signal: controller.signal
167
+ });
168
+ } catch (err) {
169
+ clearTimeout(timeoutId);
170
+ if (err instanceof DOMException && err.name === "AbortError") {
171
+ throw new APIConnectionError(
172
+ `Request timed out after ${this.timeout}ms`
173
+ );
174
+ }
175
+ throw new APIConnectionError(
176
+ err instanceof Error ? err.message : "Failed to connect to the Pendra API"
177
+ );
178
+ }
179
+ if (!options.stream) {
180
+ clearTimeout(timeoutId);
181
+ }
182
+ if (!response.ok) {
183
+ clearTimeout(timeoutId);
184
+ let message;
185
+ try {
186
+ const body = await response.json();
187
+ message = body.detail ?? response.statusText;
188
+ } catch {
189
+ message = response.statusText;
190
+ }
191
+ if (response.status === 401) throw new AuthenticationError(message);
192
+ if (response.status === 429) throw new RateLimitError(message);
193
+ throw new APIStatusError(message, response.status);
194
+ }
195
+ return { response, controller };
196
+ }
197
+ };
198
+
199
+ // src/index.ts
200
+ var index_default = Pendra;
201
+ export {
202
+ APIConnectionError,
203
+ APIError,
204
+ APIStatusError,
205
+ AuthenticationError,
206
+ Pendra,
207
+ RateLimitError,
208
+ Stream,
209
+ index_default as default
210
+ };
211
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/streaming.ts","../src/resources/chat/completions.ts","../src/resources/chat/index.ts","../src/resources/models.ts","../src/errors.ts","../src/client.ts","../src/index.ts"],"sourcesContent":["import type { ChatCompletionChunk } from \"./types/chat\";\n\nexport class Stream implements AsyncIterable<ChatCompletionChunk> {\n private reader: ReadableStreamDefaultReader<Uint8Array>;\n private decoder = new TextDecoder();\n private buffer = \"\";\n private done = false;\n private controller: AbortController;\n\n constructor(response: Response, controller: AbortController) {\n if (!response.body) {\n throw new Error(\"Response body is null — streaming not supported\");\n }\n this.reader = response.body.getReader();\n this.controller = controller;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk> {\n try {\n while (!this.done) {\n const { value, done: readerDone } = await this.reader.read();\n if (readerDone) {\n this.done = true;\n break;\n }\n\n this.buffer += this.decoder.decode(value, { stream: true });\n const lines = this.buffer.split(\"\\n\");\n this.buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\":\")) continue;\n\n if (!trimmed.startsWith(\"data: \")) continue;\n const data = trimmed.slice(6);\n\n if (data === \"[DONE]\") {\n this.done = true;\n return;\n }\n\n try {\n yield JSON.parse(data) as ChatCompletionChunk;\n } catch {\n // skip malformed JSON\n }\n }\n }\n } finally {\n this.reader.releaseLock();\n }\n }\n\n abort(): void {\n this.done = true;\n this.controller.abort();\n }\n}\n","import type { Pendra } from \"../../client\";\nimport type {\n ChatCompletion,\n ChatCompletionChunk,\n ChatCompletionCreateParams,\n} from \"../../types/chat\";\nimport { Stream } from \"../../streaming\";\n\nexport class Completions {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n create(\n params: ChatCompletionCreateParams & { stream: true },\n ): Promise<Stream>;\n create(\n params: ChatCompletionCreateParams & { stream?: false },\n ): Promise<ChatCompletion>;\n create(\n params: ChatCompletionCreateParams,\n ): Promise<ChatCompletion | Stream>;\n async create(\n params: ChatCompletionCreateParams,\n ): Promise<ChatCompletion | Stream> {\n const body: Record<string, unknown> = {\n model: params.model,\n messages: params.messages,\n };\n\n if (params.stream != null) body.stream = params.stream;\n if (params.temperature != null) body.temperature = params.temperature;\n if (params.max_tokens != null) body.max_tokens = params.max_tokens;\n if (params.top_p != null) body.top_p = params.top_p;\n if (params.stop != null) body.stop = params.stop;\n\n if (params.stream) {\n const { response, controller } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body, stream: true },\n );\n return new Stream(response, controller);\n }\n\n const { response } = await this.client._fetch(\n \"/api/v1/chat/completions\",\n { method: \"POST\", body },\n );\n return (await response.json()) as ChatCompletion;\n }\n}\n","import type { Pendra } from \"../../client\";\nimport { Completions } from \"./completions\";\n\nexport class Chat {\n completions: Completions;\n\n constructor(client: Pendra) {\n this.completions = new Completions(client);\n }\n}\n","import type { Pendra } from \"../client\";\nimport type { Model } from \"../types/models\";\n\nexport class Models {\n private client: Pendra;\n\n constructor(client: Pendra) {\n this.client = client;\n }\n\n async list(): Promise<Model[]> {\n const { response } = await this.client._fetch(\"/api/v1/models\", {\n method: \"GET\",\n });\n const data = (await response.json()) as { data: Model[] };\n return data.data;\n }\n}\n","export class APIError extends Error {\n readonly status: number | undefined;\n\n constructor(message: string, status?: number) {\n super(message);\n this.name = \"APIError\";\n this.status = status;\n }\n}\n\nexport class APIConnectionError extends APIError {\n constructor(message = \"Failed to connect to the Pendra API\") {\n super(message);\n this.name = \"APIConnectionError\";\n }\n}\n\nexport class APIStatusError extends APIError {\n override readonly status: number;\n\n constructor(message: string, status: number) {\n super(message, status);\n this.name = \"APIStatusError\";\n this.status = status;\n }\n}\n\nexport class AuthenticationError extends APIStatusError {\n constructor(\n message = \"Invalid API key — check your PENDRA_API_KEY\",\n ) {\n super(message, 401);\n this.name = \"AuthenticationError\";\n }\n}\n\nexport class RateLimitError extends APIStatusError {\n constructor(message = \"Rate limit exceeded\") {\n super(message, 429);\n this.name = \"RateLimitError\";\n }\n}\n","import { Chat } from \"./resources/chat/index\";\nimport { Models } from \"./resources/models\";\nimport {\n APIConnectionError,\n APIStatusError,\n AuthenticationError,\n RateLimitError,\n} from \"./errors\";\n\nexport interface PendraOptions {\n apiKey?: string;\n baseURL?: string;\n timeout?: number;\n}\n\nexport class Pendra {\n readonly apiKey: string;\n readonly baseURL: string;\n readonly timeout: number;\n\n chat: Chat;\n models: Models;\n\n constructor(options: PendraOptions = {}) {\n const apiKey =\n options.apiKey ??\n (typeof process !== \"undefined\" ? process.env?.PENDRA_API_KEY : undefined);\n\n if (!apiKey) {\n throw new Error(\n \"API key is required — pass apiKey or set the PENDRA_API_KEY environment variable\",\n );\n }\n\n this.apiKey = apiKey;\n this.baseURL = (options.baseURL ?? \"https://api.pendra.ai\").replace(\n /\\/$/,\n \"\",\n );\n this.timeout = options.timeout ?? 120_000;\n\n this.chat = new Chat(this);\n this.models = new Models(this);\n }\n\n /** @internal */\n async _fetch(\n path: string,\n options: {\n method: string;\n body?: Record<string, unknown>;\n stream?: boolean;\n },\n ): Promise<{ response: Response; controller: AbortController }> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n\n let response: Response;\n try {\n response = await fetch(`${this.baseURL}${path}`, {\n method: options.method,\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timeoutId);\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw new APIConnectionError(\n `Request timed out after ${this.timeout}ms`,\n );\n }\n throw new APIConnectionError(\n err instanceof Error ? err.message : \"Failed to connect to the Pendra API\",\n );\n }\n\n if (!options.stream) {\n clearTimeout(timeoutId);\n }\n\n if (!response.ok) {\n clearTimeout(timeoutId);\n let message: string;\n try {\n const body = (await response.json()) as { detail?: string };\n message = body.detail ?? response.statusText;\n } catch {\n message = response.statusText;\n }\n\n if (response.status === 401) throw new AuthenticationError(message);\n if (response.status === 429) throw new RateLimitError(message);\n throw new APIStatusError(message, response.status);\n }\n\n return { response, controller };\n }\n}\n","export { Pendra } from \"./client\";\nexport type { PendraOptions } from \"./client\";\nexport { Stream } from \"./streaming\";\n\nexport type {\n ChatCompletion,\n ChatCompletionChunk,\n ChatCompletionMessage,\n ChatCompletionCreateParams,\n Choice,\n StreamChoice,\n ChoiceDelta,\n Usage,\n} from \"./types/chat\";\n\nexport type { Model } from \"./types/models\";\n\nexport {\n APIError,\n APIConnectionError,\n APIStatusError,\n AuthenticationError,\n RateLimitError,\n} from \"./errors\";\n\n// Default export for convenient usage:\n// import Pendra from 'pendra';\nimport { Pendra as _Pendra } from \"./client\";\nexport default _Pendra;\n"],"mappings":";AAEO,IAAM,SAAN,MAA2D;AAAA,EAOhE,YAAY,UAAoB,YAA6B;AAL7D,SAAQ,UAAU,IAAI,YAAY;AAClC,SAAQ,SAAS;AACjB,SAAQ,OAAO;AAIb,QAAI,CAAC,SAAS,MAAM;AAClB,YAAM,IAAI,MAAM,sDAAiD;AAAA,IACnE;AACA,SAA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5D,cAAM,IAAI;AAAA,UACR,2BAA2B,KAAK,OAAO;AAAA,QACzC;AAAA,MACF;AACA,YAAM,IAAI;AAAA,QACR,eAAe,QAAQ,IAAI,UAAU;AAAA,MACvC;AAAA,IACF;AAEA,QAAI,CAAC,QAAQ,QAAQ;AACnB,mBAAa,SAAS;AAAA,IACxB;AAEA,QAAI,CAAC,SAAS,IAAI;AAChB,mBAAa,SAAS;AACtB,UAAI;AACJ,UAAI;AACF,cAAM,OAAQ,MAAM,SAAS,KAAK;AAClC,kBAAU,KAAK,UAAU,SAAS;AAAA,MACpC,QAAQ;AACN,kBAAU,SAAS;AAAA,MACrB;AAEA,UAAI,SAAS,WAAW,IAAK,OAAM,IAAI,oBAAoB,OAAO;AAClE,UAAI,SAAS,WAAW,IAAK,OAAM,IAAI,eAAe,OAAO;AAC7D,YAAM,IAAI,eAAe,SAAS,SAAS,MAAM;AAAA,IACnD;AAEA,WAAO,EAAE,UAAU,WAAW;AAAA,EAChC;AACF;;;AC3EA,IAAO,gBAAQ;","names":["response"]}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "pendra",
3
+ "version": "0.1.0",
4
+ "description": "Official TypeScript SDK for the Pendra LLM inference API",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "require": {
15
+ "types": "./dist/index.d.cts",
16
+ "default": "./dist/index.cjs"
17
+ }
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsup",
25
+ "dev": "tsup --watch",
26
+ "test": "vitest run"
27
+ },
28
+ "keywords": [
29
+ "pendra",
30
+ "llm",
31
+ "inference",
32
+ "openai",
33
+ "ai",
34
+ "typescript"
35
+ ],
36
+ "author": "Pendra <hello@pendra.ai>",
37
+ "license": "Apache-2.0",
38
+ "engines": {
39
+ "node": ">=18.0.0"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^25.3.3",
43
+ "tsup": "^8.0.0",
44
+ "typescript": "^5.4.0",
45
+ "vitest": "^3.0.0"
46
+ }
47
+ }