Skip to content

Commit 0e22bd6

Browse files
committed
feat: Support streaming
1 parent adfc8b0 commit 0e22bd6

File tree

404 files changed

+2688
-503364
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

404 files changed

+2688
-503364
lines changed

dist/Client.d.ts

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
1-
import { APIClient, FinalRequestOptions, Headers } from "./Core.js";
2-
export declare class AI21 extends APIClient {
1+
import * as Core from "./Core";
2+
import { Chat } from "./resources/chat";
3+
export declare class AI21 extends Core.APIClient {
34
constructor(apiKey: string);
4-
protected authHeaders(opts: FinalRequestOptions): Headers;
5-
createChatCompletion(model: string, messages: Array<{
6-
role: string;
7-
content: string;
8-
}>): Promise<{
9-
completion: string;
10-
}>;
5+
protected authHeaders(opts: Core.FinalRequestOptions): Core.Headers;
6+
chat: Chat;
117
}

dist/Client.js

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,45 @@
1-
import { APIClient } from "./Core.js";
2-
export class AI21 extends APIClient {
1+
"use strict";
2+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3+
if (k2 === undefined) k2 = k;
4+
var desc = Object.getOwnPropertyDescriptor(m, k);
5+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6+
desc = { enumerable: true, get: function() { return m[k]; } };
7+
}
8+
Object.defineProperty(o, k2, desc);
9+
}) : (function(o, m, k, k2) {
10+
if (k2 === undefined) k2 = k;
11+
o[k2] = m[k];
12+
}));
13+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14+
Object.defineProperty(o, "default", { enumerable: true, value: v });
15+
}) : function(o, v) {
16+
o["default"] = v;
17+
});
18+
var __importStar = (this && this.__importStar) || function (mod) {
19+
if (mod && mod.__esModule) return mod;
20+
var result = {};
21+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22+
__setModuleDefault(result, mod);
23+
return result;
24+
};
25+
Object.defineProperty(exports, "__esModule", { value: true });
26+
exports.AI21 = void 0;
27+
const Core = __importStar(require("./Core"));
28+
const chat_1 = require("./resources/chat");
29+
class AI21 extends Core.APIClient {
330
constructor(apiKey) {
431
super({
532
baseURL: 'https://api.ai21.com/studio/v1',
633
timeout: 60000,
734
apiKey,
835
options: {}
936
});
37+
this.chat = new chat_1.Chat(this);
1038
}
11-
// Override auth headers to include API key
1239
authHeaders(opts) {
1340
return {
1441
'Authorization': `Bearer ${this.apiKey}`
1542
};
1643
}
17-
// Create a method for chat completions
18-
async createChatCompletion(model, messages) {
19-
return this.post('/chat/completions', {
20-
body: { model, messages }
21-
});
22-
}
2344
}
45+
exports.AI21 = AI21;

