Skip to content

Commit adfc8b0

Browse files
committed
feat: Initial Project files
1 parent 5f0a280 commit adfc8b0

File tree

939 files changed

+1020666
-0
lines changed

Some content is hidden

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

939 files changed

+1020666
-0
lines changed

dist/Client.d.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { APIClient, FinalRequestOptions, Headers } from "./Core.js";
2+
export declare class AI21 extends APIClient {
3+
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+
}>;
11+
}

dist/Client.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { APIClient } from "./Core.js";
2+
export class AI21 extends APIClient {
3+
constructor(apiKey) {
4+
super({
5+
baseURL: 'https://api.ai21.com/studio/v1',
6+
timeout: 60000,
7+
apiKey,
8+
options: {}
9+
});
10+
}
11+
// Override auth headers to include API key
12+
authHeaders(opts) {
13+
return {
14+
'Authorization': `Bearer ${this.apiKey}`
15+
};
16+
}
17+
// Create a method for chat completions
18+
async createChatCompletion(model, messages) {
19+
return this.post('/chat/completions', {
20+
body: { model, messages }
21+
});
22+
}
23+
}

dist/Core.d.ts

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { BlobLike } from "formdata-node";
2+
import { Readable } from "stream";
3+
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 = {
7+
response: Response;
8+
options: FinalRequestOptions;
9+
controller: AbortController;
10+
};
11+
export type RequestOptions<Req = unknown | Record<string, unknown> | Readable | BlobLike | ArrayBufferView | ArrayBuffer> = {
12+
method?: HTTPMethod;
13+
path?: string;
14+
query?: Req | undefined;
15+
body?: Req | null | undefined;
16+
headers?: Headers | undefined;
17+
maxRetries?: number;
18+
stream?: boolean | undefined;
19+
timeout?: number;
20+
};
21+
export type FinalRequestOptions = RequestOptions & {
22+
method: HTTPMethod;
23+
path: string;
24+
};
25+
export declare const createResponseHeaders: (headers: Awaited<ReturnType<any>>["headers"]) => Record<string, string>;
26+
type ClientOptions = {
27+
apiKey?: string;
28+
organization?: string | null;
29+
project?: string | null;
30+
baseURL?: string;
31+
maxRetries?: number;
32+
timeout?: number;
33+
defaultQuery?: DefaultQuery;
34+
defaultHeaders?: Headers;
35+
dangerouslyAllowBrowser?: boolean;
36+
};
37+
type DefaultQuery = Record<string, unknown>;
38+
type PromiseOrValue<T> = T | Promise<T>;
39+
export declare class APIPromise<T> extends Promise<T> {
40+
private responsePromise;
41+
private parseResponse;
42+
constructor(responsePromise: Promise<APIResponseProps>, parseResponse?: (props: APIResponseProps) => Promise<T>);
43+
/**
44+
* Gets the raw Response instance
45+
*/
46+
asResponse(): Promise<Response>;
47+
/**
48+
* Gets both the parsed response data and the raw Response instance
49+
*/
50+
withResponse(): Promise<{
51+
data: T;
52+
response: Response;
53+
}>;
54+
private parse;
55+
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
56+
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null): Promise<T | TResult>;
57+
finally(onfinally?: (() => void) | null): Promise<T>;
58+
}
59+
export declare abstract class APIClient {
60+
protected options: ClientOptions;
61+
protected apiKey: string;
62+
protected baseURL: string;
63+
protected maxRetries: number;
64+
protected timeout: number;
65+
constructor({ baseURL, maxRetries, timeout, // 10 minutes
66+
apiKey, options, }: {
67+
baseURL: string;
68+
maxRetries?: number | undefined;
69+
timeout: number | undefined;
70+
apiKey: string;
71+
options: ClientOptions;
72+
});
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>;
78+
private getUserAgent;
79+
protected defaultHeaders(opts: FinalRequestOptions): Headers;
80+
protected authHeaders(opts: FinalRequestOptions): Headers;
81+
protected defaultQuery(): DefaultQuery | undefined;
82+
protected stringifyQuery(query: Record<string, unknown>): string;
83+
private makeRequest;
84+
private performRequest;
85+
protected static isRunningInBrowser(): boolean;
86+
}
87+
export declare const readEnv: (env: string) => string | undefined;
88+
export {};

