@neta-art/generation 0.1.1 → 0.1.2
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 +36 -0
- package/dist/builtins-B1AheaEa.js.map +1 -1
- package/dist/{builtins-BuI-rf8X.d.ts → builtins-BE6FhnwP.d.ts} +32 -2
- package/dist/builtins-BE6FhnwP.d.ts.map +1 -0
- package/dist/builtins.d.ts +1 -1
- package/dist/cli/index.js +83 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/export-config-BPnZYpmN.js +884 -0
- package/dist/export-config-BPnZYpmN.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -655
- package/package.json +14 -16
- package/dist/builtins-BuI-rf8X.d.ts.map +0 -1
- package/dist/export-config-Bwqnn7Vs.js +0 -128
- package/dist/export-config-Bwqnn7Vs.js.map +0 -1
- package/dist/index.js.map +0 -1
|
@@ -0,0 +1,884 @@
|
|
|
1
|
+
import { a as compactArray, c as slugifyFileName, i as cloneJson, l as MODEL_SCHEMA, n as getBuiltinGenerationModel, o as compactObject, r as listBuiltinGenerationModels, s as getBlockMeta, t as builtinGenerationModels } from "./builtins-B1AheaEa.js";
|
|
2
|
+
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { extname, join } from "node:path";
|
|
4
|
+
import { parse, stringify } from "yaml";
|
|
5
|
+
|
|
6
|
+
//#region src/errors.ts
|
|
7
|
+
var GenerationError = class extends Error {
|
|
8
|
+
constructor(message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "GenerationError";
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
var GenerationConfigError = class extends GenerationError {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "GenerationConfigError";
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
var GenerationValidationError = class extends GenerationError {
|
|
20
|
+
constructor(message) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.name = "GenerationValidationError";
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
var GenerationUnsupportedAdapterError = class extends GenerationError {
|
|
26
|
+
constructor(adapterType) {
|
|
27
|
+
super(`Unsupported generation adapter: ${adapterType}`);
|
|
28
|
+
this.name = "GenerationUnsupportedAdapterError";
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
var GenerationProviderError = class extends GenerationError {
|
|
32
|
+
status;
|
|
33
|
+
body;
|
|
34
|
+
details;
|
|
35
|
+
constructor(message = "Generation provider request failed", options) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.name = "GenerationProviderError";
|
|
38
|
+
this.status = options?.status;
|
|
39
|
+
this.body = options?.body;
|
|
40
|
+
this.details = options?.details;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
var GenerationTimeoutError = class extends GenerationProviderError {
|
|
44
|
+
constructor(message = "Generation request timed out", details) {
|
|
45
|
+
super(message, details ? { details } : void 0);
|
|
46
|
+
this.name = "GenerationTimeoutError";
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/http.ts
|
|
52
|
+
function headersToRecord(headers) {
|
|
53
|
+
if (!headers) return {};
|
|
54
|
+
if (headers instanceof Headers) {
|
|
55
|
+
const output = {};
|
|
56
|
+
headers.forEach((value, key) => {
|
|
57
|
+
output[key] = value;
|
|
58
|
+
});
|
|
59
|
+
return output;
|
|
60
|
+
}
|
|
61
|
+
if (Array.isArray(headers)) return Object.fromEntries(headers.map(([key, value]) => [key, value]));
|
|
62
|
+
return { ...headers };
|
|
63
|
+
}
|
|
64
|
+
function parseJsonBody(body) {
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(body);
|
|
67
|
+
} catch {
|
|
68
|
+
return body;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function parseDebugBody(body) {
|
|
72
|
+
if (typeof body !== "string") return body ? "[non-string body]" : void 0;
|
|
73
|
+
return parseJsonBody(body);
|
|
74
|
+
}
|
|
75
|
+
const TRACE_HEADER_PATTERN = /(^|[-_])(request|trace|span|correlation|cf-ray|x-tt-logid)([-_]|$)|^(x-request-id|x-trace-id|x-correlation-id|traceparent|tracestate|cf-ray|server-timing)$/i;
|
|
76
|
+
function pickTraceHeaders(headers) {
|
|
77
|
+
const output = {};
|
|
78
|
+
for (const [key, value] of Object.entries(headers)) if (TRACE_HEADER_PATTERN.test(key)) output[key] = value;
|
|
79
|
+
return output;
|
|
80
|
+
}
|
|
81
|
+
function emitDebugRequest(debug, url, init) {
|
|
82
|
+
debug.logger({
|
|
83
|
+
type: "request",
|
|
84
|
+
url,
|
|
85
|
+
method: init.method ?? "GET",
|
|
86
|
+
headers: headersToRecord(init.headers),
|
|
87
|
+
body: parseDebugBody(init.body)
|
|
88
|
+
});
|
|
89
|
+
return Date.now();
|
|
90
|
+
}
|
|
91
|
+
async function readDebugResponseBody(response) {
|
|
92
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
93
|
+
if (contentType.includes("application/json") || contentType.includes("+json")) return parseJsonBody(await response.clone().text());
|
|
94
|
+
if (contentType.startsWith("text/")) return response.clone().text();
|
|
95
|
+
return "[non-text body]";
|
|
96
|
+
}
|
|
97
|
+
async function emitDebugResponse(debug, url, response, startedAt) {
|
|
98
|
+
const headers = headersToRecord(response.headers);
|
|
99
|
+
debug.logger({
|
|
100
|
+
type: "response",
|
|
101
|
+
url,
|
|
102
|
+
status: response.status,
|
|
103
|
+
statusText: response.statusText,
|
|
104
|
+
headers,
|
|
105
|
+
trace: pickTraceHeaders(headers),
|
|
106
|
+
elapsedMs: Date.now() - startedAt,
|
|
107
|
+
...debug.includeResponseBody ? { body: await readDebugResponseBody(response) } : {}
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
function createDebugFetch(fetchFn, debug) {
|
|
111
|
+
return (async (input, init) => {
|
|
112
|
+
const url = String(input instanceof Request ? input.url : input);
|
|
113
|
+
const startedAt = emitDebugRequest(debug, url, init ?? (input instanceof Request ? input : {}));
|
|
114
|
+
const response = await fetchFn(input, init);
|
|
115
|
+
await emitDebugResponse(debug, url, response, startedAt);
|
|
116
|
+
return response;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
async function fetchWithTimeout(fetchFn, url, init, timeoutMs) {
|
|
120
|
+
const controller = new AbortController();
|
|
121
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
122
|
+
try {
|
|
123
|
+
return await fetchFn(url, {
|
|
124
|
+
...init,
|
|
125
|
+
signal: controller.signal
|
|
126
|
+
});
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (error instanceof Error && error.name === "AbortError") throw new GenerationTimeoutError();
|
|
129
|
+
throw error;
|
|
130
|
+
} finally {
|
|
131
|
+
clearTimeout(timeout);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function joinUrl(baseUrl, path) {
|
|
135
|
+
return `${baseUrl.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/validation.ts
|
|
140
|
+
function specsByType(specs) {
|
|
141
|
+
const map = /* @__PURE__ */ new Map();
|
|
142
|
+
for (const spec of specs) map.set(spec.type, spec);
|
|
143
|
+
return map;
|
|
144
|
+
}
|
|
145
|
+
function validateGenerationContent(declaration, content) {
|
|
146
|
+
const inputSpecs = specsByType(declaration.content.input);
|
|
147
|
+
const counts = /* @__PURE__ */ new Map();
|
|
148
|
+
for (const block of content) {
|
|
149
|
+
const spec = inputSpecs.get(block.type);
|
|
150
|
+
if (!spec) throw new GenerationValidationError(`Content block type is not supported by ${declaration.model}: ${block.type}`);
|
|
151
|
+
counts.set(block.type, (counts.get(block.type) ?? 0) + 1);
|
|
152
|
+
if ("source" in block && spec.sources && !spec.sources.includes(block.source.type)) throw new GenerationValidationError(`${block.type} source is not supported by ${declaration.model}: ${block.source.type}`);
|
|
153
|
+
}
|
|
154
|
+
for (const spec of declaration.content.input) {
|
|
155
|
+
const count = counts.get(spec.type) ?? 0;
|
|
156
|
+
if (spec.required && count === 0) throw new GenerationValidationError(`Missing required ${spec.type} content block`);
|
|
157
|
+
if (spec.min !== void 0 && count < spec.min) throw new GenerationValidationError(`Expected at least ${spec.min} ${spec.type} content block(s)`);
|
|
158
|
+
if (spec.max !== void 0 && count > spec.max) throw new GenerationValidationError(`Expected at most ${spec.max} ${spec.type} content block(s)`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function resolveGenerationParameters(declaration, parameters) {
|
|
162
|
+
const specs = declaration.parameters ?? {};
|
|
163
|
+
const resolved = {};
|
|
164
|
+
for (const key of Object.keys(parameters ?? {})) if (!specs[key]) throw new GenerationValidationError(`Unknown parameter: ${key}`);
|
|
165
|
+
for (const [key, spec] of Object.entries(specs)) {
|
|
166
|
+
const value = parameters?.[key];
|
|
167
|
+
if (value === void 0) {
|
|
168
|
+
if (spec.default !== void 0) resolved[key] = spec.default;
|
|
169
|
+
else if (!spec.optional) throw new GenerationValidationError(`Missing required parameter: ${key}`);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
switch (spec.type) {
|
|
173
|
+
case "string":
|
|
174
|
+
if (typeof value !== "string") throw new GenerationValidationError(`Parameter ${key} must be a string`);
|
|
175
|
+
if (spec.enum && !spec.enum.includes(value)) throw new GenerationValidationError(`Parameter ${key} must be one of: ${spec.enum.join(", ")}`);
|
|
176
|
+
break;
|
|
177
|
+
case "number":
|
|
178
|
+
if (typeof value !== "number" || !Number.isFinite(value)) throw new GenerationValidationError(`Parameter ${key} must be a number`);
|
|
179
|
+
if (spec.min !== void 0 && value < spec.min) throw new GenerationValidationError(`Parameter ${key} must be >= ${spec.min}`);
|
|
180
|
+
if (spec.max !== void 0 && value > spec.max) throw new GenerationValidationError(`Parameter ${key} must be <= ${spec.max}`);
|
|
181
|
+
break;
|
|
182
|
+
case "integer":
|
|
183
|
+
if (typeof value !== "number" || !Number.isInteger(value)) throw new GenerationValidationError(`Parameter ${key} must be an integer`);
|
|
184
|
+
if (spec.min !== void 0 && value < spec.min) throw new GenerationValidationError(`Parameter ${key} must be >= ${spec.min}`);
|
|
185
|
+
if (spec.max !== void 0 && value > spec.max) throw new GenerationValidationError(`Parameter ${key} must be <= ${spec.max}`);
|
|
186
|
+
break;
|
|
187
|
+
case "boolean":
|
|
188
|
+
if (typeof value !== "boolean") throw new GenerationValidationError(`Parameter ${key} must be a boolean`);
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
resolved[key] = value;
|
|
192
|
+
}
|
|
193
|
+
return resolved;
|
|
194
|
+
}
|
|
195
|
+
function mergeTextBlocks(declaration, content) {
|
|
196
|
+
const textSpec = declaration.content.input.find((spec) => spec.type === "text");
|
|
197
|
+
const separator = textSpec?.merge === "space" ? " " : textSpec?.merge === "concat" ? "" : "\n";
|
|
198
|
+
return content.filter((block) => block.type === "text").map((block) => block.text).join(separator).trim();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
//#endregion
|
|
202
|
+
//#region src/adapters/ark-video-generations.ts
|
|
203
|
+
const REQUEST_TIMEOUT_MS$2 = 6e4;
|
|
204
|
+
const DEFAULT_POLL_INTERVAL_SEC = 2;
|
|
205
|
+
const DEFAULT_MAX_WAIT_SEC = 600;
|
|
206
|
+
const RESOLUTION_SHORT_EDGE = {
|
|
207
|
+
"480p": 480,
|
|
208
|
+
"720p": 720,
|
|
209
|
+
"1080p": 1080,
|
|
210
|
+
"2K": 1440
|
|
211
|
+
};
|
|
212
|
+
const ASPECT_RATIOS = {
|
|
213
|
+
"16:9": [16, 9],
|
|
214
|
+
"9:16": [9, 16],
|
|
215
|
+
"1:1": [1, 1],
|
|
216
|
+
"4:3": [4, 3],
|
|
217
|
+
"3:2": [3, 2],
|
|
218
|
+
"2:3": [2, 3],
|
|
219
|
+
"3:4": [3, 4],
|
|
220
|
+
"21:9": [21, 9],
|
|
221
|
+
adaptive: null
|
|
222
|
+
};
|
|
223
|
+
function sleep(ms) {
|
|
224
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
225
|
+
}
|
|
226
|
+
function asString(value) {
|
|
227
|
+
return typeof value === "string" && value ? value : void 0;
|
|
228
|
+
}
|
|
229
|
+
function asNumber(value) {
|
|
230
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
231
|
+
}
|
|
232
|
+
function asBoolean(value) {
|
|
233
|
+
return typeof value === "boolean" ? value : void 0;
|
|
234
|
+
}
|
|
235
|
+
function normalizeStatus(value) {
|
|
236
|
+
const status = value.toLowerCase();
|
|
237
|
+
return status === "success" ? "succeeded" : status;
|
|
238
|
+
}
|
|
239
|
+
function getIntegerParameter(parameters, key, fallback) {
|
|
240
|
+
const value = parameters[key];
|
|
241
|
+
return typeof value === "number" && Number.isInteger(value) ? value : fallback;
|
|
242
|
+
}
|
|
243
|
+
function resolveSize(resolution, aspectRatio) {
|
|
244
|
+
const ratio = ASPECT_RATIOS[aspectRatio];
|
|
245
|
+
if (!ratio) return null;
|
|
246
|
+
const shortEdge = RESOLUTION_SHORT_EDGE[resolution];
|
|
247
|
+
if (!shortEdge) throw new GenerationValidationError(`Unsupported resolution: ${resolution}`);
|
|
248
|
+
const [wRatio, hRatio] = ratio;
|
|
249
|
+
const width = wRatio >= hRatio ? Math.round(shortEdge * wRatio / hRatio) : shortEdge;
|
|
250
|
+
const height = wRatio >= hRatio ? shortEdge : Math.round(shortEdge * hRatio / wRatio);
|
|
251
|
+
return {
|
|
252
|
+
width: width % 2 === 0 ? width : width + 1,
|
|
253
|
+
height: height % 2 === 0 ? height : height + 1
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
function getImageRole(block) {
|
|
257
|
+
const role = getBlockMeta(block)?.role;
|
|
258
|
+
return typeof role === "string" && role ? role : void 0;
|
|
259
|
+
}
|
|
260
|
+
function classifyImages(images) {
|
|
261
|
+
if (images.length === 0) return null;
|
|
262
|
+
const hasFirstOrLast = images.some((image) => image.role === "first_frame" || image.role === "last_frame");
|
|
263
|
+
const hasReference = images.some((image) => image.role === "reference_image");
|
|
264
|
+
if ([
|
|
265
|
+
images.some((image) => !image.role),
|
|
266
|
+
hasFirstOrLast,
|
|
267
|
+
hasReference
|
|
268
|
+
].filter(Boolean).length > 1) throw new GenerationValidationError("Cannot mix video image modes: use only plain image, first_frame/last_frame, or reference_image");
|
|
269
|
+
if (hasReference) return "reference";
|
|
270
|
+
if (hasFirstOrLast) return "frame";
|
|
271
|
+
return "image";
|
|
272
|
+
}
|
|
273
|
+
function buildMetadataContent(prompt, images, mode) {
|
|
274
|
+
const content = [{
|
|
275
|
+
type: "text",
|
|
276
|
+
text: prompt
|
|
277
|
+
}];
|
|
278
|
+
for (const image of images) {
|
|
279
|
+
if (mode === "frame" && image.role !== "first_frame" && image.role !== "last_frame") throw new GenerationValidationError("Frame mode images must use meta.role first_frame or last_frame");
|
|
280
|
+
if (mode === "reference" && image.role !== "reference_image") throw new GenerationValidationError("Reference mode images must use meta.role reference_image");
|
|
281
|
+
content.push({
|
|
282
|
+
type: "image_url",
|
|
283
|
+
image_url: { url: image.url },
|
|
284
|
+
role: image.role
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
return content;
|
|
288
|
+
}
|
|
289
|
+
function extractTaskId(response) {
|
|
290
|
+
const taskId = asString(response.task_id) ?? asString(response.id);
|
|
291
|
+
if (!taskId) throw new GenerationProviderError("Video generation provider did not return a task id", { details: { response } });
|
|
292
|
+
return taskId;
|
|
293
|
+
}
|
|
294
|
+
function normalizeTaskStatus(response) {
|
|
295
|
+
if (response.data) {
|
|
296
|
+
const wrapper = response.data;
|
|
297
|
+
const native = wrapper.data;
|
|
298
|
+
const status = normalizeStatus(asString(native?.status) ?? asString(wrapper.status) ?? "unknown");
|
|
299
|
+
const videoUrl = asString(wrapper.result_url) ?? asString(native?.content?.video_url);
|
|
300
|
+
const lastFrameUrl = asString(wrapper.first_frame) ?? asString(native?.content?.first_frame);
|
|
301
|
+
const metadata = {
|
|
302
|
+
progress: wrapper.progress,
|
|
303
|
+
resolution: native?.resolution,
|
|
304
|
+
ratio: native?.ratio,
|
|
305
|
+
duration: native?.duration,
|
|
306
|
+
framespersecond: native?.framespersecond,
|
|
307
|
+
seed: native?.seed,
|
|
308
|
+
generate_audio: native?.generate_audio,
|
|
309
|
+
model: native?.model,
|
|
310
|
+
usage: native?.usage
|
|
311
|
+
};
|
|
312
|
+
for (const key of Object.keys(metadata)) if (metadata[key] === void 0) delete metadata[key];
|
|
313
|
+
return {
|
|
314
|
+
status,
|
|
315
|
+
videoUrl,
|
|
316
|
+
lastFrameUrl,
|
|
317
|
+
metadata
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
status: "unknown",
|
|
322
|
+
videoUrl: void 0,
|
|
323
|
+
lastFrameUrl: void 0,
|
|
324
|
+
metadata: {}
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
async function requestJson(input, path, init) {
|
|
328
|
+
const response = await fetchWithTimeout(input.context.fetch, joinUrl(input.context.baseUrl, path), {
|
|
329
|
+
...init,
|
|
330
|
+
headers: {
|
|
331
|
+
Authorization: `Bearer ${input.context.apiKey}`,
|
|
332
|
+
"Content-Type": "application/json",
|
|
333
|
+
...init.headers
|
|
334
|
+
}
|
|
335
|
+
}, REQUEST_TIMEOUT_MS$2);
|
|
336
|
+
if (!response.ok) {
|
|
337
|
+
const body = await response.text().catch(() => response.statusText);
|
|
338
|
+
throw new GenerationProviderError("Video generation provider request failed", {
|
|
339
|
+
status: response.status,
|
|
340
|
+
body
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
return response.json();
|
|
344
|
+
}
|
|
345
|
+
async function arkVideoGenerationsAdapter(input) {
|
|
346
|
+
const prompt = mergeTextBlocks(input.declaration, input.request.content);
|
|
347
|
+
if (!prompt) throw new GenerationValidationError("Prompt text is required");
|
|
348
|
+
const imageBlocks = input.request.content.filter((block) => block.type === "image");
|
|
349
|
+
const images = await Promise.all(imageBlocks.map(async (block) => ({
|
|
350
|
+
url: await input.context.resolveSource(block.source),
|
|
351
|
+
role: getImageRole(block)
|
|
352
|
+
})));
|
|
353
|
+
const mode = classifyImages(images);
|
|
354
|
+
const resolution = asString(input.parameters.resolution) ?? "720p";
|
|
355
|
+
const aspectRatio = asString(input.parameters.aspect_ratio) ?? "16:9";
|
|
356
|
+
const duration = getIntegerParameter(input.parameters, "duration", 5);
|
|
357
|
+
const fps = getIntegerParameter(input.parameters, "fps", 30);
|
|
358
|
+
const pollIntervalSec = getIntegerParameter(input.parameters, "poll_interval", DEFAULT_POLL_INTERVAL_SEC);
|
|
359
|
+
const maxWaitSec = getIntegerParameter(input.parameters, "max_wait", DEFAULT_MAX_WAIT_SEC);
|
|
360
|
+
const generateAudio = asBoolean(input.parameters.generate_audio) ?? true;
|
|
361
|
+
const returnLastFrame = asBoolean(input.parameters.return_last_frame) ?? true;
|
|
362
|
+
const cameraFixed = asBoolean(input.parameters.camera_fixed) ?? false;
|
|
363
|
+
const watermark = asBoolean(input.parameters.watermark) ?? false;
|
|
364
|
+
const seed = asNumber(input.parameters.seed);
|
|
365
|
+
const payload = {
|
|
366
|
+
model: input.declaration.model,
|
|
367
|
+
prompt
|
|
368
|
+
};
|
|
369
|
+
const metadata = {
|
|
370
|
+
duration,
|
|
371
|
+
fps,
|
|
372
|
+
generate_audio: generateAudio
|
|
373
|
+
};
|
|
374
|
+
if (seed !== void 0) metadata.seed = seed;
|
|
375
|
+
if (returnLastFrame) metadata.return_last_frame = true;
|
|
376
|
+
if (cameraFixed) metadata.camera_fixed = true;
|
|
377
|
+
if (watermark) metadata.watermark = true;
|
|
378
|
+
if (mode === "frame" || mode === "reference") {
|
|
379
|
+
metadata.content = buildMetadataContent(prompt, images, mode);
|
|
380
|
+
metadata.resolution = resolution;
|
|
381
|
+
metadata.ratio = aspectRatio;
|
|
382
|
+
} else {
|
|
383
|
+
const size = resolveSize(resolution, aspectRatio);
|
|
384
|
+
if (size) {
|
|
385
|
+
payload.width = size.width;
|
|
386
|
+
payload.height = size.height;
|
|
387
|
+
}
|
|
388
|
+
if (images[0]) payload.image = images[0].url;
|
|
389
|
+
}
|
|
390
|
+
payload.metadata = metadata;
|
|
391
|
+
const taskId = extractTaskId(await requestJson(input, "/v1/video/generations", {
|
|
392
|
+
method: "POST",
|
|
393
|
+
body: JSON.stringify(payload)
|
|
394
|
+
}));
|
|
395
|
+
const startedAt = Date.now();
|
|
396
|
+
while (Date.now() - startedAt <= maxWaitSec * 1e3) {
|
|
397
|
+
await sleep(pollIntervalSec * 1e3);
|
|
398
|
+
const rawStatus = await requestJson(input, `/v1/video/generations/${encodeURIComponent(taskId)}`, { method: "GET" });
|
|
399
|
+
const status = normalizeTaskStatus(rawStatus);
|
|
400
|
+
if (status.status === "succeeded") {
|
|
401
|
+
if (!status.videoUrl) throw new GenerationProviderError("Video generation succeeded but returned no video URL", { details: compactObject({
|
|
402
|
+
taskId,
|
|
403
|
+
rawStatus,
|
|
404
|
+
metadata: status.metadata
|
|
405
|
+
}) });
|
|
406
|
+
const output = [{
|
|
407
|
+
type: "video",
|
|
408
|
+
source: {
|
|
409
|
+
type: "url",
|
|
410
|
+
url: status.videoUrl
|
|
411
|
+
},
|
|
412
|
+
meta: {
|
|
413
|
+
task_id: taskId,
|
|
414
|
+
status: status.status,
|
|
415
|
+
...status.metadata
|
|
416
|
+
}
|
|
417
|
+
}];
|
|
418
|
+
if (status.lastFrameUrl) output.push({
|
|
419
|
+
type: "image",
|
|
420
|
+
source: {
|
|
421
|
+
type: "url",
|
|
422
|
+
url: status.lastFrameUrl
|
|
423
|
+
},
|
|
424
|
+
meta: {
|
|
425
|
+
role: "last_frame",
|
|
426
|
+
task_id: taskId
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
return output;
|
|
430
|
+
}
|
|
431
|
+
if ([
|
|
432
|
+
"failed",
|
|
433
|
+
"expired",
|
|
434
|
+
"cancelled"
|
|
435
|
+
].includes(status.status)) throw new GenerationProviderError(`Video generation ${status.status}`, { details: {
|
|
436
|
+
taskId,
|
|
437
|
+
rawStatus
|
|
438
|
+
} });
|
|
439
|
+
}
|
|
440
|
+
throw new GenerationTimeoutError("Timed out waiting for video generation", { taskId });
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
//#endregion
|
|
444
|
+
//#region src/adapters/gemini-generate-content.ts
|
|
445
|
+
const REQUEST_TIMEOUT_MS$1 = 3e5;
|
|
446
|
+
const IMAGE_FETCH_TIMEOUT_MS = 6e4;
|
|
447
|
+
const MAX_REFERENCE_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
448
|
+
const DATA_URI_PATTERN = /^data:([^;]+);base64,(.+)$/s;
|
|
449
|
+
const MARKDOWN_IMAGE_DATA_URI_PATTERN = /!\[[^\]]*\]\(data:([^;]+);base64,([^)]+)\)/;
|
|
450
|
+
function dataUriToInlineData(value) {
|
|
451
|
+
const match = DATA_URI_PATTERN.exec(value);
|
|
452
|
+
if (!match) return null;
|
|
453
|
+
const [, mimeType, data] = match;
|
|
454
|
+
if (!mimeType || !data) return null;
|
|
455
|
+
return { inlineData: {
|
|
456
|
+
mimeType,
|
|
457
|
+
data
|
|
458
|
+
} };
|
|
459
|
+
}
|
|
460
|
+
async function urlToInlineData(fetchFn, url) {
|
|
461
|
+
const response = await fetchWithTimeout(fetchFn, url, {
|
|
462
|
+
method: "GET",
|
|
463
|
+
headers: { "User-Agent": "NetaGeneration/1.0" }
|
|
464
|
+
}, IMAGE_FETCH_TIMEOUT_MS);
|
|
465
|
+
if (!response.ok) throw new GenerationProviderError("Failed to fetch reference image", { status: response.status });
|
|
466
|
+
const contentLength = response.headers.get("content-length");
|
|
467
|
+
if (contentLength && Number(contentLength) > MAX_REFERENCE_IMAGE_BYTES) throw new GenerationValidationError("Reference image is too large");
|
|
468
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
469
|
+
if (bytes.byteLength > MAX_REFERENCE_IMAGE_BYTES) throw new GenerationValidationError("Reference image is too large");
|
|
470
|
+
const contentType = response.headers.get("content-type")?.split(";")[0]?.trim();
|
|
471
|
+
return { inlineData: {
|
|
472
|
+
mimeType: contentType?.startsWith("image/") ? contentType : "image/png",
|
|
473
|
+
data: bytes.toString("base64")
|
|
474
|
+
} };
|
|
475
|
+
}
|
|
476
|
+
async function sourceToInlineData(input, value) {
|
|
477
|
+
const inline = dataUriToInlineData(value);
|
|
478
|
+
if (inline) return inline;
|
|
479
|
+
if (value.startsWith("http://") || value.startsWith("https://")) return urlToInlineData(input.context.fetch, value);
|
|
480
|
+
throw new GenerationValidationError("Unsupported image source for Gemini image generation");
|
|
481
|
+
}
|
|
482
|
+
function extractMarkdownDataUriImage(text) {
|
|
483
|
+
const match = MARKDOWN_IMAGE_DATA_URI_PATTERN.exec(text);
|
|
484
|
+
if (!match) return null;
|
|
485
|
+
const [, mediaType, data] = match;
|
|
486
|
+
if (!mediaType || !data) return null;
|
|
487
|
+
return {
|
|
488
|
+
type: "image",
|
|
489
|
+
source: {
|
|
490
|
+
type: "base64",
|
|
491
|
+
mediaType,
|
|
492
|
+
data
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
function collectGeminiNoOutputDetails(raw) {
|
|
497
|
+
const candidates = raw.candidates ?? [];
|
|
498
|
+
return compactObject({
|
|
499
|
+
finishReasons: compactArray(candidates.map((candidate) => candidate.finishReason).filter((value) => value !== void 0)),
|
|
500
|
+
finishMessages: compactArray(candidates.map((candidate) => candidate.finishMessage).filter((value) => value !== void 0)),
|
|
501
|
+
safetyRatings: compactArray(candidates.flatMap((candidate) => candidate.safetyRatings ?? [])),
|
|
502
|
+
promptFeedback: raw.promptFeedback,
|
|
503
|
+
usageMetadata: raw.usageMetadata,
|
|
504
|
+
modelVersion: raw.modelVersion,
|
|
505
|
+
responseId: raw.responseId,
|
|
506
|
+
candidateCount: candidates.length,
|
|
507
|
+
candidates: compactArray(candidates.map((candidate) => compactObject({
|
|
508
|
+
index: candidate.index,
|
|
509
|
+
finishReason: candidate.finishReason,
|
|
510
|
+
finishMessage: candidate.finishMessage,
|
|
511
|
+
safetyRatings: candidate.safetyRatings,
|
|
512
|
+
citationMetadata: candidate.citationMetadata,
|
|
513
|
+
groundingMetadata: candidate.groundingMetadata,
|
|
514
|
+
avgLogprobs: candidate.avgLogprobs,
|
|
515
|
+
contentRole: candidate.content?.role,
|
|
516
|
+
partCount: candidate.content?.parts?.length
|
|
517
|
+
})))
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
function appendGeminiFileDataOutput(output, fileData) {
|
|
521
|
+
if (typeof fileData?.fileUri !== "string" || !fileData.fileUri) return false;
|
|
522
|
+
const mediaType = typeof fileData.mimeType === "string" ? fileData.mimeType : "image/png";
|
|
523
|
+
output.push({
|
|
524
|
+
type: "image",
|
|
525
|
+
source: {
|
|
526
|
+
type: "url",
|
|
527
|
+
url: fileData.fileUri
|
|
528
|
+
},
|
|
529
|
+
meta: { mediaType }
|
|
530
|
+
});
|
|
531
|
+
return true;
|
|
532
|
+
}
|
|
533
|
+
function appendGeminiPartOutput(output, part) {
|
|
534
|
+
if (typeof part.text === "string" && part.text.trim()) {
|
|
535
|
+
const image = extractMarkdownDataUriImage(part.text);
|
|
536
|
+
if (image) {
|
|
537
|
+
output.push(image);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
output.push({
|
|
541
|
+
type: "text",
|
|
542
|
+
text: part.text
|
|
543
|
+
});
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
if (part.inlineData && typeof part.inlineData.data === "string" && part.inlineData.data) {
|
|
547
|
+
output.push({
|
|
548
|
+
type: "image",
|
|
549
|
+
source: {
|
|
550
|
+
type: "base64",
|
|
551
|
+
mediaType: typeof part.inlineData.mimeType === "string" ? part.inlineData.mimeType : "image/png",
|
|
552
|
+
data: part.inlineData.data
|
|
553
|
+
}
|
|
554
|
+
});
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
appendGeminiFileDataOutput(output, part.fileData);
|
|
558
|
+
}
|
|
559
|
+
async function geminiGenerateContentAdapter(input) {
|
|
560
|
+
const prompt = mergeTextBlocks(input.declaration, input.request.content);
|
|
561
|
+
if (!prompt) throw new GenerationValidationError("Prompt text is required");
|
|
562
|
+
const imageParts = await Promise.all(input.request.content.filter((block) => block.type === "image").map(async (block) => sourceToInlineData(input, await input.context.resolveSource(block.source))));
|
|
563
|
+
const generationConfig = { responseModalities: ["IMAGE"] };
|
|
564
|
+
const aspectRatio = input.parameters.aspect_ratio;
|
|
565
|
+
const imageSize = input.parameters.image_size;
|
|
566
|
+
if (typeof aspectRatio === "string" || typeof imageSize === "string") {
|
|
567
|
+
const image = {};
|
|
568
|
+
if (typeof aspectRatio === "string") image.aspectRatio = aspectRatio;
|
|
569
|
+
if (typeof imageSize === "string") image.imageSize = imageSize;
|
|
570
|
+
generationConfig.responseFormat = { image };
|
|
571
|
+
}
|
|
572
|
+
const payload = {
|
|
573
|
+
contents: [{ parts: [{ text: prompt }, ...imageParts] }],
|
|
574
|
+
generationConfig
|
|
575
|
+
};
|
|
576
|
+
const response = await fetchWithTimeout(input.context.fetch, joinUrl(input.context.baseUrl, `/v1beta/models/${encodeURIComponent(input.declaration.model)}:generateContent`), {
|
|
577
|
+
method: "POST",
|
|
578
|
+
headers: {
|
|
579
|
+
Authorization: `Bearer ${input.context.apiKey}`,
|
|
580
|
+
"Content-Type": "application/json"
|
|
581
|
+
},
|
|
582
|
+
body: JSON.stringify(payload)
|
|
583
|
+
}, REQUEST_TIMEOUT_MS$1);
|
|
584
|
+
if (!response.ok) {
|
|
585
|
+
const body = await response.text().catch(() => response.statusText);
|
|
586
|
+
throw new GenerationProviderError("Gemini generation provider request failed", {
|
|
587
|
+
status: response.status,
|
|
588
|
+
body
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
const raw = await response.json();
|
|
592
|
+
const output = [];
|
|
593
|
+
for (const candidate of raw.candidates ?? []) for (const part of candidate.content?.parts ?? []) appendGeminiPartOutput(output, part);
|
|
594
|
+
if (output.length === 0) throw new GenerationProviderError("Gemini generation returned no output", { details: collectGeminiNoOutputDetails(raw) });
|
|
595
|
+
return output;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
//#endregion
|
|
599
|
+
//#region src/adapters/openai-images.ts
|
|
600
|
+
const REQUEST_TIMEOUT_MS = 3e5;
|
|
601
|
+
function collectOpenAiImagesNoOutputDetails(raw) {
|
|
602
|
+
const data = raw.data ?? [];
|
|
603
|
+
return compactObject({
|
|
604
|
+
created: raw.created,
|
|
605
|
+
usage: raw.usage,
|
|
606
|
+
background: raw.background,
|
|
607
|
+
outputFormat: raw.output_format,
|
|
608
|
+
quality: raw.quality,
|
|
609
|
+
size: raw.size,
|
|
610
|
+
dataCount: data.length,
|
|
611
|
+
data: compactArray(data.map((item) => compactObject({
|
|
612
|
+
hasUrl: typeof item.url === "string" && item.url.length > 0,
|
|
613
|
+
hasBase64Json: typeof item.b64_json === "string" && item.b64_json.length > 0,
|
|
614
|
+
revisedPrompt: item.revised_prompt
|
|
615
|
+
})))
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
async function openAiImagesAdapter(input) {
|
|
619
|
+
const prompt = mergeTextBlocks(input.declaration, input.request.content);
|
|
620
|
+
if (!prompt) throw new GenerationValidationError("Prompt text is required");
|
|
621
|
+
const images = await Promise.all(input.request.content.filter((block) => block.type === "image").map((block) => input.context.resolveSource(block.source)));
|
|
622
|
+
const payload = {
|
|
623
|
+
model: input.declaration.model,
|
|
624
|
+
prompt,
|
|
625
|
+
...input.parameters
|
|
626
|
+
};
|
|
627
|
+
if (images.length > 0) payload.image = images;
|
|
628
|
+
const response = await fetchWithTimeout(input.context.fetch, joinUrl(input.context.baseUrl, "/v1/images/generations"), {
|
|
629
|
+
method: "POST",
|
|
630
|
+
headers: {
|
|
631
|
+
Authorization: `Bearer ${input.context.apiKey}`,
|
|
632
|
+
"Content-Type": "application/json"
|
|
633
|
+
},
|
|
634
|
+
body: JSON.stringify(payload)
|
|
635
|
+
}, REQUEST_TIMEOUT_MS);
|
|
636
|
+
if (!response.ok) {
|
|
637
|
+
const body = await response.text().catch(() => response.statusText);
|
|
638
|
+
throw new GenerationProviderError("Image generation provider request failed", {
|
|
639
|
+
status: response.status,
|
|
640
|
+
body
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
const raw = await response.json();
|
|
644
|
+
const output = [];
|
|
645
|
+
for (const item of raw.data ?? []) {
|
|
646
|
+
if (typeof item.url === "string" && item.url) output.push({
|
|
647
|
+
type: "image",
|
|
648
|
+
source: {
|
|
649
|
+
type: "url",
|
|
650
|
+
url: item.url
|
|
651
|
+
}
|
|
652
|
+
});
|
|
653
|
+
if (typeof item.b64_json === "string" && item.b64_json) output.push({
|
|
654
|
+
type: "image",
|
|
655
|
+
source: {
|
|
656
|
+
type: "base64",
|
|
657
|
+
mediaType: "image/png",
|
|
658
|
+
data: item.b64_json
|
|
659
|
+
}
|
|
660
|
+
});
|
|
661
|
+
if (typeof item.revised_prompt === "string" && item.revised_prompt.trim()) output.push({
|
|
662
|
+
type: "text",
|
|
663
|
+
text: item.revised_prompt,
|
|
664
|
+
meta: { role: "revised_prompt" }
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
if (output.length === 0) throw new GenerationProviderError("Image generation returned no output", { details: collectOpenAiImagesNoOutputDetails(raw) });
|
|
668
|
+
return output;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
//#endregion
|
|
672
|
+
//#region src/adapters/index.ts
|
|
673
|
+
const builtinGenerationAdapters = {
|
|
674
|
+
"ark.videoGenerations": arkVideoGenerationsAdapter,
|
|
675
|
+
"gemini.generateContent": geminiGenerateContentAdapter,
|
|
676
|
+
"openai.images": openAiImagesAdapter
|
|
677
|
+
};
|
|
678
|
+
function getGenerationAdapter(type, adapters = {}) {
|
|
679
|
+
const adapter = adapters[type] ?? builtinGenerationAdapters[type];
|
|
680
|
+
if (!adapter) throw new GenerationUnsupportedAdapterError(type);
|
|
681
|
+
return adapter;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
//#endregion
|
|
685
|
+
//#region src/config.ts
|
|
686
|
+
const DECLARATION_EXTENSIONS = new Set([
|
|
687
|
+
".yaml",
|
|
688
|
+
".yml",
|
|
689
|
+
".json"
|
|
690
|
+
]);
|
|
691
|
+
function isRecord(value) {
|
|
692
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
693
|
+
}
|
|
694
|
+
function isParameterSpec(value) {
|
|
695
|
+
if (!isRecord(value)) return false;
|
|
696
|
+
return [
|
|
697
|
+
"string",
|
|
698
|
+
"number",
|
|
699
|
+
"integer",
|
|
700
|
+
"boolean"
|
|
701
|
+
].includes(String(value.type));
|
|
702
|
+
}
|
|
703
|
+
function isGenerationModelDeclaration(value) {
|
|
704
|
+
if (!isRecord(value)) return false;
|
|
705
|
+
const adapter = value.adapter;
|
|
706
|
+
const content = value.content;
|
|
707
|
+
const parameters = value.parameters;
|
|
708
|
+
const examples = value.examples;
|
|
709
|
+
return value.schema === MODEL_SCHEMA && typeof value.model === "string" && value.model.trim().length > 0 && isRecord(adapter) && typeof adapter.type === "string" && isRecord(content) && Array.isArray(content.input) && (parameters === void 0 || isRecord(parameters) && Object.values(parameters).every(isParameterSpec)) && (examples === void 0 || Array.isArray(examples));
|
|
710
|
+
}
|
|
711
|
+
function parseGenerationModelDeclaration(rawText, filePath = "model.yaml") {
|
|
712
|
+
const parsed = extname(filePath) === ".json" ? JSON.parse(rawText) : parse(rawText);
|
|
713
|
+
if (!isGenerationModelDeclaration(parsed)) throw new GenerationConfigError(`Invalid model declaration: ${filePath}`);
|
|
714
|
+
return parsed;
|
|
715
|
+
}
|
|
716
|
+
function stringifyGenerationModelDeclaration(declaration, options = {}) {
|
|
717
|
+
const value = cloneJson(declaration);
|
|
718
|
+
if (options.format === "json") return `${JSON.stringify(value, null, 2)}\n`;
|
|
719
|
+
return stringify(value, { lineWidth: 120 });
|
|
720
|
+
}
|
|
721
|
+
async function readGenerationModelDeclaration(filePath) {
|
|
722
|
+
return parseGenerationModelDeclaration(await readFile(filePath, "utf-8"), filePath);
|
|
723
|
+
}
|
|
724
|
+
async function readGenerationModelDeclarationsFromFiles(filePaths) {
|
|
725
|
+
return mergeGenerationModelDeclarations(await Promise.all(filePaths.map((filePath) => readGenerationModelDeclaration(filePath))));
|
|
726
|
+
}
|
|
727
|
+
async function readGenerationModelDeclarationsFromDirectory(directory) {
|
|
728
|
+
return readGenerationModelDeclarationsFromFiles((await readdir(directory)).filter((entry) => DECLARATION_EXTENSIONS.has(extname(entry))).sort().map((entry) => join(directory, entry)));
|
|
729
|
+
}
|
|
730
|
+
function mergeGenerationModelDeclarations(declarations) {
|
|
731
|
+
const byModel = /* @__PURE__ */ new Map();
|
|
732
|
+
for (const declaration of declarations) byModel.set(declaration.model, declaration);
|
|
733
|
+
return [...byModel.values()].sort((a, b) => a.model.localeCompare(b.model));
|
|
734
|
+
}
|
|
735
|
+
async function writeGenerationModelDeclaration(declaration, filePath, options = {}) {
|
|
736
|
+
await writeFile(filePath, stringifyGenerationModelDeclaration(declaration, options));
|
|
737
|
+
}
|
|
738
|
+
async function writeGenerationModelDeclarations(declarations, directory, options = {}) {
|
|
739
|
+
await mkdir(directory, { recursive: true });
|
|
740
|
+
const ext = options.format === "json" ? "json" : "yaml";
|
|
741
|
+
await Promise.all(declarations.map((declaration) => writeGenerationModelDeclaration(declaration, join(directory, `${slugifyFileName(declaration.model)}.${ext}`), options)));
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
//#endregion
|
|
745
|
+
//#region src/source.ts
|
|
746
|
+
const defaultGenerationSourceResolver = (source) => {
|
|
747
|
+
switch (source.type) {
|
|
748
|
+
case "url": return source.url;
|
|
749
|
+
case "base64": return `data:${source.mediaType};base64,${source.data}`;
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
//#endregion
|
|
754
|
+
//#region src/client.ts
|
|
755
|
+
const DEFAULT_BASE_URL = "https://router.neta.art";
|
|
756
|
+
function redactDebugEvent(value) {
|
|
757
|
+
if (Array.isArray(value)) return value.map((item) => redactDebugEvent(item));
|
|
758
|
+
if (!value || typeof value !== "object") return value;
|
|
759
|
+
const output = {};
|
|
760
|
+
for (const [key, child] of Object.entries(value)) if (/^(authorization|api[-_]?key|token|b64_json|thoughtSignature)$/i.test(key) || key === "data") output[key] = "[REDACTED]";
|
|
761
|
+
else output[key] = redactDebugEvent(child);
|
|
762
|
+
return output;
|
|
763
|
+
}
|
|
764
|
+
function defaultDebugLogger(event) {
|
|
765
|
+
console.error(JSON.stringify(event, null, 2));
|
|
766
|
+
}
|
|
767
|
+
function resolveDebugConfig(debug) {
|
|
768
|
+
if (!debug) return void 0;
|
|
769
|
+
if (debug === true) return {
|
|
770
|
+
enabled: true,
|
|
771
|
+
includeSensitive: false,
|
|
772
|
+
includeResponseBody: true,
|
|
773
|
+
logger: (event) => defaultDebugLogger(redactDebugEvent(event))
|
|
774
|
+
};
|
|
775
|
+
if (!debug.enabled) return void 0;
|
|
776
|
+
const includeSensitive = debug.includeSensitive ?? false;
|
|
777
|
+
const logger = debug.logger ?? defaultDebugLogger;
|
|
778
|
+
return {
|
|
779
|
+
enabled: true,
|
|
780
|
+
includeSensitive,
|
|
781
|
+
includeResponseBody: debug.includeResponseBody ?? true,
|
|
782
|
+
logger: (event) => logger(includeSensitive ? event : redactDebugEvent(event))
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
function resolveModels(options) {
|
|
786
|
+
const models = [...options.includeBuiltinModels ?? !options.models ? builtinGenerationModels : [], ...options.models ?? []];
|
|
787
|
+
const byModel = /* @__PURE__ */ new Map();
|
|
788
|
+
for (const model of models) byModel.set(model.model, cloneJson(model));
|
|
789
|
+
return [...byModel.values()].sort((a, b) => a.model.localeCompare(b.model));
|
|
790
|
+
}
|
|
791
|
+
function createGenerationClient(options = {}) {
|
|
792
|
+
const models = resolveModels(options);
|
|
793
|
+
const byModel = new Map(models.map((declaration) => [declaration.model, declaration]));
|
|
794
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
795
|
+
if (!fetchFn) throw new GenerationConfigError("A fetch implementation is required");
|
|
796
|
+
const debug = resolveDebugConfig(options.debug);
|
|
797
|
+
const adapterFetch = debug ? createDebugFetch(fetchFn, debug) : fetchFn;
|
|
798
|
+
function requireModel(model) {
|
|
799
|
+
const declaration = byModel.get(model);
|
|
800
|
+
if (!declaration) throw new GenerationConfigError(`Generation model is unavailable: ${model}`);
|
|
801
|
+
return declaration;
|
|
802
|
+
}
|
|
803
|
+
return {
|
|
804
|
+
validate(request) {
|
|
805
|
+
const declaration = requireModel(request.model);
|
|
806
|
+
validateGenerationContent(declaration, request.content);
|
|
807
|
+
const parameters = resolveGenerationParameters(declaration, request.parameters);
|
|
808
|
+
return {
|
|
809
|
+
declaration: cloneJson(declaration),
|
|
810
|
+
request: cloneJson(request),
|
|
811
|
+
parameters
|
|
812
|
+
};
|
|
813
|
+
},
|
|
814
|
+
async generate(request) {
|
|
815
|
+
const resolved = this.validate(request);
|
|
816
|
+
const apiKey = request.apiKey ?? options.apiKey;
|
|
817
|
+
if (!apiKey) throw new GenerationConfigError("apiKey is required");
|
|
818
|
+
return getGenerationAdapter(resolved.declaration.adapter.type, options.adapters)({
|
|
819
|
+
...resolved,
|
|
820
|
+
context: {
|
|
821
|
+
apiKey,
|
|
822
|
+
baseUrl: request.baseUrl ?? options.baseUrl ?? DEFAULT_BASE_URL,
|
|
823
|
+
fetch: adapterFetch,
|
|
824
|
+
resolveSource: options.sourceResolver ?? defaultGenerationSourceResolver
|
|
825
|
+
}
|
|
826
|
+
});
|
|
827
|
+
},
|
|
828
|
+
listModels() {
|
|
829
|
+
return cloneJson(models);
|
|
830
|
+
},
|
|
831
|
+
getModel(model) {
|
|
832
|
+
const declaration = byModel.get(model);
|
|
833
|
+
return declaration ? cloneJson(declaration) : null;
|
|
834
|
+
},
|
|
835
|
+
stringifyModelConfig(model, stringifyOptions = {}) {
|
|
836
|
+
return stringifyGenerationModelDeclaration(requireModel(model), stringifyOptions);
|
|
837
|
+
},
|
|
838
|
+
exportModelConfig(model, filePath) {
|
|
839
|
+
return writeGenerationModelDeclaration(requireModel(model), filePath);
|
|
840
|
+
},
|
|
841
|
+
exportModelConfigs(directory) {
|
|
842
|
+
return writeGenerationModelDeclarations(models, directory);
|
|
843
|
+
}
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
async function createGenerationClientFromFiles(filePaths, options = {}) {
|
|
847
|
+
const models = await readGenerationModelDeclarationsFromFiles(filePaths);
|
|
848
|
+
return createGenerationClient({
|
|
849
|
+
...options,
|
|
850
|
+
models,
|
|
851
|
+
includeBuiltinModels: options.includeBuiltinModels ?? true
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
async function createGenerationClientFromDirectory(directory, options = {}) {
|
|
855
|
+
const models = await readGenerationModelDeclarationsFromDirectory(directory);
|
|
856
|
+
return createGenerationClient({
|
|
857
|
+
...options,
|
|
858
|
+
models,
|
|
859
|
+
includeBuiltinModels: options.includeBuiltinModels ?? true
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
async function createGenerationClientFromFile(filePath, options = {}) {
|
|
863
|
+
return createGenerationClientFromFiles([filePath], options);
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
//#endregion
|
|
867
|
+
//#region src/export-config.ts
|
|
868
|
+
function stringifyBuiltinModelConfig(model, options = {}) {
|
|
869
|
+
const declaration = getBuiltinGenerationModel(model);
|
|
870
|
+
if (!declaration) throw new GenerationConfigError(`Built-in model is unavailable: ${model}`);
|
|
871
|
+
return stringifyGenerationModelDeclaration(declaration, options);
|
|
872
|
+
}
|
|
873
|
+
async function exportBuiltinModelConfig(model, filePath) {
|
|
874
|
+
const declaration = getBuiltinGenerationModel(model);
|
|
875
|
+
if (!declaration) throw new GenerationConfigError(`Built-in model is unavailable: ${model}`);
|
|
876
|
+
await writeGenerationModelDeclaration(declaration, filePath);
|
|
877
|
+
}
|
|
878
|
+
async function exportBuiltinModelConfigs(directory) {
|
|
879
|
+
await writeGenerationModelDeclarations(listBuiltinGenerationModels(), directory);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
//#endregion
|
|
883
|
+
export { GenerationUnsupportedAdapterError as A, mergeTextBlocks as C, GenerationError as D, GenerationConfigError as E, GenerationProviderError as O, arkVideoGenerationsAdapter as S, validateGenerationContent as T, writeGenerationModelDeclarations as _, createGenerationClientFromDirectory as a, openAiImagesAdapter as b, defaultGenerationSourceResolver as c, parseGenerationModelDeclaration as d, readGenerationModelDeclaration as f, writeGenerationModelDeclaration as g, stringifyGenerationModelDeclaration as h, createGenerationClient as i, GenerationValidationError as j, GenerationTimeoutError as k, isGenerationModelDeclaration as l, readGenerationModelDeclarationsFromFiles as m, exportBuiltinModelConfigs as n, createGenerationClientFromFile as o, readGenerationModelDeclarationsFromDirectory as p, stringifyBuiltinModelConfig as r, createGenerationClientFromFiles as s, exportBuiltinModelConfig as t, mergeGenerationModelDeclarations as u, builtinGenerationAdapters as v, resolveGenerationParameters as w, geminiGenerateContentAdapter as x, getGenerationAdapter as y };
|
|
884
|
+
//# sourceMappingURL=export-config-BPnZYpmN.js.map
|