import { instrument, BeforeRequestResult } from "aden";
// Track costs locally
const userCosts = new Map<string, number>();
await instrument({
emitMetric: myEmitter,
sdks: { OpenAI },
getContextId: () => getCurrentUserId(),
beforeRequest: async (request): Promise<BeforeRequestResult> => {
const userId = getCurrentUserId();
const currentCost = userCosts.get(userId) || 0;
const estimatedCost = estimateCost(request.model, request.messages);
// Block if over budget
if (currentCost >= 10.0) {
return {
action: "cancel",
reason: "Monthly budget exceeded",
};
}
// Degrade expensive models when approaching budget
if (currentCost >= 8.0 && request.model === "gpt-4o") {
return {
action: "degrade",
toModel: "gpt-4o-mini",
reason: "Approaching budget limit",
};
}
// Throttle during high-cost periods
if (currentCost >= 5.0) {
return {
action: "throttle",
delayMs: 1000,
};
}
// Alert when halfway through budget
if (currentCost >= 5.0 && !hasAlertedUser(userId)) {
return {
action: "alert",
level: "warning",
message: "50% of monthly budget used",
};
}
return { action: "proceed" };
},
});