dist/Core.js

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
import { AI21Error } from "./errors.js";
2+
import { VERSION } from "./version.js";
3+
import fetch from 'node-fetch';
4+
export const createResponseHeaders = (headers) => {
5+
return new Proxy(Object.fromEntries(
6+
// @ts-ignore
7+
headers.entries()), {
8+
get(target, name) {
9+
const key = name.toString();
10+
return target[key.toLowerCase()] || target[key];
11+
},
12+
});
13+
};
14+
const validatePositiveInteger = (name, n) => {
15+
if (typeof n !== 'number' || !Number.isInteger(n)) {
16+
throw new AI21Error(`${name} must be an integer`);
17+
}
18+
if (n < 0) {
19+
throw new AI21Error(`${name} must be a positive integer`);
20+
}
21+
return n;
22+
};
23+
async function defaultParseResponse({ response }) {
24+
const contentType = response.headers.get('content-type');
25+
if (contentType?.includes('application/json')) {
26+
return response.json();
27+
}
28+
return response.text();
29+
}
30+
export class APIPromise extends Promise {
31+
constructor(responsePromise, parseResponse = defaultParseResponse) {
32+
super((resolve) => resolve(null));
33+
this.responsePromise = responsePromise;
34+
this.parseResponse = parseResponse;
35+
}
36+
/**
37+
* Gets the raw Response instance
38+
*/
39+
asResponse() {
40+
return this.responsePromise.then((p) => p.response);
41+
}
42+
/**
43+
* Gets both the parsed response data and the raw Response instance
44+
*/
45+
async withResponse() {
46+
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
47+
return { data, response };
48+
}
49+
parse() {
50+
return this.responsePromise.then(this.parseResponse);
51+
}
52+
then(onfulfilled, onrejected) {
53+
return this.parse().then(onfulfilled, onrejected);
54+
}
55+
catch(onrejected) {
56+
return this.parse().catch(onrejected);
57+
}
58+
finally(onfinally) {
59+
return this.parse().finally(onfinally);
60+
}
61+
}
62+
export class APIClient {
63+
constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes
64+
// fetch: overridenFetch,
65+
apiKey, options, }) {
66+
this.baseURL = baseURL;
67+
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
68+
this.timeout = validatePositiveInteger('timeout', timeout);
69+
this.apiKey = apiKey;
70+
this.options = options;
71+
}
72+
get(path, opts) {
73+
return this.makeRequest('get', path, opts);
74+
}
75+
post(path, opts) {
76+
return this.makeRequest('post', path, opts);
77+
}
78+
patch(path, opts) {
79+
return this.makeRequest('patch', path, opts);
80+
}
81+
put(path, opts) {
82+
return this.makeRequest('put', path, opts);
83+
}
84+
delete(path, opts) {
85+
return this.makeRequest('delete', path, opts);
86+
}
87+
getUserAgent() {
88+
return `${this.constructor.name}/JS ${VERSION}`;
89+
}
90+
defaultHeaders(opts) {
91+
return {
92+
Accept: 'application/json',
93+
'Content-Type': 'application/json',
94+
'User-Agent': this.getUserAgent(),
95+
// ...getPlatformHeaders(),
96+
...this.authHeaders(opts),
97+
};
98+
}
99+
authHeaders(opts) {
100+
return {};
101+
}
102+
defaultQuery() {
103+
return this.options.defaultQuery;
104+
}
105+
stringifyQuery(query) {
106+
const params = new URLSearchParams();
107+
for (const [key, value] of Object.entries(query)) {
108+
if (value !== undefined && value !== null) {
109+
params.append(key, String(value));
110+
}
111+
}
112+
return params.toString();
113+
}
114+
makeRequest(method, path, opts) {
115+
const options = {
116+
method,
117+
path,
118+
...opts
119+
};
120+
return new APIPromise(this.performRequest(options));
121+
}
122+
async performRequest(options) {
123+
const controller = new AbortController();
124+
const url = `${this.baseURL}${options.path}`;
125+
const headers = {
126+
...this.defaultHeaders(options),
127+
...options.headers,
128+
};
129+
const response = await fetch(url, {
130+
method: options.method,
131+
headers: headers,
132+
signal: controller.signal, // Type cast to avoid AbortSignal compatibility issue
133+
body: options.body ? JSON.stringify(options.body) : undefined
134+
});
135+
if (!response.ok) {
136+
throw new AI21Error(`Request failed with status ${response.status}`);
137+
}
138+
return { response, options, controller };
139+
}
140+
static isRunningInBrowser() {
141+
return (typeof window !== 'undefined' &&
142+
typeof window.document !== 'undefined' &&
143+
typeof fetch === 'function');
144+
}
145+
}
146+
export const readEnv = (env) => {
147+
if (typeof process !== 'undefined' && process.env) {
148+
return process.env[env]?.trim() ?? undefined;
149+
}
150+
return undefined;
151+
};

dist/errors.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export declare class AI21Error extends Error {
2+
}

dist/errors.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export class AI21Error extends Error {
2+
}

dist/index.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { AI21 } from './Client.js';

dist/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { AI21 } from './Client.js';

dist/version.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export declare const VERSION = "0.0.1";

dist/version.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const VERSION = '0.0.1';

0 commit comments

Comments
 (0)