dist/Core.d.ts

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
1+
/// <reference types="node" />
12
import { BlobLike } from "formdata-node";
23
import { Readable } from "stream";
34
import { Response } from "node-fetch";
4-
export type Headers = Record<string, string | null | undefined>;
5-
type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
6-
type APIResponseProps = {
5+
export declare type Headers = Record<string, string | null | undefined>;
6+
declare type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
7+
declare type APIResponseProps = {
78
response: Response;
89
options: FinalRequestOptions;
910
controller: AbortController;
1011
};
11-
export type RequestOptions<Req = unknown | Record<string, unknown> | Readable | BlobLike | ArrayBufferView | ArrayBuffer> = {
12+
export declare type RequestOptions<Req = unknown | Record<string, unknown> | Readable | BlobLike | ArrayBufferView | ArrayBuffer> = {
1213
method?: HTTPMethod;
1314
path?: string;
1415
query?: Req | undefined;
@@ -18,12 +19,12 @@ export type RequestOptions<Req = unknown | Record<string, unknown> | Readable |
1819
stream?: boolean | undefined;
1920
timeout?: number;
2021
};
21-
export type FinalRequestOptions = RequestOptions & {
22+
export declare type FinalRequestOptions = RequestOptions & {
2223
method: HTTPMethod;
2324
path: string;
2425
};
25-
export declare const createResponseHeaders: (headers: Awaited<ReturnType<any>>["headers"]) => Record<string, string>;
26-
type ClientOptions = {
26+
export declare const createResponseHeaders: (headers: Awaited<ReturnType<any>>['headers']) => Record<string, string>;
27+
declare type ClientOptions = {
2728
apiKey?: string;
2829
organization?: string | null;
2930
project?: string | null;
@@ -34,8 +35,8 @@ type ClientOptions = {
3435
defaultHeaders?: Headers;
3536
dangerouslyAllowBrowser?: boolean;
3637
};
37-
type DefaultQuery = Record<string, unknown>;
38-
type PromiseOrValue<T> = T | Promise<T>;
38+
declare type DefaultQuery = Record<string, unknown>;
39+
declare type PromiseOrValue<T> = T | Promise<T>;
3940
export declare class APIPromise<T> extends Promise<T> {
4041
private responsePromise;
4142
private parseResponse;
@@ -70,11 +71,10 @@ export declare abstract class APIClient {
7071
apiKey: string;
7172
options: ClientOptions;
7273
});
73-
protected get<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
74-
protected post<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
75-
protected patch<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
76-
protected put<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
77-
protected delete<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
74+
get<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
75+
post<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
76+
put<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
77+
delete<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
7878
private getUserAgent;
7979
protected defaultHeaders(opts: FinalRequestOptions): Headers;
8080
protected authHeaders(opts: FinalRequestOptions): Headers;

dist/Core.js

Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,14 @@
1-
import { AI21Error } from "./errors.js";
2-
import { VERSION } from "./version.js";
3-
import fetch from 'node-fetch';
4-
export const createResponseHeaders = (headers) => {
1+
"use strict";
2+
var __importDefault = (this && this.__importDefault) || function (mod) {
3+
return (mod && mod.__esModule) ? mod : { "default": mod };
4+
};
5+
Object.defineProperty(exports, "__esModule", { value: true });
6+
exports.readEnv = exports.APIClient = exports.APIPromise = exports.createResponseHeaders = void 0;
7+
const errors_js_1 = require("./errors.js");
8+
const version_js_1 = require("./version.js");
9+
const node_fetch_1 = __importDefault(require("node-fetch"));
10+
const Streaming_1 = require("./Streaming");
11+
const createResponseHeaders = (headers) => {
512
return new Proxy(Object.fromEntries(
613
// @ts-ignore
714
headers.entries()), {
@@ -11,23 +18,30 @@ export const createResponseHeaders = (headers) => {
1118
},
1219
});
1320
};
21+
exports.createResponseHeaders = createResponseHeaders;
1422
const validatePositiveInteger = (name, n) => {
1523
if (typeof n !== 'number' || !Number.isInteger(n)) {
16-
throw new AI21Error(`${name} must be an integer`);
24+
throw new errors_js_1.AI21Error(`${name} must be an integer`);
1725
}
1826
if (n < 0) {
19-
throw new AI21Error(`${name} must be a positive integer`);
27+
throw new errors_js_1.AI21Error(`${name} must be a positive integer`);
2028
}
2129
return n;
2230
};
23-
async function defaultParseResponse({ response }) {
31+
async function defaultParseResponse({ response, options }) {
32+
if (options.stream) {
33+
if (!response.body) {
34+
throw new errors_js_1.AI21Error('Response body is null');
35+
}
36+
return new Streaming_1.Stream(response);
37+
}
2438
const contentType = response.headers.get('content-type');
2539
if (contentType?.includes('application/json')) {
2640
return response.json();
2741
}
2842
return response.text();
2943
}
30-
export class APIPromise extends Promise {
44+
class APIPromise extends Promise {
3145
constructor(responsePromise, parseResponse = defaultParseResponse) {
3246
super((resolve) => resolve(null));
3347
this.responsePromise = responsePromise;
@@ -59,7 +73,8 @@ export class APIPromise extends Promise {
5973
return this.parse().finally(onfinally);
6074
}
6175
}
62-
export class APIClient {
76+
exports.APIPromise = APIPromise;
77+
class APIClient {
6378
constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes
6479
// fetch: overridenFetch,
6580
apiKey, options, }) {
@@ -75,17 +90,14 @@ export class APIClient {
7590
post(path, opts) {
7691
return this.makeRequest('post', path, opts);
7792
}
78-
patch(path, opts) {
79-
return this.makeRequest('patch', path, opts);
80-
}
8193
put(path, opts) {
8294
return this.makeRequest('put', path, opts);
8395
}
8496
delete(path, opts) {
8597
return this.makeRequest('delete', path, opts);
8698
}
8799
getUserAgent() {
88-
return `${this.constructor.name}/JS ${VERSION}`;
100+
return `${this.constructor.name}/JS ${version_js_1.VERSION}`;
89101
}
90102
defaultHeaders(opts) {
91103
return {
@@ -126,26 +138,28 @@ export class APIClient {
126138
...this.defaultHeaders(options),
127139
...options.headers,
128140
};
129-
const response = await fetch(url, {
141+
const response = await (0, node_fetch_1.default)(url, {
130142
method: options.method,
131143
headers: headers,
132-
signal: controller.signal, // Type cast to avoid AbortSignal compatibility issue
144+
signal: controller.signal,
133145
body: options.body ? JSON.stringify(options.body) : undefined
134146
});
135147
if (!response.ok) {
136-
throw new AI21Error(`Request failed with status ${response.status}`);
148+
throw new errors_js_1.AI21Error(`Request failed with status ${response.status}`);
137149
}
138150
return { response, options, controller };
139151
}
140152
static isRunningInBrowser() {
141153
return (typeof window !== 'undefined' &&
142154
typeof window.document !== 'undefined' &&
143-
typeof fetch === 'function');
155+
typeof node_fetch_1.default === 'function');
144156
}
145157
}
146-
export const readEnv = (env) => {
158+
exports.APIClient = APIClient;
159+
const readEnv = (env) => {
147160
if (typeof process !== 'undefined' && process.env) {
148161
return process.env[env]?.trim() ?? undefined;
149162
}
150163
return undefined;
151164
};
165+
exports.readEnv = readEnv;

dist/errors.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,6 @@
1-
export class AI21Error extends Error {
1+
"use strict";
2+
Object.defineProperty(exports, "__esModule", { value: true });
3+
exports.AI21Error = void 0;
4+
class AI21Error extends Error {
25
}
6+
exports.AI21Error = AI21Error;

dist/index.d.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
export { AI21 } from './Client.js';
1+
export { AI21 } from './Client';
2+
export { RequestOptions } from './Core';

dist/index.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,5 @@
1-
export { AI21 } from './Client.js';
1+
"use strict";
2+
Object.defineProperty(exports, "__esModule", { value: true });
3+
exports.AI21 = void 0;
4+
var Client_1 = require("./Client");
5+
Object.defineProperty(exports, "AI21", { enumerable: true, get: function () { return Client_1.AI21; } });

dist/version.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,4 @@
1-
export const VERSION = '0.0.1';
1+
"use strict";
2+
Object.defineProperty(exports, "__esModule", { value: true });
3+
exports.VERSION = void 0;
4+
exports.VERSION = '0.0.1';

node_modules/.bin/tsc

Lines changed: 0 additions & 1 deletion
This file was deleted.

node_modules/.bin/tsserver

Lines changed: 0 additions & 1 deletion
This file was deleted.

0 commit comments

Comments
 (0)