@accelerate/ai 0.1.0 → 0.4.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 +2 -0
- package/dist/modules/agents-core/dist/durable.d.ts +41 -0
- package/dist/modules/agents-core/dist/durable.js +149 -0
- package/dist/modules/ai-core/dist/index.d.ts +8 -0
- package/dist/modules/ai-gateway/dist/index.d.ts +1 -0
- package/dist/modules/ai-gateway/dist/index.js +29 -10
- package/dist/modules/ai-structured/dist/generate.d.ts +37 -0
- package/dist/modules/ai-structured/dist/generate.js +92 -0
- package/dist/modules/ai-structured/dist/index.d.ts +1 -0
- package/dist/modules/ai-structured/dist/index.js +1 -0
- package/dist/modules/ai-tools/dist/index.d.ts +6 -2
- package/dist/modules/ai-tools/dist/index.js +19 -6
- package/dist/modules/ai-usage/dist/budgets.d.ts +44 -0
- package/dist/modules/ai-usage/dist/budgets.js +64 -0
- package/dist/modules/ai-usage/dist/postgres.d.ts +30 -0
- package/dist/modules/ai-usage/dist/postgres.js +118 -0
- package/package.json +17 -3
package/README.md
CHANGED
|
@@ -4,6 +4,8 @@ Model gateways, prompts, structured output, agents and evaluation.
|
|
|
4
4
|
|
|
5
5
|
Install with `npm install @accelerate/ai`. See the [Accelerate SDK catalog](https://www.npmjs.com/package/@accelerate/sdk) for the other packages.
|
|
6
6
|
|
|
7
|
+
See [persistent AI usage and budget enforcement](https://github.com/archubbuck/accelerate/blob/main/docs/ai-budgets.md) for guarded gateway and agent calls. See [structured generation and recovery](https://github.com/archubbuck/accelerate/blob/main/docs/structured-output.md) for schema-constrained output. See [durable agent execution](https://github.com/archubbuck/accelerate/blob/main/docs/durable-agents.md) for checkpointed model and tool activities.
|
|
8
|
+
|
|
7
9
|
## Import migration
|
|
8
10
|
|
|
9
11
|
Use the subpaths below. Update related imports together wherever your app shares class or provider identity.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Message, ModelProvider, ToolCall } from "../../ai-core/dist/index.js";
|
|
2
|
+
import type { ToolRegistry } from "../../ai-tools/dist/index.js";
|
|
3
|
+
import { type ActivityContext, type WorkflowStore } from "@accelerate/messaging/workflows";
|
|
4
|
+
interface AgentVersions {
|
|
5
|
+
model: string;
|
|
6
|
+
prompt: string;
|
|
7
|
+
tools: string;
|
|
8
|
+
}
|
|
9
|
+
export interface DurableAgentOptions {
|
|
10
|
+
name: string;
|
|
11
|
+
version: number;
|
|
12
|
+
model: string;
|
|
13
|
+
versions: AgentVersions;
|
|
14
|
+
tools: ToolRegistry;
|
|
15
|
+
/** Return a budgeted provider for this durable activity, with stable attempt identity if supported. */
|
|
16
|
+
provider: (context: ActivityContext) => ModelProvider;
|
|
17
|
+
authorizeTool: (call: ToolCall, activity: ActivityContext) => boolean | Promise<boolean>;
|
|
18
|
+
requiresApproval?: (call: ToolCall, activity: ActivityContext) => boolean | Promise<boolean>;
|
|
19
|
+
authorizeApproval?: (input: {
|
|
20
|
+
actorId: string;
|
|
21
|
+
instanceId: string;
|
|
22
|
+
path: string;
|
|
23
|
+
accepted: boolean;
|
|
24
|
+
}) => boolean | Promise<boolean>;
|
|
25
|
+
maxSteps?: number;
|
|
26
|
+
maxCallsPerStep?: number;
|
|
27
|
+
maxContextChars?: number;
|
|
28
|
+
maxToolOutputChars?: number;
|
|
29
|
+
timeoutMs?: number;
|
|
30
|
+
}
|
|
31
|
+
export declare function createDurableAgent(store: WorkflowStore, options: DurableAgentOptions): {
|
|
32
|
+
start(id: string, messages: readonly Message[]): Promise<string>;
|
|
33
|
+
tick(id: string): Promise<boolean>;
|
|
34
|
+
cancel(id: string): Promise<boolean>;
|
|
35
|
+
inspect: (id: string) => Promise<import("@accelerate/messaging/workflows").Instance | undefined>;
|
|
36
|
+
history(id: string, after?: number, limit?: number): Promise<(import("@accelerate/messaging/workflows").WorkflowEvent & {
|
|
37
|
+
cursor: number;
|
|
38
|
+
})[]>;
|
|
39
|
+
approve(actorId: string, id: string, path: string, accepted: boolean): Promise<boolean>;
|
|
40
|
+
};
|
|
41
|
+
export {};
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { checkId, count, DurableWorkflowRunner, snapshot, } from "@accelerate/messaging/workflows";
|
|
2
|
+
function pack(state) {
|
|
3
|
+
// A persisted checkpoint contains only JSON values created by trusted handlers.
|
|
4
|
+
return snapshot(state);
|
|
5
|
+
}
|
|
6
|
+
function asState(input) {
|
|
7
|
+
return snapshot(input);
|
|
8
|
+
}
|
|
9
|
+
export function createDurableAgent(store, options) {
|
|
10
|
+
checkId(options.name);
|
|
11
|
+
count(options.version, 1);
|
|
12
|
+
const maxSteps = options.maxSteps ?? 8;
|
|
13
|
+
const maxCalls = options.maxCallsPerStep ?? 4;
|
|
14
|
+
const maxContext = options.maxContextChars ?? 128 * 1024;
|
|
15
|
+
const maxToolOutput = options.maxToolOutputChars ?? 32 * 1024;
|
|
16
|
+
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
17
|
+
count(maxSteps, 1, 24);
|
|
18
|
+
count(maxCalls, 0, 8);
|
|
19
|
+
count(maxContext, 1, 1024 * 1024);
|
|
20
|
+
count(maxToolOutput, 1, maxContext);
|
|
21
|
+
count(timeoutMs, 1);
|
|
22
|
+
if (!options.model.trim() || Object.values(options.versions).some(value => typeof value !== "string" || !value.trim())) {
|
|
23
|
+
throw new TypeError("A durable agent must pin model, prompt and tool versions");
|
|
24
|
+
}
|
|
25
|
+
const versions = { ...options.versions };
|
|
26
|
+
const modelHandler = "generate-v" + options.version;
|
|
27
|
+
const toolHandler = "tool-v" + options.version;
|
|
28
|
+
const stages = [];
|
|
29
|
+
for (let step = 1; step <= maxSteps; step++) {
|
|
30
|
+
stages.push({ id: "generate-" + step, kind: "task", handler: modelHandler, when: { field: "complete", equals: false }, timeoutMs });
|
|
31
|
+
if (maxCalls) {
|
|
32
|
+
stages.push({ id: "approve-" + step, kind: "approval", when: { field: "needsApproval", equals: true } });
|
|
33
|
+
for (let slot = 1; slot <= maxCalls; slot++) {
|
|
34
|
+
stages.push({ id: "tool-" + step + "-" + slot, kind: "task", handler: toolHandler, when: { field: "hasTools", equals: true }, timeoutMs });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function contextWithinLimit(messages) {
|
|
39
|
+
if (JSON.stringify(messages).length > maxContext)
|
|
40
|
+
throw new RangeError("Durable agent context exceeded its limit");
|
|
41
|
+
}
|
|
42
|
+
const generate = async (input, activity) => {
|
|
43
|
+
const state = asState(input);
|
|
44
|
+
if (state.pending.length)
|
|
45
|
+
throw new Error("Tool calls must finish before generating again");
|
|
46
|
+
const request = {
|
|
47
|
+
model: state.model, messages: state.messages, signal: activity.signal,
|
|
48
|
+
...(maxCalls ? { tools: options.tools.definitions() } : {}),
|
|
49
|
+
};
|
|
50
|
+
const response = await options.provider(activity).generate(request);
|
|
51
|
+
activity.signal.throwIfAborted();
|
|
52
|
+
if (typeof response.content !== "string" || response.content.length > maxContext)
|
|
53
|
+
throw new Error("Invalid model response");
|
|
54
|
+
if (response.usage && ![response.usage.inputTokens, response.usage.outputTokens]
|
|
55
|
+
.every(value => Number.isSafeInteger(value) && value >= 0))
|
|
56
|
+
throw new Error("Invalid model usage");
|
|
57
|
+
const calls = (response.toolCalls ?? []).map(call => ({
|
|
58
|
+
id: call.id, name: call.name, arguments: snapshot(call.arguments),
|
|
59
|
+
}));
|
|
60
|
+
if (calls.length > maxCalls || (calls.length && state.steps + 1 === maxSteps))
|
|
61
|
+
throw new Error("Durable agent tool limit reached");
|
|
62
|
+
const seen = new Set(state.seen);
|
|
63
|
+
let needsApproval = false;
|
|
64
|
+
for (const call of calls) {
|
|
65
|
+
checkId(call.id);
|
|
66
|
+
if (!call.name || seen.has(call.id) || !await options.authorizeTool(call, activity))
|
|
67
|
+
throw new Error("Agent tool call denied");
|
|
68
|
+
seen.add(call.id);
|
|
69
|
+
if (await options.requiresApproval?.(call, activity))
|
|
70
|
+
needsApproval = true;
|
|
71
|
+
}
|
|
72
|
+
const nextUsage = {
|
|
73
|
+
inputTokens: state.usage.inputTokens + (response.usage?.inputTokens ?? 0),
|
|
74
|
+
outputTokens: state.usage.outputTokens + (response.usage?.outputTokens ?? 0),
|
|
75
|
+
};
|
|
76
|
+
if (!Object.values(nextUsage).every(value => Number.isSafeInteger(value) && value >= 0))
|
|
77
|
+
throw new Error("Invalid model usage");
|
|
78
|
+
const messages = [...state.messages, {
|
|
79
|
+
role: "assistant", content: response.content, ...(calls.length ? { toolCalls: calls } : {}),
|
|
80
|
+
}];
|
|
81
|
+
contextWithinLimit(messages);
|
|
82
|
+
return pack({
|
|
83
|
+
...state, messages, pending: calls, seen: [...seen], usage: nextUsage,
|
|
84
|
+
steps: state.steps + 1, complete: !calls.length, hasTools: !!calls.length, needsApproval,
|
|
85
|
+
});
|
|
86
|
+
};
|
|
87
|
+
const tool = async (input, activity) => {
|
|
88
|
+
const state = asState(input);
|
|
89
|
+
const [call, ...remaining] = state.pending;
|
|
90
|
+
if (!call)
|
|
91
|
+
throw new Error("Missing checkpointed tool call");
|
|
92
|
+
const output = await options.tools.execute(call, candidate => options.authorizeTool(candidate, activity), activity.signal, {
|
|
93
|
+
idempotencyKey: activity.idempotencyKey,
|
|
94
|
+
instanceId: activity.instanceId,
|
|
95
|
+
});
|
|
96
|
+
const content = JSON.stringify(output) ?? "null";
|
|
97
|
+
if (content.length > maxToolOutput)
|
|
98
|
+
throw new RangeError("Durable agent tool output exceeded its limit");
|
|
99
|
+
const messages = [...state.messages, { role: "tool", content, toolCallId: call.id }];
|
|
100
|
+
contextWithinLimit(messages);
|
|
101
|
+
return pack({ ...state, messages, pending: remaining, hasTools: !!remaining.length, needsApproval: false, toolCalls: state.toolCalls + 1 });
|
|
102
|
+
};
|
|
103
|
+
const runner = new DurableWorkflowRunner(store, [{ name: options.name, version: options.version, stages }], { [modelHandler]: generate, [toolHandler]: tool });
|
|
104
|
+
async function inspect(id) {
|
|
105
|
+
const instance = await runner.inspect(id);
|
|
106
|
+
if (!instance || instance.plan.name !== options.name || instance.plan.version !== options.version)
|
|
107
|
+
return undefined;
|
|
108
|
+
const state = asState(instance.input);
|
|
109
|
+
if (state.model !== options.model || Object.keys(versions).some(key => {
|
|
110
|
+
const dimension = key;
|
|
111
|
+
return state.versions[dimension] !== versions[dimension];
|
|
112
|
+
})) {
|
|
113
|
+
throw new Error("Agent worker configuration does not match the pinned versions");
|
|
114
|
+
}
|
|
115
|
+
return instance;
|
|
116
|
+
}
|
|
117
|
+
async function owned(id) {
|
|
118
|
+
if (!await inspect(id))
|
|
119
|
+
throw new Error("Unknown durable agent instance");
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
start(id, messages) {
|
|
123
|
+
if (messages.some(message => !["system", "user"].includes(message.role) || typeof message.content !== "string")) {
|
|
124
|
+
throw new TypeError("Durable agent input must contain only application system and user messages");
|
|
125
|
+
}
|
|
126
|
+
const initial = messages.map(message => ({ role: message.role, content: message.content }));
|
|
127
|
+
contextWithinLimit(initial);
|
|
128
|
+
return runner.start(id, options.name, options.version, pack({
|
|
129
|
+
model: options.model, messages: initial, versions, pending: [], seen: [],
|
|
130
|
+
usage: { inputTokens: 0, outputTokens: 0 }, toolCalls: 0,
|
|
131
|
+
steps: 0, complete: false, hasTools: false, needsApproval: false,
|
|
132
|
+
}));
|
|
133
|
+
},
|
|
134
|
+
async tick(id) { await owned(id); return runner.tick(id); },
|
|
135
|
+
async cancel(id) { await owned(id); return runner.cancel(id); },
|
|
136
|
+
inspect,
|
|
137
|
+
async history(id, after, limit) {
|
|
138
|
+
await owned(id);
|
|
139
|
+
return runner.history(id, after, limit);
|
|
140
|
+
},
|
|
141
|
+
async approve(actorId, id, path, accepted) {
|
|
142
|
+
if (!actorId || !await options.authorizeApproval?.({ actorId, instanceId: id, path, accepted })) {
|
|
143
|
+
throw new Error("Agent approval denied");
|
|
144
|
+
}
|
|
145
|
+
await owned(id);
|
|
146
|
+
return runner.approve(id, path, accepted);
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
|
@@ -24,20 +24,28 @@ export interface ToolDefinition {
|
|
|
24
24
|
readonly description: string;
|
|
25
25
|
readonly inputSchema: Readonly<Record<string, unknown>>;
|
|
26
26
|
}
|
|
27
|
+
export interface NativeStructuredOutput {
|
|
28
|
+
readonly schemaId: string;
|
|
29
|
+
readonly schemaVersion: string;
|
|
30
|
+
readonly jsonSchema: Readonly<Record<string, unknown>>;
|
|
31
|
+
}
|
|
27
32
|
export interface ModelRequest {
|
|
28
33
|
readonly model: string;
|
|
29
34
|
readonly messages: readonly Message[];
|
|
30
35
|
readonly tools?: readonly ToolDefinition[];
|
|
31
36
|
readonly signal?: AbortSignal;
|
|
32
37
|
readonly maxOutputTokens?: number;
|
|
38
|
+
readonly structuredOutput?: NativeStructuredOutput;
|
|
33
39
|
}
|
|
34
40
|
export interface ModelResponse {
|
|
35
41
|
readonly content: string;
|
|
36
42
|
readonly toolCalls?: readonly ToolCall[];
|
|
37
43
|
readonly usage?: Usage;
|
|
44
|
+
readonly structuredOutputMode?: "native" | "prompt";
|
|
38
45
|
}
|
|
39
46
|
export interface ModelProvider {
|
|
40
47
|
generate(request: ModelRequest): Promise<ModelResponse>;
|
|
48
|
+
supportsStructuredOutput?(model: string): boolean | Promise<boolean>;
|
|
41
49
|
}
|
|
42
50
|
export declare class ModelError extends Error {
|
|
43
51
|
readonly retryable: boolean;
|
|
@@ -6,5 +6,6 @@ export interface Route {
|
|
|
6
6
|
export declare class ModelGateway implements ModelProvider {
|
|
7
7
|
private readonly routes;
|
|
8
8
|
constructor(routes: ReadonlyMap<string, readonly Route[]>);
|
|
9
|
+
supportsStructuredOutput(model: string): Promise<boolean>;
|
|
9
10
|
generate(request: ModelRequest): Promise<ModelResponse>;
|
|
10
11
|
}
|
|
@@ -3,17 +3,36 @@ export class ModelGateway {
|
|
|
3
3
|
constructor(routes) {
|
|
4
4
|
this.routes = routes;
|
|
5
5
|
}
|
|
6
|
-
async
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
try {
|
|
11
|
-
return await route.provider.generate({ ...request, model: route.model });
|
|
6
|
+
async supportsStructuredOutput(model) {
|
|
7
|
+
for (const route of this.routes.get(model) ?? []) {
|
|
8
|
+
if (await route.provider.supportsStructuredOutput?.(route.model))
|
|
9
|
+
return true;
|
|
12
10
|
}
|
|
13
|
-
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
async generate(request) {
|
|
14
|
+
const routes = this.routes.get(request.model);
|
|
15
|
+
if (!routes?.length)
|
|
16
|
+
throw new ModelError("Unknown model route");
|
|
17
|
+
for (let index = 0; index < routes.length; index++) {
|
|
14
18
|
request.signal?.throwIfAborted();
|
|
15
|
-
|
|
16
|
-
|
|
19
|
+
const route = routes[index];
|
|
20
|
+
try {
|
|
21
|
+
if (!request.structuredOutput)
|
|
22
|
+
return await route.provider.generate({ ...request, model: route.model });
|
|
23
|
+
const native = await route.provider.supportsStructuredOutput?.(route.model);
|
|
24
|
+
const { structuredOutput, ...fallback } = request;
|
|
25
|
+
const response = await route.provider.generate({
|
|
26
|
+
...fallback, model: route.model, ...(native ? { structuredOutput } : {}),
|
|
27
|
+
});
|
|
28
|
+
return { ...response, structuredOutputMode: response.structuredOutputMode ?? (native ? "native" : "prompt") };
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
request.signal?.throwIfAborted();
|
|
32
|
+
if (!(error instanceof ModelError && error.retryable) || index === routes.length - 1)
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
17
35
|
}
|
|
18
|
-
|
|
36
|
+
throw new ModelError("No route available");
|
|
37
|
+
}
|
|
19
38
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { ModelProvider, ModelRequest, ModelResponse, NativeStructuredOutput, Usage } from "../../ai-core/dist/index.js";
|
|
2
|
+
import type { Schema, ValidationIssue } from "@accelerate/core/validation";
|
|
3
|
+
type Failure = "INVALID_JSON" | "SCHEMA_MISMATCH" | "OUTPUT_TOO_LARGE" | "UNEXPECTED_TOOL_CALL";
|
|
4
|
+
export interface StructuredAttempt {
|
|
5
|
+
content?: string;
|
|
6
|
+
mode: "native" | "prompt";
|
|
7
|
+
usage?: Usage;
|
|
8
|
+
costMicros?: bigint;
|
|
9
|
+
failure?: Failure;
|
|
10
|
+
}
|
|
11
|
+
export declare class StructuredOutputError extends Error {
|
|
12
|
+
#private;
|
|
13
|
+
readonly code: Failure;
|
|
14
|
+
readonly schemaVersion: string;
|
|
15
|
+
constructor(code: Failure, schemaVersion: string, attempts: readonly StructuredAttempt[]);
|
|
16
|
+
get attempts(): readonly StructuredAttempt[];
|
|
17
|
+
}
|
|
18
|
+
export declare function generateStructured<T>(provider: ModelProvider, request: ModelRequest, options: {
|
|
19
|
+
schema: Schema<T>;
|
|
20
|
+
output: NativeStructuredOutput;
|
|
21
|
+
maxRepairs?: number;
|
|
22
|
+
maxOutputChars?: number;
|
|
23
|
+
repairFeedback?: (failure: Failure, issues: readonly ValidationIssue[]) => string | undefined;
|
|
24
|
+
estimateCostMicros?: (usage: Usage, response: ModelResponse) => bigint;
|
|
25
|
+
}): Promise<{
|
|
26
|
+
estimatedCostMicros?: bigint | undefined;
|
|
27
|
+
data: T;
|
|
28
|
+
schemaId: string;
|
|
29
|
+
schemaVersion: string;
|
|
30
|
+
attempts: StructuredAttempt[];
|
|
31
|
+
usage: {
|
|
32
|
+
inputTokens: number;
|
|
33
|
+
outputTokens: number;
|
|
34
|
+
};
|
|
35
|
+
attemptsWithoutUsage: number;
|
|
36
|
+
}>;
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
export class StructuredOutputError extends Error {
|
|
2
|
+
#attempts;
|
|
3
|
+
constructor(code, schemaVersion, attempts) {
|
|
4
|
+
super("Model output did not match the requested structure");
|
|
5
|
+
this.code = code;
|
|
6
|
+
this.schemaVersion = schemaVersion;
|
|
7
|
+
this.name = "StructuredOutputError";
|
|
8
|
+
this.#attempts = attempts;
|
|
9
|
+
}
|
|
10
|
+
get attempts() { return this.#attempts; }
|
|
11
|
+
}
|
|
12
|
+
function parseAttempt(response, schema, maxChars) {
|
|
13
|
+
if (response.toolCalls?.length)
|
|
14
|
+
return { ok: false, failure: "UNEXPECTED_TOOL_CALL" };
|
|
15
|
+
if (response.content.length > maxChars)
|
|
16
|
+
return { ok: false, failure: "OUTPUT_TOO_LARGE" };
|
|
17
|
+
let input;
|
|
18
|
+
try {
|
|
19
|
+
input = JSON.parse(response.content);
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return { ok: false, failure: "INVALID_JSON" };
|
|
23
|
+
}
|
|
24
|
+
const result = schema.safeParse(input);
|
|
25
|
+
return result.success ? { ok: true, data: result.data } : { ok: false, failure: "SCHEMA_MISMATCH", issues: result.issues };
|
|
26
|
+
}
|
|
27
|
+
function safeFeedback(failure, issues = []) {
|
|
28
|
+
const paths = issues.slice(0, 12).map(issue => issue.path.slice(0, 16).map(segment => typeof segment === "number" || /^[A-Za-z0-9_-]{1,48}$/.test(segment) ? segment : "?"));
|
|
29
|
+
return "Return only valid JSON matching the schema. Correct the previous error: " + JSON.stringify({ failure, paths });
|
|
30
|
+
}
|
|
31
|
+
export async function generateStructured(provider, request, options) {
|
|
32
|
+
const { output, schema } = options;
|
|
33
|
+
const maxRepairs = options.maxRepairs ?? 1;
|
|
34
|
+
const maxOutputChars = options.maxOutputChars ?? 64 * 1024;
|
|
35
|
+
if (!Number.isSafeInteger(maxRepairs) || maxRepairs < 0 || maxRepairs > 5
|
|
36
|
+
|| !Number.isSafeInteger(maxOutputChars) || maxOutputChars < 1
|
|
37
|
+
|| !output.schemaId.trim() || !output.schemaVersion.trim())
|
|
38
|
+
throw new RangeError("Invalid structured generation options");
|
|
39
|
+
const json = JSON.stringify(output.jsonSchema);
|
|
40
|
+
if (!json || json.length > 64 * 1024)
|
|
41
|
+
throw new RangeError("Invalid structured output JSON Schema");
|
|
42
|
+
const format = { ...output, jsonSchema: JSON.parse(json) };
|
|
43
|
+
const messages = [
|
|
44
|
+
{ role: "system", content: "Return JSON and no other text. Use this JSON Schema: " + json },
|
|
45
|
+
...request.messages,
|
|
46
|
+
];
|
|
47
|
+
const { tools: omittedTools, structuredOutput: omittedFormat, ...base } = request;
|
|
48
|
+
request.signal?.throwIfAborted();
|
|
49
|
+
const native = await provider.supportsStructuredOutput?.(request.model);
|
|
50
|
+
const attempts = [];
|
|
51
|
+
let failure = "INVALID_JSON";
|
|
52
|
+
let inputTokens = 0, outputTokens = 0, estimatedCostMicros = 0n, attemptsWithoutUsage = 0;
|
|
53
|
+
for (let index = 0; index <= maxRepairs; index++) {
|
|
54
|
+
request.signal?.throwIfAborted();
|
|
55
|
+
const response = await provider.generate({ ...base, messages: [...messages], ...(native ? { structuredOutput: format } : {}) });
|
|
56
|
+
request.signal?.throwIfAborted();
|
|
57
|
+
const parsed = parseAttempt(response, schema, maxOutputChars);
|
|
58
|
+
const usage = response.usage;
|
|
59
|
+
if (usage) {
|
|
60
|
+
inputTokens += usage.inputTokens;
|
|
61
|
+
outputTokens += usage.outputTokens;
|
|
62
|
+
}
|
|
63
|
+
else
|
|
64
|
+
attemptsWithoutUsage++;
|
|
65
|
+
const costMicros = usage && options.estimateCostMicros?.(usage, response);
|
|
66
|
+
estimatedCostMicros += costMicros ?? 0n;
|
|
67
|
+
const content = response.content.length <= maxOutputChars ? response.content : undefined;
|
|
68
|
+
attempts.push({
|
|
69
|
+
content, mode: response.structuredOutputMode ?? (native ? "native" : "prompt"),
|
|
70
|
+
usage, costMicros, ...(parsed.ok ? {} : { failure: parsed.failure }),
|
|
71
|
+
});
|
|
72
|
+
if (parsed.ok) {
|
|
73
|
+
return {
|
|
74
|
+
data: parsed.data, schemaId: output.schemaId, schemaVersion: output.schemaVersion,
|
|
75
|
+
attempts, usage: { inputTokens, outputTokens }, attemptsWithoutUsage,
|
|
76
|
+
...(options.estimateCostMicros ? { estimatedCostMicros } : {}),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
failure = parsed.failure;
|
|
80
|
+
if (index >= maxRepairs)
|
|
81
|
+
break;
|
|
82
|
+
const feedback = options.repairFeedback
|
|
83
|
+
? options.repairFeedback(failure, parsed.issues ?? [])
|
|
84
|
+
: safeFeedback(failure, parsed.issues);
|
|
85
|
+
if (!feedback)
|
|
86
|
+
break;
|
|
87
|
+
if (content && failure !== "UNEXPECTED_TOOL_CALL")
|
|
88
|
+
messages.push({ role: "assistant", content });
|
|
89
|
+
messages.push({ role: "user", content: feedback });
|
|
90
|
+
}
|
|
91
|
+
throw new StructuredOutputError(failure, output.schemaVersion, attempts);
|
|
92
|
+
}
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import type { ToolCall, ToolDefinition } from "../../ai-core/dist/index.js";
|
|
2
|
+
export interface DurableToolContext {
|
|
3
|
+
readonly idempotencyKey: string;
|
|
4
|
+
readonly instanceId: string;
|
|
5
|
+
}
|
|
2
6
|
export interface RegisteredTool {
|
|
3
7
|
readonly definition: ToolDefinition;
|
|
4
8
|
validate(input: unknown): unknown;
|
|
5
|
-
execute(input: unknown, signal?: AbortSignal): Promise<unknown>;
|
|
9
|
+
execute(input: unknown, signal?: AbortSignal, durable?: DurableToolContext): Promise<unknown>;
|
|
6
10
|
}
|
|
7
11
|
export type ToolAuthorization = (call: ToolCall) => boolean | Promise<boolean>;
|
|
8
12
|
export declare class ToolRegistry {
|
|
9
13
|
private readonly tools;
|
|
10
14
|
register(tool: RegisteredTool): void;
|
|
11
15
|
definitions(): readonly ToolDefinition[];
|
|
12
|
-
execute(call: ToolCall, authorize: ToolAuthorization, signal?: AbortSignal): Promise<unknown>;
|
|
16
|
+
execute(call: ToolCall, authorize: ToolAuthorization, signal?: AbortSignal, durable?: DurableToolContext): Promise<unknown>;
|
|
13
17
|
}
|
|
@@ -2,10 +2,23 @@ export class ToolRegistry {
|
|
|
2
2
|
constructor() {
|
|
3
3
|
this.tools = new Map();
|
|
4
4
|
}
|
|
5
|
-
register(tool) {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
5
|
+
register(tool) {
|
|
6
|
+
if (!tool.definition.name || this.tools.has(tool.definition.name))
|
|
7
|
+
throw new Error("Invalid or duplicate tool");
|
|
8
|
+
this.tools.set(tool.definition.name, tool);
|
|
9
|
+
}
|
|
10
|
+
definitions() {
|
|
11
|
+
return [...this.tools.values()].map(tool => tool.definition);
|
|
12
|
+
}
|
|
13
|
+
async execute(call, authorize, signal, durable) {
|
|
14
|
+
signal?.throwIfAborted();
|
|
15
|
+
const tool = this.tools.get(call.name);
|
|
16
|
+
if (!tool)
|
|
17
|
+
throw new Error("Unknown tool");
|
|
18
|
+
if (!await authorize(call))
|
|
19
|
+
throw new Error("Tool execution denied");
|
|
20
|
+
signal?.throwIfAborted();
|
|
21
|
+
const args = tool.validate(call.arguments);
|
|
22
|
+
return durable ? tool.execute(args, signal, durable) : tool.execute(args, signal);
|
|
23
|
+
}
|
|
11
24
|
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { ModelProvider, ModelRequest, Usage } from "../../ai-core/dist/index.js";
|
|
2
|
+
export interface VersionedPrice {
|
|
3
|
+
version: string;
|
|
4
|
+
provider: string;
|
|
5
|
+
model: string;
|
|
6
|
+
inputMicrosPerMillion: bigint;
|
|
7
|
+
outputMicrosPerMillion: bigint;
|
|
8
|
+
}
|
|
9
|
+
export interface BudgetReservation {
|
|
10
|
+
id: string;
|
|
11
|
+
budgetIds: readonly string[];
|
|
12
|
+
estimateMicros: bigint;
|
|
13
|
+
price: VersionedPrice;
|
|
14
|
+
now: Date;
|
|
15
|
+
expiresAt: Date;
|
|
16
|
+
}
|
|
17
|
+
export interface BudgetStore {
|
|
18
|
+
reserve(reservation: BudgetReservation): Promise<"reserved" | "exhausted" | "duplicate">;
|
|
19
|
+
settle(id: string, costMicros: bigint, usage: Usage | undefined, now: Date): Promise<void>;
|
|
20
|
+
markUncertain(id: string, now: Date): Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
export declare class UsageBudgetError extends Error {
|
|
23
|
+
readonly code: "BUDGET_EXHAUSTED" | "DUPLICATE_RESERVATION";
|
|
24
|
+
constructor(code: "BUDGET_EXHAUSTED" | "DUPLICATE_RESERVATION");
|
|
25
|
+
}
|
|
26
|
+
export declare function priceUsage(usage: Usage, price: VersionedPrice): bigint;
|
|
27
|
+
/** Wrap each concrete route separately so fallback attempts have separate reservations. */
|
|
28
|
+
export declare function createBudgetedModelProvider(provider: ModelProvider, options: {
|
|
29
|
+
store: BudgetStore;
|
|
30
|
+
plan: (request: ModelRequest) => {
|
|
31
|
+
id: string;
|
|
32
|
+
budgetIds: readonly string[];
|
|
33
|
+
upperBound: Usage;
|
|
34
|
+
price: VersionedPrice;
|
|
35
|
+
reservationTtlMs: number;
|
|
36
|
+
} | Promise<{
|
|
37
|
+
id: string;
|
|
38
|
+
budgetIds: readonly string[];
|
|
39
|
+
upperBound: Usage;
|
|
40
|
+
price: VersionedPrice;
|
|
41
|
+
reservationTtlMs: number;
|
|
42
|
+
}>;
|
|
43
|
+
now?: () => Date;
|
|
44
|
+
}): ModelProvider;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export class UsageBudgetError extends Error {
|
|
2
|
+
constructor(code) {
|
|
3
|
+
super(code === "BUDGET_EXHAUSTED" ? "Model usage budget exhausted" : "Model usage reservation already exists");
|
|
4
|
+
this.code = code;
|
|
5
|
+
this.name = "UsageBudgetError";
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export function priceUsage(usage, price) {
|
|
9
|
+
if (![usage.inputTokens, usage.outputTokens].every(value => Number.isSafeInteger(value) && value >= 0)
|
|
10
|
+
|| price.inputMicrosPerMillion < 0n || price.outputMicrosPerMillion < 0n) {
|
|
11
|
+
throw new RangeError("Invalid token count or usage price");
|
|
12
|
+
}
|
|
13
|
+
const units = BigInt(usage.inputTokens) * price.inputMicrosPerMillion + BigInt(usage.outputTokens) * price.outputMicrosPerMillion;
|
|
14
|
+
return (units + 999999n) / 1000000n;
|
|
15
|
+
}
|
|
16
|
+
/** Wrap each concrete route separately so fallback attempts have separate reservations. */
|
|
17
|
+
export function createBudgetedModelProvider(provider, options) {
|
|
18
|
+
const now = options.now ?? (() => new Date());
|
|
19
|
+
return {
|
|
20
|
+
supportsStructuredOutput: provider.supportsStructuredOutput?.bind(provider),
|
|
21
|
+
async generate(request) {
|
|
22
|
+
request.signal?.throwIfAborted();
|
|
23
|
+
const plan = await options.plan(request);
|
|
24
|
+
if (!Number.isSafeInteger(plan.reservationTtlMs) || plan.reservationTtlMs <= 0)
|
|
25
|
+
throw new RangeError("Invalid reservation lifetime");
|
|
26
|
+
const started = now();
|
|
27
|
+
const price = { ...plan.price };
|
|
28
|
+
request.signal?.throwIfAborted();
|
|
29
|
+
const result = await options.store.reserve({
|
|
30
|
+
id: plan.id, budgetIds: [...plan.budgetIds], price, estimateMicros: priceUsage(plan.upperBound, price),
|
|
31
|
+
now: started, expiresAt: new Date(started.getTime() + plan.reservationTtlMs),
|
|
32
|
+
});
|
|
33
|
+
if (result !== "reserved")
|
|
34
|
+
throw new UsageBudgetError(result === "duplicate" ? "DUPLICATE_RESERVATION" : "BUDGET_EXHAUSTED");
|
|
35
|
+
if (request.signal?.aborted) {
|
|
36
|
+
await options.store.settle(plan.id, 0n, undefined, now());
|
|
37
|
+
request.signal.throwIfAborted();
|
|
38
|
+
}
|
|
39
|
+
let response;
|
|
40
|
+
try {
|
|
41
|
+
response = await provider.generate(request);
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
// A failed request may have reached the provider and incurred a charge.
|
|
45
|
+
await options.store.markUncertain(plan.id, now());
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
if (!response.usage)
|
|
49
|
+
await options.store.markUncertain(plan.id, now());
|
|
50
|
+
else {
|
|
51
|
+
let actual;
|
|
52
|
+
try {
|
|
53
|
+
actual = priceUsage(response.usage, price);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
await options.store.markUncertain(plan.id, now());
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
await options.store.settle(plan.id, actual, response.usage, now());
|
|
60
|
+
}
|
|
61
|
+
return response;
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Usage } from "../../ai-core/dist/index.js";
|
|
2
|
+
import type { Database } from "@accelerate/data/core";
|
|
3
|
+
import type { BudgetReservation } from "./budgets.js";
|
|
4
|
+
export declare const usageBudgetSchema: readonly ["CREATE TABLE IF NOT EXISTS accelerate_usage_budgets (\n id text PRIMARY KEY, scope text NOT NULL, starts_at timestamptz NOT NULL, ends_at timestamptz NOT NULL,\n limit_micros numeric(30,0) NOT NULL CHECK (limit_micros >= 0),\n held_micros numeric(30,0) NOT NULL DEFAULT 0 CHECK (held_micros >= 0),\n spent_micros numeric(30,0) NOT NULL DEFAULT 0 CHECK (spent_micros >= 0),\n CHECK (ends_at > starts_at), UNIQUE (scope, starts_at, ends_at)\n )", "CREATE TABLE IF NOT EXISTS accelerate_usage_reservations (\n id text PRIMARY KEY, budget_ids text[] NOT NULL,\n estimated_micros numeric(30,0) NOT NULL CHECK (estimated_micros >= 0),\n actual_micros numeric(30,0) CHECK (actual_micros >= 0),\n state text NOT NULL CHECK (state IN ('reserved', 'uncertain', 'settled')),\n provider text NOT NULL, model text NOT NULL, price_version text NOT NULL,\n price_input numeric(30,0) NOT NULL CHECK (price_input >= 0),\n price_output numeric(30,0) NOT NULL CHECK (price_output >= 0),\n started_at timestamptz NOT NULL, expires_at timestamptz NOT NULL, updated_at timestamptz NOT NULL,\n input_tokens bigint, output_tokens bigint\n )", "CREATE INDEX IF NOT EXISTS accelerate_usage_reservations_expiry\n ON accelerate_usage_reservations (expires_at, id) WHERE state IN ('reserved', 'uncertain')"];
|
|
5
|
+
export declare function createPostgresUsageBudgetStore(db: Database): {
|
|
6
|
+
defineBudget(input: {
|
|
7
|
+
id: string;
|
|
8
|
+
scope: string;
|
|
9
|
+
startsAt: Date;
|
|
10
|
+
endsAt: Date;
|
|
11
|
+
limitMicros: bigint;
|
|
12
|
+
}): Promise<void>;
|
|
13
|
+
report(id: string): Promise<{
|
|
14
|
+
id: string;
|
|
15
|
+
limitMicros: bigint;
|
|
16
|
+
heldMicros: bigint;
|
|
17
|
+
spentMicros: bigint;
|
|
18
|
+
availableMicros: bigint;
|
|
19
|
+
} | undefined>;
|
|
20
|
+
listExpired(now: Date, limit?: number): Promise<readonly {
|
|
21
|
+
id: string;
|
|
22
|
+
provider: string;
|
|
23
|
+
model: string;
|
|
24
|
+
price_version: string;
|
|
25
|
+
estimated_micros: string;
|
|
26
|
+
}[]>;
|
|
27
|
+
reserve(reservation: BudgetReservation): Promise<"reserved" | "exhausted" | "duplicate">;
|
|
28
|
+
settle(id: string, costMicros: bigint, usage: Usage | undefined, now: Date): Promise<void>;
|
|
29
|
+
markUncertain(id: string, now: Date): Promise<void>;
|
|
30
|
+
};
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
export const usageBudgetSchema = [
|
|
2
|
+
`CREATE TABLE IF NOT EXISTS accelerate_usage_budgets (
|
|
3
|
+
id text PRIMARY KEY, scope text NOT NULL, starts_at timestamptz NOT NULL, ends_at timestamptz NOT NULL,
|
|
4
|
+
limit_micros numeric(30,0) NOT NULL CHECK (limit_micros >= 0),
|
|
5
|
+
held_micros numeric(30,0) NOT NULL DEFAULT 0 CHECK (held_micros >= 0),
|
|
6
|
+
spent_micros numeric(30,0) NOT NULL DEFAULT 0 CHECK (spent_micros >= 0),
|
|
7
|
+
CHECK (ends_at > starts_at), UNIQUE (scope, starts_at, ends_at)
|
|
8
|
+
)`,
|
|
9
|
+
`CREATE TABLE IF NOT EXISTS accelerate_usage_reservations (
|
|
10
|
+
id text PRIMARY KEY, budget_ids text[] NOT NULL,
|
|
11
|
+
estimated_micros numeric(30,0) NOT NULL CHECK (estimated_micros >= 0),
|
|
12
|
+
actual_micros numeric(30,0) CHECK (actual_micros >= 0),
|
|
13
|
+
state text NOT NULL CHECK (state IN ('reserved', 'uncertain', 'settled')),
|
|
14
|
+
provider text NOT NULL, model text NOT NULL, price_version text NOT NULL,
|
|
15
|
+
price_input numeric(30,0) NOT NULL CHECK (price_input >= 0),
|
|
16
|
+
price_output numeric(30,0) NOT NULL CHECK (price_output >= 0),
|
|
17
|
+
started_at timestamptz NOT NULL, expires_at timestamptz NOT NULL, updated_at timestamptz NOT NULL,
|
|
18
|
+
input_tokens bigint, output_tokens bigint
|
|
19
|
+
)`,
|
|
20
|
+
`CREATE INDEX IF NOT EXISTS accelerate_usage_reservations_expiry
|
|
21
|
+
ON accelerate_usage_reservations (expires_at, id) WHERE state IN ('reserved', 'uncertain')`,
|
|
22
|
+
];
|
|
23
|
+
const maxMoney = 10n ** 30n - 1n;
|
|
24
|
+
const validMoney = (value) => typeof value === "bigint" && value >= 0n && value <= maxMoney;
|
|
25
|
+
const validDate = (value) => value instanceof Date && Number.isFinite(value.getTime());
|
|
26
|
+
const validId = (value) => typeof value === "string" && value.length > 0 && value.length <= 256 && value.trim() === value;
|
|
27
|
+
function checkPrice(price) {
|
|
28
|
+
if (![price.provider, price.model, price.version].every(validId)
|
|
29
|
+
|| !validMoney(price.inputMicrosPerMillion) || !validMoney(price.outputMicrosPerMillion))
|
|
30
|
+
throw new TypeError("Invalid usage price");
|
|
31
|
+
}
|
|
32
|
+
async function lockBudgets(tx, ids) {
|
|
33
|
+
return (await tx.query("SELECT id, limit_micros, held_micros, spent_micros FROM accelerate_usage_budgets WHERE id = ANY($1::text[]) ORDER BY id FOR UPDATE", [ids])).rows;
|
|
34
|
+
}
|
|
35
|
+
export function createPostgresUsageBudgetStore(db) {
|
|
36
|
+
const store = {
|
|
37
|
+
async reserve(input) {
|
|
38
|
+
const ids = [...new Set(input.budgetIds)];
|
|
39
|
+
const { id, estimateMicros, price, now, expiresAt } = input;
|
|
40
|
+
if (!validId(id) || ids.length === 0 || ids.length > 16 || ids.length !== input.budgetIds.length
|
|
41
|
+
|| !ids.every(validId) || !validMoney(estimateMicros) || !validDate(now) || !validDate(expiresAt) || expiresAt <= now) {
|
|
42
|
+
throw new TypeError("Invalid usage reservation");
|
|
43
|
+
}
|
|
44
|
+
checkPrice(price);
|
|
45
|
+
return db.transaction(async (tx) => {
|
|
46
|
+
const budgets = await lockBudgets(tx, ids);
|
|
47
|
+
const duplicate = await tx.query("SELECT id FROM accelerate_usage_reservations WHERE id = $1", [id]);
|
|
48
|
+
if (duplicate.rowCount)
|
|
49
|
+
return "duplicate";
|
|
50
|
+
const active = await tx.query("SELECT id FROM accelerate_usage_budgets WHERE id = ANY($1::text[]) AND starts_at <= $2 AND ends_at > $2", [ids, now]);
|
|
51
|
+
if (active.rowCount !== ids.length || budgets.length !== ids.length || budgets.some(row => BigInt(row.held_micros) + BigInt(row.spent_micros) + estimateMicros > BigInt(row.limit_micros)))
|
|
52
|
+
return "exhausted";
|
|
53
|
+
const inserted = await tx.query(`INSERT INTO accelerate_usage_reservations (id, budget_ids, estimated_micros, state, provider, model,
|
|
54
|
+
price_version, price_input, price_output, started_at, expires_at, updated_at)
|
|
55
|
+
VALUES ($1,$2,$3,'reserved',$4,$5,$6,$7,$8,$9,$10,$9) ON CONFLICT DO NOTHING`, [id, ids, estimateMicros.toString(), price.provider, price.model, price.version,
|
|
56
|
+
price.inputMicrosPerMillion.toString(), price.outputMicrosPerMillion.toString(), now, expiresAt]);
|
|
57
|
+
if (!inserted.rowCount)
|
|
58
|
+
return "duplicate";
|
|
59
|
+
await tx.query("UPDATE accelerate_usage_budgets SET held_micros = held_micros + $2 WHERE id = ANY($1::text[])", [ids, estimateMicros.toString()]);
|
|
60
|
+
return "reserved";
|
|
61
|
+
});
|
|
62
|
+
},
|
|
63
|
+
async settle(id, costMicros, usage, now) {
|
|
64
|
+
const tokens = [usage?.inputTokens ?? null, usage?.outputTokens ?? null];
|
|
65
|
+
if (!validId(id) || !validMoney(costMicros) || !validDate(now)
|
|
66
|
+
|| !tokens.every(value => value === null || (Number.isSafeInteger(value) && value >= 0)))
|
|
67
|
+
throw new TypeError("Invalid usage settlement");
|
|
68
|
+
await db.transaction(async (tx) => {
|
|
69
|
+
const entry = (await tx.query(`SELECT id, state, budget_ids, estimated_micros, actual_micros, input_tokens, output_tokens
|
|
70
|
+
FROM accelerate_usage_reservations WHERE id = $1 FOR UPDATE`, [id])).rows[0];
|
|
71
|
+
if (!entry)
|
|
72
|
+
throw new Error("Unknown budget reservation");
|
|
73
|
+
if (entry.state === "settled") {
|
|
74
|
+
const same = entry.actual_micros === costMicros.toString()
|
|
75
|
+
&& [entry.input_tokens, entry.output_tokens].every((token, i) => token === (tokens[i]?.toString() ?? null));
|
|
76
|
+
if (!same)
|
|
77
|
+
throw new Error("Budget reservation has a different settlement");
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const budgets = await lockBudgets(tx, entry.budget_ids);
|
|
81
|
+
if (budgets.length !== entry.budget_ids.length)
|
|
82
|
+
throw new Error("Budget reservation references a missing budget");
|
|
83
|
+
await tx.query("UPDATE accelerate_usage_budgets SET held_micros = held_micros - $2, spent_micros = spent_micros + $3 WHERE id = ANY($1::text[])", [entry.budget_ids, entry.estimated_micros, costMicros.toString()]);
|
|
84
|
+
await tx.query(`UPDATE accelerate_usage_reservations SET state = 'settled', actual_micros = $2,
|
|
85
|
+
input_tokens = $3, output_tokens = $4, updated_at = $5 WHERE id = $1`, [id, costMicros.toString(), ...tokens, now]);
|
|
86
|
+
});
|
|
87
|
+
},
|
|
88
|
+
async markUncertain(id, now) {
|
|
89
|
+
if (!validId(id) || !validDate(now))
|
|
90
|
+
throw new TypeError("Invalid usage reservation");
|
|
91
|
+
await db.query("UPDATE accelerate_usage_reservations SET state = 'uncertain', updated_at = $2 WHERE id = $1 AND state = 'reserved'", [id, now]);
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
return {
|
|
95
|
+
...store,
|
|
96
|
+
async defineBudget(input) {
|
|
97
|
+
const { id, scope, startsAt, endsAt, limitMicros } = input;
|
|
98
|
+
if (!validId(id) || !validId(scope) || !validDate(startsAt) || !validDate(endsAt)
|
|
99
|
+
|| endsAt <= startsAt || !validMoney(limitMicros))
|
|
100
|
+
throw new TypeError("Invalid budget period");
|
|
101
|
+
await db.query("INSERT INTO accelerate_usage_budgets (id, scope, starts_at, ends_at, limit_micros) VALUES ($1,$2,$3,$4,$5)", [id, scope, startsAt, endsAt, limitMicros.toString()]);
|
|
102
|
+
},
|
|
103
|
+
async report(id) {
|
|
104
|
+
const row = (await db.query("SELECT id, limit_micros, held_micros, spent_micros FROM accelerate_usage_budgets WHERE id = $1", [id])).rows[0];
|
|
105
|
+
if (!row)
|
|
106
|
+
return undefined;
|
|
107
|
+
const limitMicros = BigInt(row.limit_micros), heldMicros = BigInt(row.held_micros), spentMicros = BigInt(row.spent_micros);
|
|
108
|
+
const remainingMicros = limitMicros - heldMicros - spentMicros;
|
|
109
|
+
return { id, limitMicros, heldMicros, spentMicros, availableMicros: remainingMicros > 0n ? remainingMicros : 0n };
|
|
110
|
+
},
|
|
111
|
+
async listExpired(now, limit = 100) {
|
|
112
|
+
if (!validDate(now) || !Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
|
|
113
|
+
throw new TypeError("Invalid recovery query");
|
|
114
|
+
return (await db.query(`SELECT id, provider, model, price_version, estimated_micros FROM accelerate_usage_reservations
|
|
115
|
+
WHERE state IN ('reserved','uncertain') AND expires_at <= $1 ORDER BY expires_at, id LIMIT $2`, [now, limit])).rows;
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@accelerate/ai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Accelerate — Model gateways, prompts, structured output, agents and evaluation.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"accelerate",
|
|
@@ -20,6 +20,10 @@
|
|
|
20
20
|
"types": "./dist/modules/agents-core/dist/index.d.ts",
|
|
21
21
|
"default": "./dist/modules/agents-core/dist/index.js"
|
|
22
22
|
},
|
|
23
|
+
"./agents/durable": {
|
|
24
|
+
"types": "./dist/modules/agents-core/dist/durable.d.ts",
|
|
25
|
+
"default": "./dist/modules/agents-core/dist/durable.js"
|
|
26
|
+
},
|
|
23
27
|
"./core": {
|
|
24
28
|
"types": "./dist/modules/ai-core/dist/index.d.ts",
|
|
25
29
|
"default": "./dist/modules/ai-core/dist/index.js"
|
|
@@ -47,6 +51,14 @@
|
|
|
47
51
|
"./usage": {
|
|
48
52
|
"types": "./dist/modules/ai-usage/dist/index.d.ts",
|
|
49
53
|
"default": "./dist/modules/ai-usage/dist/index.js"
|
|
54
|
+
},
|
|
55
|
+
"./usage/budgets": {
|
|
56
|
+
"types": "./dist/modules/ai-usage/dist/budgets.d.ts",
|
|
57
|
+
"default": "./dist/modules/ai-usage/dist/budgets.js"
|
|
58
|
+
},
|
|
59
|
+
"./usage/postgres": {
|
|
60
|
+
"types": "./dist/modules/ai-usage/dist/postgres.d.ts",
|
|
61
|
+
"default": "./dist/modules/ai-usage/dist/postgres.js"
|
|
50
62
|
}
|
|
51
63
|
},
|
|
52
64
|
"files": [
|
|
@@ -69,8 +81,10 @@
|
|
|
69
81
|
"tag": "latest"
|
|
70
82
|
},
|
|
71
83
|
"dependencies": {
|
|
72
|
-
"@accelerate/
|
|
73
|
-
"@accelerate/
|
|
84
|
+
"@accelerate/messaging": "0.2.0",
|
|
85
|
+
"@accelerate/testing": "0.1.2",
|
|
86
|
+
"@accelerate/core": "0.1.0",
|
|
87
|
+
"@accelerate/data": "0.1.0"
|
|
74
88
|
},
|
|
75
89
|
"devDependencies": {
|
|
76
90
|
"@accelerate/agents-core": "0.1.0",
|