@layer_ai/sdk 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +166 -0
- package/dist/client.d.ts +74 -0
- package/dist/client.js +108 -0
- package/dist/errors.d.ts +98 -0
- package/dist/errors.js +109 -0
- package/dist/generated/types.d.ts +1443 -0
- package/dist/generated/types.js +7 -0
- package/dist/http.d.ts +76 -0
- package/dist/http.js +193 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +29 -0
- package/dist/pagination.d.ts +28 -0
- package/dist/pagination.js +21 -0
- package/dist/resources/base-models.d.ts +47 -0
- package/dist/resources/base-models.js +59 -0
- package/dist/resources/files.d.ts +54 -0
- package/dist/resources/files.js +94 -0
- package/dist/resources/inferences.d.ts +70 -0
- package/dist/resources/inferences.js +126 -0
- package/dist/resources/projects.d.ts +42 -0
- package/dist/resources/projects.js +66 -0
- package/dist/resources/reference-sets.d.ts +30 -0
- package/dist/resources/reference-sets.js +40 -0
- package/dist/resources/scores.d.ts +24 -0
- package/dist/resources/scores.js +31 -0
- package/dist/resources/training-runs.d.ts +50 -0
- package/dist/resources/training-runs.js +93 -0
- package/dist/resources/workflows.d.ts +37 -0
- package/dist/resources/workflows.js +38 -0
- package/dist/resources/workspaces.d.ts +23 -0
- package/dist/resources/workspaces.js +35 -0
- package/dist/types.d.ts +61 -0
- package/dist/types.js +9 -0
- package/dist/version.d.ts +11 -0
- package/dist/version.js +1 -0
- package/package.json +50 -0
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The transport every resource method goes through.
|
|
3
|
+
*
|
|
4
|
+
* Four jobs beyond sending requests: it puts a bearer token on each call, turns the API's
|
|
5
|
+
* RFC 9457 problem responses into typed errors, retries what the server said was worth
|
|
6
|
+
* retrying, and surfaces deprecation notices so a caller hears about a sunset before it
|
|
7
|
+
* bites.
|
|
8
|
+
*
|
|
9
|
+
* Every unsafe request carries an `Idempotency-Key`, minted here when the caller supplies
|
|
10
|
+
* none. That is what makes a retry safe: a generation that was accepted but whose response
|
|
11
|
+
* was lost is replayed rather than run — and paid for — a second time.
|
|
12
|
+
*/
|
|
13
|
+
/** The subset of `fetch` the SDK uses, so a caller can pass their own. */
|
|
14
|
+
export type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
|
|
15
|
+
/** A bearer token, or a function returning one — sync or async — so it can be refreshed. */
|
|
16
|
+
export type TokenSource = string | (() => string | Promise<string>);
|
|
17
|
+
export interface RetryPolicy {
|
|
18
|
+
/** How many times a failed request is re-sent. 0 disables retrying. */
|
|
19
|
+
maxRetries: number;
|
|
20
|
+
/** Delay before the first retry, in milliseconds. Doubles each attempt. */
|
|
21
|
+
initialDelayMs: number;
|
|
22
|
+
/** Ceiling on a single backoff delay, in milliseconds. */
|
|
23
|
+
maxDelayMs: number;
|
|
24
|
+
}
|
|
25
|
+
export declare const DEFAULT_RETRY_POLICY: RetryPolicy;
|
|
26
|
+
export interface HttpClientOptions {
|
|
27
|
+
baseUrl: string;
|
|
28
|
+
token: TokenSource;
|
|
29
|
+
userAgent: string;
|
|
30
|
+
timeoutMs: number;
|
|
31
|
+
retry: RetryPolicy;
|
|
32
|
+
fetch: FetchLike;
|
|
33
|
+
onDeprecation?: (notice: DeprecationNotice) => void;
|
|
34
|
+
/** Injected in tests so backoff does not spend real seconds. */
|
|
35
|
+
sleep?: (ms: number) => Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
/** What the server said about an endpoint it intends to withdraw. */
|
|
38
|
+
export interface DeprecationNotice {
|
|
39
|
+
/** The path that carried the notice. */
|
|
40
|
+
path: string;
|
|
41
|
+
/** Value of the `Deprecation` header. */
|
|
42
|
+
deprecation: string;
|
|
43
|
+
/** Value of the `Sunset` header — the earliest date it may stop working. */
|
|
44
|
+
sunset: string | null;
|
|
45
|
+
}
|
|
46
|
+
export interface RequestOptions {
|
|
47
|
+
query?: Record<string, string | number | boolean | undefined | null>;
|
|
48
|
+
body?: unknown;
|
|
49
|
+
/** Replay key for an unsafe request. One is minted when this is omitted. */
|
|
50
|
+
idempotencyKey?: string;
|
|
51
|
+
signal?: AbortSignal;
|
|
52
|
+
}
|
|
53
|
+
export declare class HttpClient {
|
|
54
|
+
private readonly options;
|
|
55
|
+
private readonly sleep;
|
|
56
|
+
/** Paths already reported, so one deprecated endpoint is announced once per client. */
|
|
57
|
+
private readonly announced;
|
|
58
|
+
constructor(options: HttpClientOptions);
|
|
59
|
+
request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
|
|
60
|
+
get<T>(path: string, options?: RequestOptions): Promise<T>;
|
|
61
|
+
post<T>(path: string, options?: RequestOptions): Promise<T>;
|
|
62
|
+
patch<T>(path: string, options?: RequestOptions): Promise<T>;
|
|
63
|
+
delete<T>(path: string, options?: RequestOptions): Promise<T>;
|
|
64
|
+
/**
|
|
65
|
+
* One attempt. Returns null when the failure is worth another attempt, so the caller's
|
|
66
|
+
* loop retries; throws when it is not.
|
|
67
|
+
*/
|
|
68
|
+
private send;
|
|
69
|
+
private url;
|
|
70
|
+
private headers;
|
|
71
|
+
private decode;
|
|
72
|
+
private errorFrom;
|
|
73
|
+
/** The server's own `Retry-After` wins; otherwise exponential backoff with full jitter. */
|
|
74
|
+
private backoff;
|
|
75
|
+
private reportDeprecation;
|
|
76
|
+
}
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The transport every resource method goes through.
|
|
3
|
+
*
|
|
4
|
+
* Four jobs beyond sending requests: it puts a bearer token on each call, turns the API's
|
|
5
|
+
* RFC 9457 problem responses into typed errors, retries what the server said was worth
|
|
6
|
+
* retrying, and surfaces deprecation notices so a caller hears about a sunset before it
|
|
7
|
+
* bites.
|
|
8
|
+
*
|
|
9
|
+
* Every unsafe request carries an `Idempotency-Key`, minted here when the caller supplies
|
|
10
|
+
* none. That is what makes a retry safe: a generation that was accepted but whose response
|
|
11
|
+
* was lost is replayed rather than run — and paid for — a second time.
|
|
12
|
+
*/
|
|
13
|
+
import { LayerApiError, LayerConnectionError, LayerTimeoutError, } from "./errors.js";
|
|
14
|
+
export const DEFAULT_RETRY_POLICY = {
|
|
15
|
+
maxRetries: 3,
|
|
16
|
+
initialDelayMs: 500,
|
|
17
|
+
maxDelayMs: 8_000,
|
|
18
|
+
};
|
|
19
|
+
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
|
|
20
|
+
/** Statuses worth sending again: the server is asking, or it is momentarily broken. */
|
|
21
|
+
const RETRIABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
|
|
22
|
+
/**
|
|
23
|
+
* A 409 is a conflict, which is normally the caller's to resolve — except when it says an
|
|
24
|
+
* earlier request under the same idempotency key is still running, which is exactly the
|
|
25
|
+
* case a retry is for.
|
|
26
|
+
*/
|
|
27
|
+
const isRetriable = (status, code) => RETRIABLE_STATUSES.has(status) || (status === 409 && code === "IDEMPOTENT_REQUEST_IN_PROGRESS");
|
|
28
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
29
|
+
const parseNumber = (value) => {
|
|
30
|
+
if (value === null)
|
|
31
|
+
return null;
|
|
32
|
+
const parsed = Number(value);
|
|
33
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
34
|
+
};
|
|
35
|
+
const readRateLimit = (headers) => {
|
|
36
|
+
const limit = parseNumber(headers.get("ratelimit-limit"));
|
|
37
|
+
const remaining = parseNumber(headers.get("ratelimit-remaining"));
|
|
38
|
+
const resetSeconds = parseNumber(headers.get("ratelimit-reset"));
|
|
39
|
+
if (limit === null && remaining === null && resetSeconds === null)
|
|
40
|
+
return null;
|
|
41
|
+
return { limit, remaining, resetSeconds };
|
|
42
|
+
};
|
|
43
|
+
export class HttpClient {
|
|
44
|
+
options;
|
|
45
|
+
sleep;
|
|
46
|
+
/** Paths already reported, so one deprecated endpoint is announced once per client. */
|
|
47
|
+
announced = new Set();
|
|
48
|
+
constructor(options) {
|
|
49
|
+
this.options = options;
|
|
50
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
51
|
+
}
|
|
52
|
+
async request(method, path, options = {}) {
|
|
53
|
+
const url = this.url(path, options.query);
|
|
54
|
+
const headers = await this.headers(method, options.idempotencyKey);
|
|
55
|
+
const init = { method, headers };
|
|
56
|
+
if (options.body !== undefined) {
|
|
57
|
+
init.body = JSON.stringify(options.body);
|
|
58
|
+
}
|
|
59
|
+
const { maxRetries } = this.options.retry;
|
|
60
|
+
for (let attempt = 0;; attempt += 1) {
|
|
61
|
+
const response = await this.send(url, init, path, method, options.signal, attempt, maxRetries);
|
|
62
|
+
if (response === null)
|
|
63
|
+
continue;
|
|
64
|
+
this.reportDeprecation(path, response.headers);
|
|
65
|
+
if (response.ok)
|
|
66
|
+
return (await this.decode(response, method, path));
|
|
67
|
+
const error = await this.errorFrom(response, method, path);
|
|
68
|
+
if (attempt < maxRetries && isRetriable(response.status, error.code)) {
|
|
69
|
+
await this.sleep(this.backoff(attempt, error.retryAfterSeconds));
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
get(path, options) {
|
|
76
|
+
return this.request("GET", path, options);
|
|
77
|
+
}
|
|
78
|
+
post(path, options) {
|
|
79
|
+
return this.request("POST", path, options);
|
|
80
|
+
}
|
|
81
|
+
patch(path, options) {
|
|
82
|
+
return this.request("PATCH", path, options);
|
|
83
|
+
}
|
|
84
|
+
delete(path, options) {
|
|
85
|
+
return this.request("DELETE", path, options);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* One attempt. Returns null when the failure is worth another attempt, so the caller's
|
|
89
|
+
* loop retries; throws when it is not.
|
|
90
|
+
*/
|
|
91
|
+
async send(url, init, path, method, signal, attempt, maxRetries) {
|
|
92
|
+
const timeout = AbortSignal.timeout(this.options.timeoutMs);
|
|
93
|
+
const abort = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
94
|
+
try {
|
|
95
|
+
return await this.options.fetch(url, { ...init, signal: abort });
|
|
96
|
+
}
|
|
97
|
+
catch (cause) {
|
|
98
|
+
if (signal?.aborted)
|
|
99
|
+
throw cause;
|
|
100
|
+
if (attempt < maxRetries) {
|
|
101
|
+
await this.sleep(this.backoff(attempt, null));
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
if (timeout.aborted) {
|
|
105
|
+
throw new LayerTimeoutError(`${method} ${path} did not answer within ${this.options.timeoutMs}ms.`, { cause });
|
|
106
|
+
}
|
|
107
|
+
throw new LayerConnectionError(`Could not reach ${this.options.baseUrl}${path}.`, { cause });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
url(path, query) {
|
|
111
|
+
const url = new URL(`${this.options.baseUrl}${path}`);
|
|
112
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
113
|
+
if (value === undefined || value === null)
|
|
114
|
+
continue;
|
|
115
|
+
url.searchParams.set(key, String(value));
|
|
116
|
+
}
|
|
117
|
+
return url.toString();
|
|
118
|
+
}
|
|
119
|
+
async headers(method, idempotencyKey) {
|
|
120
|
+
const { token, userAgent } = this.options;
|
|
121
|
+
const resolved = typeof token === "function" ? await token() : token;
|
|
122
|
+
const headers = new Headers({
|
|
123
|
+
accept: "application/json",
|
|
124
|
+
"content-type": "application/json",
|
|
125
|
+
"user-agent": userAgent,
|
|
126
|
+
authorization: `Bearer ${resolved}`,
|
|
127
|
+
});
|
|
128
|
+
if (!SAFE_METHODS.has(method)) {
|
|
129
|
+
headers.set("idempotency-key", idempotencyKey ?? crypto.randomUUID());
|
|
130
|
+
}
|
|
131
|
+
return headers;
|
|
132
|
+
}
|
|
133
|
+
async decode(response, method, path) {
|
|
134
|
+
if (response.status === 204)
|
|
135
|
+
return undefined;
|
|
136
|
+
const text = await response.text();
|
|
137
|
+
if (text === "")
|
|
138
|
+
return undefined;
|
|
139
|
+
try {
|
|
140
|
+
return JSON.parse(text);
|
|
141
|
+
}
|
|
142
|
+
catch (cause) {
|
|
143
|
+
// Everything out of here is a LayerError, so a proxy answering 200 with HTML must
|
|
144
|
+
// not surface as a JSON syntax error from somewhere inside the SDK.
|
|
145
|
+
throw new LayerConnectionError(`${method} ${path} returned a response that is not JSON. ` +
|
|
146
|
+
"This usually means something other than the Layer API answered the request.", { cause });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async errorFrom(response, method, path) {
|
|
150
|
+
let problem = {};
|
|
151
|
+
try {
|
|
152
|
+
const parsed = JSON.parse(await response.text());
|
|
153
|
+
if (parsed !== null && typeof parsed === "object")
|
|
154
|
+
problem = parsed;
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
// A body that is not a problem document leaves the fields null below.
|
|
158
|
+
}
|
|
159
|
+
const asString = (key) => typeof problem[key] === "string" ? problem[key] : null;
|
|
160
|
+
const type = asString("type");
|
|
161
|
+
const title = asString("title");
|
|
162
|
+
const detail = asString("detail");
|
|
163
|
+
// `type` is a URI whose last segment is the machine-readable code.
|
|
164
|
+
const code = type ? (type.split("/").pop() ?? "UNKNOWN") : "UNKNOWN";
|
|
165
|
+
return new LayerApiError({
|
|
166
|
+
message: detail ?? title ?? `${response.status} from ${method} ${path}`,
|
|
167
|
+
status: response.status,
|
|
168
|
+
code,
|
|
169
|
+
type,
|
|
170
|
+
title,
|
|
171
|
+
detail,
|
|
172
|
+
retryAfterSeconds: parseNumber(response.headers.get("retry-after")),
|
|
173
|
+
rateLimit: readRateLimit(response.headers),
|
|
174
|
+
method,
|
|
175
|
+
path,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
/** The server's own `Retry-After` wins; otherwise exponential backoff with full jitter. */
|
|
179
|
+
backoff(attempt, retryAfterSeconds) {
|
|
180
|
+
if (retryAfterSeconds !== null && retryAfterSeconds >= 0)
|
|
181
|
+
return retryAfterSeconds * 1000;
|
|
182
|
+
const { initialDelayMs, maxDelayMs } = this.options.retry;
|
|
183
|
+
const ceiling = Math.min(maxDelayMs, initialDelayMs * 2 ** attempt);
|
|
184
|
+
return Math.random() * ceiling;
|
|
185
|
+
}
|
|
186
|
+
reportDeprecation(path, headers) {
|
|
187
|
+
const deprecation = headers.get("deprecation");
|
|
188
|
+
if (!deprecation || !this.options.onDeprecation || this.announced.has(path))
|
|
189
|
+
return;
|
|
190
|
+
this.announced.add(path);
|
|
191
|
+
this.options.onDeprecation({ path, deprecation, sunset: headers.get("sunset") });
|
|
192
|
+
}
|
|
193
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Layer SDK — AI asset generation for game studios, from JavaScript and TypeScript.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { Layer } from "@layer_ai/sdk";
|
|
6
|
+
*
|
|
7
|
+
* const layer = new Layer({ apiKey: process.env.LAYER_API_KEY });
|
|
8
|
+
* const run = await layer.inferences.generate({ prompt: "a crystal sword icon" });
|
|
9
|
+
* console.log(run.outputs?.[0]?.url);
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* Reference: https://www.layer.ai/docs
|
|
13
|
+
*/
|
|
14
|
+
export { DEFAULT_BASE_URL, Layer, type LayerOptions } from "./client.js";
|
|
15
|
+
export { VERSION } from "./version.js";
|
|
16
|
+
export { ERROR_CODES, LayerApiError, LayerBudgetExceededError, LayerConnectionError, LayerError, LayerRunFailedError, LayerTimeoutError, type ErrorCode, type KnownErrorCode, type RateLimitState, } from "./errors.js";
|
|
17
|
+
export { DEFAULT_RETRY_POLICY, HttpClient, type DeprecationNotice, type FetchLike, type RequestOptions, type RetryPolicy, type TokenSource, } from "./http.js";
|
|
18
|
+
export { walkPages, type ListOptions, type Page } from "./pagination.js";
|
|
19
|
+
export { BaseModels, type BaseModelListOptions } from "./resources/base-models.js";
|
|
20
|
+
export { Files, type UploadOptions, type UploadableContent } from "./resources/files.js";
|
|
21
|
+
export { Inferences, type GenerateOptions, type RunOptions, type WaitOptions, } from "./resources/inferences.js";
|
|
22
|
+
export { Projects, type ProjectListOptions } from "./resources/projects.js";
|
|
23
|
+
export { ReferenceSets, type ReferenceSetListOptions } from "./resources/reference-sets.js";
|
|
24
|
+
export { Scores } from "./resources/scores.js";
|
|
25
|
+
export { TrainingRuns, type TrainingRunListOptions, type TrainingWaitOptions, } from "./resources/training-runs.js";
|
|
26
|
+
export { Workflows, type WorkflowRunRequest } from "./resources/workflows.js";
|
|
27
|
+
export { Workspaces } from "./resources/workspaces.js";
|
|
28
|
+
export * from "./types.js";
|
|
29
|
+
export * from "./generated/types.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Layer SDK — AI asset generation for game studios, from JavaScript and TypeScript.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { Layer } from "@layer_ai/sdk";
|
|
6
|
+
*
|
|
7
|
+
* const layer = new Layer({ apiKey: process.env.LAYER_API_KEY });
|
|
8
|
+
* const run = await layer.inferences.generate({ prompt: "a crystal sword icon" });
|
|
9
|
+
* console.log(run.outputs?.[0]?.url);
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* Reference: https://www.layer.ai/docs
|
|
13
|
+
*/
|
|
14
|
+
export { DEFAULT_BASE_URL, Layer } from "./client.js";
|
|
15
|
+
export { VERSION } from "./version.js";
|
|
16
|
+
export { ERROR_CODES, LayerApiError, LayerBudgetExceededError, LayerConnectionError, LayerError, LayerRunFailedError, LayerTimeoutError, } from "./errors.js";
|
|
17
|
+
export { DEFAULT_RETRY_POLICY, HttpClient, } from "./http.js";
|
|
18
|
+
export { walkPages } from "./pagination.js";
|
|
19
|
+
export { BaseModels } from "./resources/base-models.js";
|
|
20
|
+
export { Files } from "./resources/files.js";
|
|
21
|
+
export { Inferences, } from "./resources/inferences.js";
|
|
22
|
+
export { Projects } from "./resources/projects.js";
|
|
23
|
+
export { ReferenceSets } from "./resources/reference-sets.js";
|
|
24
|
+
export { Scores } from "./resources/scores.js";
|
|
25
|
+
export { TrainingRuns, } from "./resources/training-runs.js";
|
|
26
|
+
export { Workflows } from "./resources/workflows.js";
|
|
27
|
+
export { Workspaces } from "./resources/workspaces.js";
|
|
28
|
+
export * from "./types.js";
|
|
29
|
+
export * from "./generated/types.js";
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor pagination, in the two shapes a caller wants.
|
|
3
|
+
*
|
|
4
|
+
* `list` returns one page — the envelope the API sent, cursor included — for a caller
|
|
5
|
+
* driving their own paging. `listAll` walks every page and yields items, which is what
|
|
6
|
+
* most code wants and what it would otherwise write by hand each time.
|
|
7
|
+
*/
|
|
8
|
+
import type { PaginationOutput } from "./generated/types.js";
|
|
9
|
+
/** One page of a list endpoint. */
|
|
10
|
+
export interface Page<T> {
|
|
11
|
+
items: T[];
|
|
12
|
+
pagination: PaginationOutput;
|
|
13
|
+
}
|
|
14
|
+
/** Query options every list endpoint accepts. */
|
|
15
|
+
export interface ListOptions {
|
|
16
|
+
/** Page size, 1-100. The API defaults to 20. */
|
|
17
|
+
limit?: number;
|
|
18
|
+
/** Cursor from a previous response. Opaque — do not parse or construct one. */
|
|
19
|
+
cursor?: string;
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Walk every page of a list endpoint, yielding items.
|
|
24
|
+
*
|
|
25
|
+
* Stops when the API says there is no next cursor, so a server that keeps answering
|
|
26
|
+
* `has_more_results` without one cannot spin this forever.
|
|
27
|
+
*/
|
|
28
|
+
export declare function walkPages<T>(fetchPage: (cursor: string | undefined) => Promise<Page<T>>): AsyncGenerator<T, void, undefined>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor pagination, in the two shapes a caller wants.
|
|
3
|
+
*
|
|
4
|
+
* `list` returns one page — the envelope the API sent, cursor included — for a caller
|
|
5
|
+
* driving their own paging. `listAll` walks every page and yields items, which is what
|
|
6
|
+
* most code wants and what it would otherwise write by hand each time.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Walk every page of a list endpoint, yielding items.
|
|
10
|
+
*
|
|
11
|
+
* Stops when the API says there is no next cursor, so a server that keeps answering
|
|
12
|
+
* `has_more_results` without one cannot spin this forever.
|
|
13
|
+
*/
|
|
14
|
+
export async function* walkPages(fetchPage) {
|
|
15
|
+
let cursor;
|
|
16
|
+
do {
|
|
17
|
+
const page = await fetchPage(cursor);
|
|
18
|
+
yield* page.items;
|
|
19
|
+
cursor = page.pagination.next_cursor ?? undefined;
|
|
20
|
+
} while (cursor !== undefined);
|
|
21
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type ListOptions, type Page } from "../pagination.js";
|
|
2
|
+
import type { BaseModelDefaultsOutput, BaseModelDetail, BaseModelSummary, Modality } from "../generated/types.js";
|
|
3
|
+
import type { HttpClient } from "../http.js";
|
|
4
|
+
export interface BaseModelListOptions extends ListOptions {
|
|
5
|
+
workspaceId?: string;
|
|
6
|
+
/** Filter by output modality. */
|
|
7
|
+
modality?: Modality;
|
|
8
|
+
/** Full-text search on name, aliases, and description. */
|
|
9
|
+
search?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The model catalogue, as this workspace may run it.
|
|
13
|
+
*
|
|
14
|
+
* Read it rather than hard-coding ids: which models a workspace can reach depends on its
|
|
15
|
+
* plan and its policy, and the catalogue changes without an SDK release.
|
|
16
|
+
*/
|
|
17
|
+
export declare class BaseModels {
|
|
18
|
+
private readonly http;
|
|
19
|
+
private readonly workspace;
|
|
20
|
+
constructor(http: HttpClient, workspace: (override?: string) => Promise<string>);
|
|
21
|
+
list(options?: BaseModelListOptions): Promise<Page<BaseModelSummary>>;
|
|
22
|
+
listAll(options?: Omit<BaseModelListOptions, "cursor">): AsyncGenerator<BaseModelSummary, void, undefined>;
|
|
23
|
+
get(baseModelId: string, options?: {
|
|
24
|
+
workspaceId?: string;
|
|
25
|
+
signal?: AbortSignal;
|
|
26
|
+
}): Promise<BaseModelDetail>;
|
|
27
|
+
/**
|
|
28
|
+
* Layer's curated picks, filtered to what this workspace may run.
|
|
29
|
+
*
|
|
30
|
+
* Both maps are ordered best-first, so entry `[0]` is the model to use when the caller
|
|
31
|
+
* expresses no preference — which is exactly what `generate()` does with no base model.
|
|
32
|
+
*/
|
|
33
|
+
defaults(options?: {
|
|
34
|
+
workspaceId?: string;
|
|
35
|
+
signal?: AbortSignal;
|
|
36
|
+
}): Promise<BaseModelDefaultsOutput>;
|
|
37
|
+
/**
|
|
38
|
+
* The JSON Schema of one model's parameters.
|
|
39
|
+
*
|
|
40
|
+
* Validate `parameters` against this before submitting: a key the model does not know
|
|
41
|
+
* is dropped silently, and the run comes back generated from defaults instead.
|
|
42
|
+
*/
|
|
43
|
+
inferenceSchema(baseModelId: string, options?: {
|
|
44
|
+
workspaceId?: string;
|
|
45
|
+
signal?: AbortSignal;
|
|
46
|
+
}): Promise<Record<string, unknown>>;
|
|
47
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { walkPages } from "../pagination.js";
|
|
2
|
+
/**
|
|
3
|
+
* The model catalogue, as this workspace may run it.
|
|
4
|
+
*
|
|
5
|
+
* Read it rather than hard-coding ids: which models a workspace can reach depends on its
|
|
6
|
+
* plan and its policy, and the catalogue changes without an SDK release.
|
|
7
|
+
*/
|
|
8
|
+
export class BaseModels {
|
|
9
|
+
http;
|
|
10
|
+
workspace;
|
|
11
|
+
constructor(http, workspace) {
|
|
12
|
+
this.http = http;
|
|
13
|
+
this.workspace = workspace;
|
|
14
|
+
}
|
|
15
|
+
async list(options = {}) {
|
|
16
|
+
const id = await this.workspace(options.workspaceId);
|
|
17
|
+
const body = await this.http.get(`/v2/workspaces/${id}/base-models`, {
|
|
18
|
+
query: {
|
|
19
|
+
limit: options.limit,
|
|
20
|
+
cursor: options.cursor,
|
|
21
|
+
modality: options.modality,
|
|
22
|
+
search: options.search,
|
|
23
|
+
},
|
|
24
|
+
signal: options.signal,
|
|
25
|
+
});
|
|
26
|
+
return { items: body.base_models, pagination: body.pagination };
|
|
27
|
+
}
|
|
28
|
+
listAll(options = {}) {
|
|
29
|
+
return walkPages((cursor) => this.list({ ...options, cursor }));
|
|
30
|
+
}
|
|
31
|
+
async get(baseModelId, options = {}) {
|
|
32
|
+
const id = await this.workspace(options.workspaceId);
|
|
33
|
+
return this.http.get(`/v2/workspaces/${id}/base-models/${baseModelId}`, {
|
|
34
|
+
signal: options.signal,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Layer's curated picks, filtered to what this workspace may run.
|
|
39
|
+
*
|
|
40
|
+
* Both maps are ordered best-first, so entry `[0]` is the model to use when the caller
|
|
41
|
+
* expresses no preference — which is exactly what `generate()` does with no base model.
|
|
42
|
+
*/
|
|
43
|
+
async defaults(options = {}) {
|
|
44
|
+
const id = await this.workspace(options.workspaceId);
|
|
45
|
+
return this.http.get(`/v2/workspaces/${id}/base-models/defaults`, {
|
|
46
|
+
signal: options.signal,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The JSON Schema of one model's parameters.
|
|
51
|
+
*
|
|
52
|
+
* Validate `parameters` against this before submitting: a key the model does not know
|
|
53
|
+
* is dropped silently, and the run comes back generated from defaults instead.
|
|
54
|
+
*/
|
|
55
|
+
async inferenceSchema(baseModelId, options = {}) {
|
|
56
|
+
const id = await this.workspace(options.workspaceId);
|
|
57
|
+
return this.http.get(`/v2/workspaces/${id}/base-models/${baseModelId}/inference-schema`, { signal: options.signal });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { FileScoresOutput, FileSourceType, RequestUploadUrlRequest, RequestUploadUrlResponse } from "../generated/types.js";
|
|
2
|
+
import type { FetchLike, HttpClient } from "../http.js";
|
|
3
|
+
/** Bytes the SDK knows how to upload. */
|
|
4
|
+
export type UploadableContent = Uint8Array | ArrayBuffer | Blob;
|
|
5
|
+
export interface UploadOptions {
|
|
6
|
+
/** MIME type of the content, e.g. `image/png`. Required — storage records it verbatim. */
|
|
7
|
+
contentType: string;
|
|
8
|
+
/** Original file name, kept for display. */
|
|
9
|
+
fileName?: string;
|
|
10
|
+
/** What produced the file. */
|
|
11
|
+
sourceType?: FileSourceType;
|
|
12
|
+
workspaceId?: string;
|
|
13
|
+
idempotencyKey?: string;
|
|
14
|
+
signal?: AbortSignal;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Workspace files: the inputs a generation references and the outputs it produces.
|
|
18
|
+
*
|
|
19
|
+
* Uploads go straight to storage rather than through the API, so a large reference image
|
|
20
|
+
* never crosses the server. `upload()` runs the whole handshake; `requestUploadUrl()` is
|
|
21
|
+
* there for a caller doing their own transfer.
|
|
22
|
+
*/
|
|
23
|
+
export declare class Files {
|
|
24
|
+
private readonly http;
|
|
25
|
+
private readonly workspace;
|
|
26
|
+
private readonly fetch;
|
|
27
|
+
constructor(http: HttpClient, workspace: (override?: string) => Promise<string>, fetch: FetchLike);
|
|
28
|
+
/** Mint a signed URL for a direct-to-storage upload. Expires in 15 minutes. */
|
|
29
|
+
requestUploadUrl(request: RequestUploadUrlRequest, options?: {
|
|
30
|
+
workspaceId?: string;
|
|
31
|
+
idempotencyKey?: string;
|
|
32
|
+
signal?: AbortSignal;
|
|
33
|
+
}): Promise<RequestUploadUrlResponse>;
|
|
34
|
+
/**
|
|
35
|
+
* Upload content and return the file id to pass to a generation.
|
|
36
|
+
*
|
|
37
|
+
* Three steps the API documents and every caller would otherwise repeat: mint a signed
|
|
38
|
+
* URL, open a resumable session against it, then send the bytes.
|
|
39
|
+
*/
|
|
40
|
+
upload(content: UploadableContent, options: UploadOptions): Promise<RequestUploadUrlResponse>;
|
|
41
|
+
/** Scores recorded for a file by the workspace's output scoring rules. */
|
|
42
|
+
scores(fileId: string, options?: {
|
|
43
|
+
workspaceId?: string;
|
|
44
|
+
signal?: AbortSignal;
|
|
45
|
+
}): Promise<FileScoresOutput>;
|
|
46
|
+
/**
|
|
47
|
+
* Start a resumable upload and return the session URI storage answers with.
|
|
48
|
+
*
|
|
49
|
+
* The size range and the resumable marker are part of what the backend signed into the
|
|
50
|
+
* URL, so storage verifies the signature against them: sending anything else, or
|
|
51
|
+
* leaving them off, is rejected before the bytes are ever offered.
|
|
52
|
+
*/
|
|
53
|
+
private openSession;
|
|
54
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { LayerConnectionError } from "../errors.js";
|
|
2
|
+
const toBytes = async (content) => {
|
|
3
|
+
if (content instanceof Uint8Array)
|
|
4
|
+
return content;
|
|
5
|
+
if (content instanceof ArrayBuffer)
|
|
6
|
+
return new Uint8Array(content);
|
|
7
|
+
return new Uint8Array(await content.arrayBuffer());
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Workspace files: the inputs a generation references and the outputs it produces.
|
|
11
|
+
*
|
|
12
|
+
* Uploads go straight to storage rather than through the API, so a large reference image
|
|
13
|
+
* never crosses the server. `upload()` runs the whole handshake; `requestUploadUrl()` is
|
|
14
|
+
* there for a caller doing their own transfer.
|
|
15
|
+
*/
|
|
16
|
+
export class Files {
|
|
17
|
+
http;
|
|
18
|
+
workspace;
|
|
19
|
+
fetch;
|
|
20
|
+
constructor(http, workspace, fetch) {
|
|
21
|
+
this.http = http;
|
|
22
|
+
this.workspace = workspace;
|
|
23
|
+
this.fetch = fetch;
|
|
24
|
+
}
|
|
25
|
+
/** Mint a signed URL for a direct-to-storage upload. Expires in 15 minutes. */
|
|
26
|
+
async requestUploadUrl(request, options = {}) {
|
|
27
|
+
const id = await this.workspace(options.workspaceId);
|
|
28
|
+
return this.http.post(`/v2/workspaces/${id}/files/upload-url`, {
|
|
29
|
+
body: request,
|
|
30
|
+
idempotencyKey: options.idempotencyKey,
|
|
31
|
+
signal: options.signal,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Upload content and return the file id to pass to a generation.
|
|
36
|
+
*
|
|
37
|
+
* Three steps the API documents and every caller would otherwise repeat: mint a signed
|
|
38
|
+
* URL, open a resumable session against it, then send the bytes.
|
|
39
|
+
*/
|
|
40
|
+
async upload(content, options) {
|
|
41
|
+
const bytes = await toBytes(content);
|
|
42
|
+
const minted = await this.requestUploadUrl({
|
|
43
|
+
content_type: options.contentType,
|
|
44
|
+
file_size_bytes: bytes.byteLength,
|
|
45
|
+
file_name: options.fileName,
|
|
46
|
+
source_type: options.sourceType,
|
|
47
|
+
}, {
|
|
48
|
+
workspaceId: options.workspaceId,
|
|
49
|
+
idempotencyKey: options.idempotencyKey,
|
|
50
|
+
signal: options.signal,
|
|
51
|
+
});
|
|
52
|
+
const session = await this.openSession(minted, bytes.byteLength, options.signal);
|
|
53
|
+
const uploaded = await this.fetch(session, {
|
|
54
|
+
method: "PUT",
|
|
55
|
+
headers: { "content-type": minted.content_type },
|
|
56
|
+
body: bytes,
|
|
57
|
+
signal: options.signal,
|
|
58
|
+
});
|
|
59
|
+
if (!uploaded.ok) {
|
|
60
|
+
throw new LayerConnectionError(`Storage rejected the upload of ${options.fileName ?? "the file"} with ${uploaded.status}.`);
|
|
61
|
+
}
|
|
62
|
+
return minted;
|
|
63
|
+
}
|
|
64
|
+
/** Scores recorded for a file by the workspace's output scoring rules. */
|
|
65
|
+
async scores(fileId, options = {}) {
|
|
66
|
+
const id = await this.workspace(options.workspaceId);
|
|
67
|
+
return this.http.get(`/v2/workspaces/${id}/files/${fileId}/scores`, {
|
|
68
|
+
signal: options.signal,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Start a resumable upload and return the session URI storage answers with.
|
|
73
|
+
*
|
|
74
|
+
* The size range and the resumable marker are part of what the backend signed into the
|
|
75
|
+
* URL, so storage verifies the signature against them: sending anything else, or
|
|
76
|
+
* leaving them off, is rejected before the bytes are ever offered.
|
|
77
|
+
*/
|
|
78
|
+
async openSession(minted, sizeBytes, signal) {
|
|
79
|
+
const response = await this.fetch(minted.upload_url, {
|
|
80
|
+
method: "POST",
|
|
81
|
+
headers: {
|
|
82
|
+
"x-goog-resumable": "start",
|
|
83
|
+
"x-goog-content-length-range": `0,${sizeBytes}`,
|
|
84
|
+
"content-type": minted.content_type,
|
|
85
|
+
},
|
|
86
|
+
signal,
|
|
87
|
+
});
|
|
88
|
+
const session = response.headers.get("location");
|
|
89
|
+
if (!response.ok || !session) {
|
|
90
|
+
throw new LayerConnectionError(`Storage would not start an upload session for file ${minted.file_id} (${response.status}).`);
|
|
91
|
+
}
|
|
92
|
+
return session;
|
|
93
|
+
}
|
|
94
|
+
}
|