@techis/ai-runtime 0.5.0 → 0.6.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/NATIVE-IMAGES.md +52 -0
- package/PYTHON.md +46 -0
- package/README.md +6 -3
- package/dist/adapters/image.d.ts +5 -0
- package/dist/adapters/image.d.ts.map +1 -0
- package/dist/adapters/image.js +105 -0
- package/dist/adapters/image.js.map +1 -0
- package/dist/adapters/registry.d.ts.map +1 -1
- package/dist/adapters/registry.js +8 -2
- package/dist/adapters/registry.js.map +1 -1
- package/dist/adapters/types.d.ts +6 -0
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/adapters/validation.d.ts.map +1 -1
- package/dist/adapters/validation.js +11 -2
- package/dist/adapters/validation.js.map +1 -1
- package/dist/bridge-worker.d.ts +3 -0
- package/dist/bridge-worker.d.ts.map +1 -0
- package/dist/bridge-worker.js +48 -0
- package/dist/bridge-worker.js.map +1 -0
- package/dist/bridge.d.ts +33 -0
- package/dist/bridge.d.ts.map +1 -0
- package/dist/bridge.js +46 -0
- package/dist/bridge.js.map +1 -0
- package/dist/compatibility-execution.d.ts +1 -0
- package/dist/compatibility-execution.d.ts.map +1 -1
- package/dist/image-generation.d.ts +25 -0
- package/dist/image-generation.d.ts.map +1 -0
- package/dist/image-generation.js +59 -0
- package/dist/image-generation.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/route-client.d.ts +3 -0
- package/dist/route-client.d.ts.map +1 -1
- package/dist/route-client.js +4 -1
- package/dist/route-client.js.map +1 -1
- package/dist/route-readiness.d.ts.map +1 -1
- package/dist/route-readiness.js +22 -5
- package/dist/route-readiness.js.map +1 -1
- package/dist/run.d.ts.map +1 -1
- package/dist/run.js +85 -18
- package/dist/run.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +10 -4
- package/python/model_routes/__init__.py +141 -0
- package/python/pyproject.toml +12 -0
package/dist/run.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { withDeadline } from "./deadline.js";
|
|
2
|
+
import { IMAGE_REQUEST, imageOutputEvidence, validateImageRequest, validateImageTransport } from "./image-generation.js";
|
|
2
3
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { compileSchema, deriveReceiptId, deriveNativeReceiptId, deriveModelReceiptId, deriveProfileReceiptId, deriveDirectModelReceiptId, hashInstructions, hashDocumentV2, validateReasoningForModel, reasoningSupportWarnings, isNativeReasoningControl, modelEndpointConflict } from "@techis/ai-contracts";
|
|
4
|
+
import { compileSchema, deriveReceiptId, deriveNativeReceiptId, deriveModelReceiptId, deriveProfileReceiptId, deriveDirectModelReceiptId, hashInstructions, hashDocumentV2, validateReasoningForModel, reasoningSupportWarnings, isNativeReasoningControl, modelEndpointConflict, resolveCatalogSlot } from "@techis/ai-contracts";
|
|
4
5
|
import { AISubsystemError, attachProviderErrorContext, AttemptsExhaustedError, BudgetExceededError, CancellationError, ConfigurationInvalidError, CredentialInvalidError, CredentialUnavailableError, InputLimitExceededError, ProviderCallError, ProviderOutputTruncatedError, InvalidOutputError, UnsupportedAdapterError, UnsupportedCapabilityError } from "./errors.js";
|
|
5
6
|
import { applyReportedCostContext, costContextForRequest, costPricing, costFromUsage, estimateInputTokens, measuredCostContext, mergeReportedUsage, preflightCostCeiling, priceForModel } from "./cost.js";
|
|
6
7
|
import { resolveEffectiveReasoning } from "./reasoning-resolution.js";
|
|
@@ -44,6 +45,14 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
44
45
|
const systemInstructions = "model" in token || "directModel" in token ? token.systemInstructions : token.instructionProjection?.systemInstructions ?? token.persona.systemInstructions;
|
|
45
46
|
const outputRequirements = "model" in token || "directModel" in token ? undefined : token.persona.outputRequirements;
|
|
46
47
|
const models = new Map(snapshot.catalog.models.map((model) => [model.catalogId, model]));
|
|
48
|
+
const resolveSlot = (slot) => {
|
|
49
|
+
try {
|
|
50
|
+
return resolveCatalogSlot(snapshot.catalog, slot);
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
throw new ConfigurationInvalidError(error.message);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
47
56
|
const runId = randomUUID();
|
|
48
57
|
async function execute(options, invocation) {
|
|
49
58
|
const startedAt = invocation?.admittedAt ?? performance.now(), admittedAt = startedAt;
|
|
@@ -51,6 +60,7 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
51
60
|
if (!validOptions)
|
|
52
61
|
options = { operationId: "", input: "" };
|
|
53
62
|
let richRequest;
|
|
63
|
+
let imageRequest;
|
|
54
64
|
let effectiveInstructions = systemInstructions;
|
|
55
65
|
const requestId = typeof options.requestId === "string" && REQUEST_ID_PATTERN.test(options.requestId)
|
|
56
66
|
? options.requestId
|
|
@@ -97,6 +107,18 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
97
107
|
try {
|
|
98
108
|
if (!validOptions)
|
|
99
109
|
throw new ConfigurationInvalidError("Generation options must be an object");
|
|
110
|
+
if (Object.hasOwn(options, "imageRequest"))
|
|
111
|
+
throw new ConfigurationInvalidError("Use images.generate for native image output.");
|
|
112
|
+
if (Object.hasOwn(options, IMAGE_REQUEST)) {
|
|
113
|
+
try {
|
|
114
|
+
imageRequest = structuredClone(options[IMAGE_REQUEST]);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
throw new ConfigurationInvalidError("Image request must be serializable.");
|
|
118
|
+
}
|
|
119
|
+
validateImageRequest(imageRequest);
|
|
120
|
+
options = { ...options, input: imageRequest.prompt };
|
|
121
|
+
}
|
|
100
122
|
if (typeof options.operationId !== "string" || !OPERATION_ID_PATTERN.test(options.operationId)) {
|
|
101
123
|
throw new ConfigurationInvalidError("GenerateOptions.operationId is required and must be a bounded logical identifier (letters, digits, '.', '_', '-'; max 128 characters)");
|
|
102
124
|
}
|
|
@@ -112,9 +134,18 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
112
134
|
if (signal?.aborted)
|
|
113
135
|
throw new CancellationError();
|
|
114
136
|
const profile = executionConfiguration(token);
|
|
137
|
+
if (imageRequest !== undefined) {
|
|
138
|
+
validateImageRequest(imageRequest);
|
|
139
|
+
if (invocation || systemInstructions.length || outputRequirements?.kind === "structured" || options.outputSchema || options.operation ||
|
|
140
|
+
options.maxOutputTokens !== undefined || options.effortHint !== undefined || options.effortByModel !== undefined ||
|
|
141
|
+
profile.defaults?.maxOutputTokens !== undefined || profile.effortPolicy?.enabled || profile.requiredCapabilities.structuredOutput ||
|
|
142
|
+
profile.requiredCapabilities.providerTools?.length || profile.caps?.maxOutputTokens !== undefined ||
|
|
143
|
+
deps.clientCaps?.maxOutputTokens !== undefined || options.caps?.maxOutputTokens !== undefined)
|
|
144
|
+
throw new UnsupportedCapabilityError("Image generation cannot silently discard text, reasoning, schema or tool controls.");
|
|
145
|
+
}
|
|
115
146
|
if (invocation) {
|
|
116
147
|
richRequest = invocation.map().request;
|
|
117
|
-
const primary =
|
|
148
|
+
const primary = resolveSlot(profile.primary);
|
|
118
149
|
if (richRequest.model !== undefined && richRequest.model !== primary?.catalogId && richRequest.model !== primary?.providerModelId)
|
|
119
150
|
throw new ConfigurationInvalidError("Request model differs from the pinned primary model");
|
|
120
151
|
effectiveInstructions = richRequest.instructions === undefined ? systemInstructions : systemInstructions + "\n\n" + richRequest.instructions;
|
|
@@ -239,11 +270,10 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
239
270
|
provenance.modelConfigurationDigest : provenance.revision,
|
|
240
271
|
supportsResponseId: adapter?.supportsResponseId === true };
|
|
241
272
|
};
|
|
242
|
-
const primaryTarget = models.has(profile.primary.catalogId) ? targetFor(
|
|
273
|
+
const primaryTarget = models.has(profile.primary.catalogId) ? targetFor(resolveSlot(profile.primary)) : undefined;
|
|
243
274
|
for (const [index, slot] of slots.entries()) {
|
|
244
|
-
const role = index === 0 ? "primary" : "fallback"
|
|
245
|
-
|
|
246
|
-
throw new ConfigurationInvalidError(`${role} ${slot.catalogId}: missing from the pinned catalog`);
|
|
275
|
+
const role = index === 0 ? "primary" : "fallback";
|
|
276
|
+
const model = resolveSlot(slot);
|
|
247
277
|
if (profile.catalogCompatibility?.excludedCatalogIds?.includes(slot.catalogId))
|
|
248
278
|
throw new ConfigurationInvalidError(`${role} ${slot.catalogId}: excluded by the pinned profile`);
|
|
249
279
|
// An invalid extension is still invalid even if its slot is never reached.
|
|
@@ -256,13 +286,23 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
256
286
|
: modelEndpointConflict(snapshot.catalog, model) ? "model-unavailable"
|
|
257
287
|
: !adapter ? "adapter-missing" : !adapter.providers.includes(model.provider) ? "adapter-provider"
|
|
258
288
|
: minVersion && !satisfiesMin(routeVersion, minVersion) ? "adapter-version"
|
|
259
|
-
: !model.capabilities.outputModalities.includes("
|
|
289
|
+
: imageRequest ? !model.capabilities.outputModalities.includes("image") || !adapter.supportsImageOutput || !adapter.executeImage
|
|
290
|
+
? "image-output" : undefined
|
|
291
|
+
: !model.capabilities.outputModalities.includes("text") ? "text-output" : undefined;
|
|
260
292
|
if (unavailableReason) {
|
|
261
293
|
unavailable.push(`${role} ${slot.catalogId} (${model.provider}): ${unavailableReason}; skipped.`);
|
|
262
294
|
skippedSlots.push({ slot: index, catalogId: slot.catalogId, providerModelId: model.providerModelId, role,
|
|
263
295
|
reason: unavailableReason, phase: "preflight", providerRequestStarted: false });
|
|
264
296
|
continue;
|
|
265
297
|
}
|
|
298
|
+
if (imageRequest) {
|
|
299
|
+
validateImageTransport(imageRequest, adapter.id);
|
|
300
|
+
if (!model.capabilities.inputModalities.includes("text") || !adapter.supportedInputModalities.includes("text"))
|
|
301
|
+
throw new UnsupportedCapabilityError("Image generation requires text prompt input support.");
|
|
302
|
+
if (Object.keys(slot.settings).some(key => key !== "reasoning") ||
|
|
303
|
+
slot.settings.reasoning && slot.settings.reasoning.mode !== "provider-default")
|
|
304
|
+
throw new UnsupportedCapabilityError("Image generation cannot silently discard saved text-generation controls.");
|
|
305
|
+
}
|
|
266
306
|
const generation = richRequest ? structuredClone(richRequest) : { items: [{ type: "message", role: "user", content: [
|
|
267
307
|
{ type: "text", text: typeof options.input === "string" ? options.input : options.input.text ?? "" },
|
|
268
308
|
...(typeof options.input === "string" ? [] : (options.input.images ?? []).map(image => ({ type: "image",
|
|
@@ -283,11 +323,13 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
283
323
|
reason: "continuation-not-portable", phase: "preflight", providerRequestStarted: false });
|
|
284
324
|
continue;
|
|
285
325
|
}
|
|
286
|
-
const features =
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
326
|
+
const features = imageRequest ? { request: generation, buffered: false, warnings: [],
|
|
327
|
+
features: [{ feature: "image-output", requested: true, effective: "sent" }] } :
|
|
328
|
+
planGenerationFeatures({ request: continuation?.request ?? generation, model, adapter: adapter, role,
|
|
329
|
+
stream: Boolean(invocation?.stream),
|
|
330
|
+
requiredInputModalities: profile.requiredCapabilities.inputModalities,
|
|
331
|
+
requiredProviderTools: profile.requiredCapabilities.providerTools, slotProviderOptions: slot.settings.providerOptions,
|
|
332
|
+
reasoningControl: slot.settings.reasoning });
|
|
291
333
|
const blocks = features.request.items.flatMap(item => item.type === "message" ? item.content ?? [] : []);
|
|
292
334
|
if (continuation) {
|
|
293
335
|
features.features.push(...continuation.features);
|
|
@@ -398,7 +440,9 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
398
440
|
const effectiveEstimate = plan.estimatedInputTokens;
|
|
399
441
|
const pricing = costPricing(snapshot.catalog, snapshot.manifest, plan.slot.catalogId, plan.costContext, effectiveEstimate);
|
|
400
442
|
const ceiling = preflightCostCeiling(pricing.price, effectiveEstimate, output.effective ?? knownOutputCeiling(plan.model, effectiveEstimate), pricing.context);
|
|
401
|
-
return [{ plan, effort, nativeSettings, output, preflightCost:
|
|
443
|
+
return [{ plan, effort, nativeSettings, output, preflightCost: imageRequest
|
|
444
|
+
? { currency: "USD", priceKnown: false, uncertainties: ["price-conditions"], basis: "preflight-estimate" }
|
|
445
|
+
: toCostEstimate(ceiling, "preflight-estimate") }];
|
|
402
446
|
});
|
|
403
447
|
// The applicable cost-ceiling policy: profile, client, and invocation caps intersect.
|
|
404
448
|
const budget = intersectCostCaps(profile.caps?.maxEstimatedCost, deps.clientCaps?.maxEstimatedCost, options.caps?.maxEstimatedCost);
|
|
@@ -474,6 +518,8 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
474
518
|
: Math.min(remaining, profile.execution.attemptTimeoutMs ?? 60_000, options.execution?.attemptTimeoutMs ?? Infinity);
|
|
475
519
|
let providerRequestStarted = false;
|
|
476
520
|
let response;
|
|
521
|
+
let providerReportedModelId;
|
|
522
|
+
let reportedIdentityCaptured = false;
|
|
477
523
|
let streamStarted = false, streamResponseId;
|
|
478
524
|
try {
|
|
479
525
|
const adapter = deps.registry.get(plan.model.adapterId);
|
|
@@ -553,6 +599,7 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
553
599
|
reserveBudget();
|
|
554
600
|
providerRequestStarted = true;
|
|
555
601
|
const adapterRequest = {
|
|
602
|
+
...(imageRequest ? { imageRequest: imageRequest } : {}),
|
|
556
603
|
model: plan.model,
|
|
557
604
|
systemInstructions: effectiveInstructions,
|
|
558
605
|
input: plan.input,
|
|
@@ -613,7 +660,8 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
613
660
|
}
|
|
614
661
|
}
|
|
615
662
|
else
|
|
616
|
-
result = await adapter.
|
|
663
|
+
result = imageRequest ? await adapter.executeImage(adapterRequest, guardedFetch)
|
|
664
|
+
: await adapter.execute(adapterRequest, guardedFetch);
|
|
617
665
|
assertDispatchAllowed();
|
|
618
666
|
return result;
|
|
619
667
|
}, admittedTimeout, () => new ProviderCallError("provider-timeout", "Attempt deadline exceeded", true), queueSignal);
|
|
@@ -638,7 +686,11 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
638
686
|
throw new CancellationError();
|
|
639
687
|
if (clock() >= deadlineAt)
|
|
640
688
|
throw deadlineError();
|
|
689
|
+
providerReportedModelId = reportedModelId(response);
|
|
690
|
+
reportedIdentityCaptured = true;
|
|
641
691
|
response = validateAdapterResponse(response);
|
|
692
|
+
if (imageRequest && !response.images?.length || !imageRequest && response.images)
|
|
693
|
+
throw new InvalidOutputError("Adapter output does not match the requested operation.");
|
|
642
694
|
response.usage = mergeReportedUsage(response.generation?.usage, response.usage);
|
|
643
695
|
let generation;
|
|
644
696
|
if (invocation) {
|
|
@@ -698,7 +750,7 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
698
750
|
if (options.signal?.aborted)
|
|
699
751
|
throw new CancellationError();
|
|
700
752
|
}
|
|
701
|
-
const cost = response.usage ? measuredCost(response.usage, response.generation)
|
|
753
|
+
const cost = imageRequest ? { ...evidence.preflightCost } : response.usage ? measuredCost(response.usage, response.generation)
|
|
702
754
|
: toCostEstimate(applyReportedCostContext(evidence.preflightCost, response.generation?.costContext), "preflight-estimate");
|
|
703
755
|
// Search is not uniformly metered across providers; token costs alone are not the total.
|
|
704
756
|
if (effectiveSearch) {
|
|
@@ -719,6 +771,8 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
719
771
|
role: plan.role,
|
|
720
772
|
latencyMs: elapsedSince(attemptStartedAt),
|
|
721
773
|
outcome: "succeeded",
|
|
774
|
+
...(providerReportedModelId ? { providerReportedModelId } : {}),
|
|
775
|
+
...(response.images ? { imageOutput: imageOutputEvidence(response.images) } : {}),
|
|
722
776
|
providerRequestStarted,
|
|
723
777
|
effective: effectiveControls(executionConfiguration(token), evidence),
|
|
724
778
|
usage: response.usage,
|
|
@@ -745,16 +799,23 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
745
799
|
startedAt
|
|
746
800
|
}));
|
|
747
801
|
return {
|
|
802
|
+
...(response.images ? { images: response.images } : {}),
|
|
748
803
|
output: validateStructured ? { kind: "structured", value } : { kind: "text", text: generation?.text ??
|
|
749
804
|
(response.output.kind === "structured" ? JSON.stringify(response.output.value) : response.output.kind === "text" ? response.output.text : "") },
|
|
750
805
|
executionReceipt: receipt, ...(generation ? { generation, requestId, providerModelId: plan.model.providerModelId } : {})
|
|
751
806
|
};
|
|
752
807
|
}
|
|
753
808
|
catch (error) {
|
|
754
|
-
|
|
809
|
+
let aiError = error instanceof AISubsystemError ? error : new AISubsystemError("network-error", "Provider adapter failed unexpectedly", true);
|
|
810
|
+
// The total deadline wins if an inner provider/attempt timer settles at the same boundary.
|
|
811
|
+
// Otherwise the bridge can mistake whole-call exhaustion for a retryable per-attempt timeout.
|
|
812
|
+
if (!options.signal?.aborted && clock() >= deadlineAt)
|
|
813
|
+
aiError = attachProviderErrorContext(deadlineError(), aiError);
|
|
755
814
|
if (!response && aiError.partialResult)
|
|
756
815
|
response = { output: { kind: "text", text: aiError.partialResult.text },
|
|
757
816
|
generation: aiError.partialResult, usage: aiError.partialResult.usage };
|
|
817
|
+
if (!reportedIdentityCaptured)
|
|
818
|
+
providerReportedModelId = reportedModelId(response);
|
|
758
819
|
if (response?.usage !== undefined) {
|
|
759
820
|
try {
|
|
760
821
|
response.usage = validateUsage(response.usage);
|
|
@@ -802,11 +863,12 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
802
863
|
role: plan.role,
|
|
803
864
|
latencyMs: elapsedSince(attemptStartedAt),
|
|
804
865
|
outcome: "cancelled",
|
|
866
|
+
...(providerReportedModelId ? { providerReportedModelId } : {}),
|
|
805
867
|
providerRequestStarted,
|
|
806
868
|
effective: effectiveControls(executionConfiguration(token), evidence),
|
|
807
869
|
errorClass: "cancelled",
|
|
808
870
|
usage: response?.usage,
|
|
809
|
-
costEstimate: response?.usage ? measuredCost(response.usage, response.generation)
|
|
871
|
+
costEstimate: imageRequest ? { ...evidence.preflightCost } : response?.usage ? measuredCost(response.usage, response.generation)
|
|
810
872
|
: toCostEstimate(applyReportedCostContext(evidence.preflightCost, response?.generation?.costContext), "preflight-estimate")
|
|
811
873
|
});
|
|
812
874
|
throw attachProviderErrorContext(new CancellationError(), aiError);
|
|
@@ -835,12 +897,13 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
|
835
897
|
role: plan.role,
|
|
836
898
|
latencyMs: elapsedSince(attemptStartedAt),
|
|
837
899
|
outcome: "failed",
|
|
900
|
+
...(providerReportedModelId ? { providerReportedModelId } : {}),
|
|
838
901
|
providerRequestStarted,
|
|
839
902
|
effective: effectiveControls(executionConfiguration(token), evidence),
|
|
840
903
|
errorClass: aiError.code,
|
|
841
904
|
errorMessage: receiptErrorMessage(aiError),
|
|
842
905
|
usage: response?.usage,
|
|
843
|
-
costEstimate: response?.usage ? measuredCost(response.usage, response.generation)
|
|
906
|
+
costEstimate: imageRequest ? { ...evidence.preflightCost } : response?.usage ? measuredCost(response.usage, response.generation)
|
|
844
907
|
: toCostEstimate(applyReportedCostContext(evidence.preflightCost, response?.generation?.costContext), "preflight-estimate")
|
|
845
908
|
});
|
|
846
909
|
if (!eligible || invocation?.stream?.context.outputExposed)
|
|
@@ -939,6 +1002,10 @@ function validateInvocationControls(options) {
|
|
|
939
1002
|
}
|
|
940
1003
|
}
|
|
941
1004
|
}
|
|
1005
|
+
function reportedModelId(response) {
|
|
1006
|
+
const value = response?.providerReportedModelId ?? response?.generation?.providerModelId;
|
|
1007
|
+
return typeof value === "string" && value.length > 0 && value.length <= 256 && /^[A-Za-z0-9_.:/@+-]+$/.test(value) ? value : undefined;
|
|
1008
|
+
}
|
|
942
1009
|
function validateGenerateInput(input) {
|
|
943
1010
|
if (typeof input === "string")
|
|
944
1011
|
return;
|