@salimassili/ai-costguard 2.1.2 → 2.2.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.
@@ -0,0 +1,58 @@
1
+ import { guard, GuardError, registerTokenizer } from '@salimassili/ai-costguard';
2
+
3
+ const webhookUrl = process.env.COSTGUARD_WEBHOOK_URL;
4
+ let providerCalls = 0;
5
+
6
+ registerTokenizer('gpt-4o-mini', (text) => Math.ceil(text.length / 4));
7
+
8
+ const mockedOpenAI = {
9
+ chat: {
10
+ completions: {
11
+ create: async () => {
12
+ providerCalls += 1;
13
+ return { ok: true };
14
+ },
15
+ },
16
+ },
17
+ };
18
+
19
+ const openai = guard(mockedOpenAI, {
20
+ budget: { maxUsd: 0.0001 },
21
+ projectId: 'webhook-alert-demo',
22
+ runId: 'local-run-1',
23
+ alerts: {
24
+ webhookUrl,
25
+ events: ['blocked'],
26
+ timeoutMs: 1000,
27
+ },
28
+ });
29
+
30
+ try {
31
+ await openai.chat.completions.create({
32
+ model: 'gpt-4o-mini',
33
+ messages: [{ role: 'user', content: 'Reserve a long output for an expensive agent step.' }],
34
+ max_tokens: 800,
35
+ });
36
+
37
+ throw new Error('Expected AI CostGuard to block the mocked provider call.');
38
+ } catch (error) {
39
+ if (!(error instanceof GuardError)) throw error;
40
+
41
+ console.log(
42
+ JSON.stringify(
43
+ {
44
+ demo: 'webhook-alerts',
45
+ alert: webhookUrl ? 'enabled from COSTGUARD_WEBHOOK_URL' : 'off by default',
46
+ blocked: true,
47
+ reason: error.code,
48
+ providerCalls,
49
+ },
50
+ null,
51
+ 2
52
+ )
53
+ );
54
+ }
55
+
56
+ if (providerCalls !== 0) {
57
+ throw new Error(`Provider executed ${providerCalls} time(s); expected 0.`);
58
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salimassili/ai-costguard",
3
- "version": "2.1.2",
3
+ "version": "2.2.0",
4
4
  "description": "Local-first runtime safety layer for AI agents that blocks runaway costs, loops, retries, and budget overruns before API calls execute.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",