@spendgraph/sdk 0.5.1 → 0.7.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/LICENSE +202 -0
- package/README.md +25 -80
- package/dist/ai.js +1 -25
- package/dist/client.d.ts +2 -1
- package/dist/client.js +1 -38
- package/dist/core/client/client.d.ts +2 -0
- package/dist/core/client/client.js +1 -132
- package/dist/core/client/errors.js +1 -17
- package/dist/core/client/index.js +1 -2
- package/dist/core/concurrency.d.ts +2 -0
- package/dist/core/concurrency.js +1 -0
- package/dist/core/money.d.ts +23 -0
- package/dist/core/money.js +1 -0
- package/dist/core/types.d.ts +4 -0
- package/dist/core/types.js +0 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +1 -5
- package/dist/langchain.js +1 -69
- package/dist/resources/alerts.js +1 -9
- package/dist/resources/cli.js +1 -21
- package/dist/resources/credentials.js +1 -15
- package/dist/resources/events.js +1 -18
- package/dist/resources/files.d.ts +35 -0
- package/dist/resources/files.js +1 -0
- package/dist/resources/index.d.ts +4 -2
- package/dist/resources/index.js +1 -13
- package/dist/resources/ingest.js +1 -27
- package/dist/resources/keys.js +1 -15
- package/dist/resources/playground.js +1 -9
- package/dist/resources/pricing.js +1 -36
- package/dist/resources/projects.js +1 -49
- package/dist/resources/prompts-admin.js +1 -21
- package/dist/resources/prompts.d.ts +13 -1
- package/dist/resources/prompts.js +1 -49
- package/dist/resources/stats.js +1 -21
- package/dist/resources/tools.d.ts +1 -1
- package/dist/resources/tools.js +1 -21
- package/dist/rollout/index.d.ts +1 -0
- package/dist/rollout/index.js +1 -1
- package/dist/rollout/rollout.d.ts +30 -0
- package/dist/rollout/rollout.js +1 -1
- package/dist/schema/index.d.ts +1 -1
- package/dist/schema/index.js +1 -2
- package/dist/schema/serialize/index.js +1 -1
- package/dist/schema/serialize/serialize.js +1 -31
- package/dist/schema/types/index.js +0 -1
- package/dist/schema/types/types.js +0 -1
- package/dist/schema/validate/index.js +1 -1
- package/dist/schema/validate/validate.d.ts +4 -0
- package/dist/schema/validate/validate.js +1 -92
- package/dist/track/index.js +1 -1
- package/dist/track/track.js +1 -331
- package/docs/client.mdx +85 -0
- package/docs/errors.mdx +82 -0
- package/docs/tracking.mdx +62 -0
- package/package.json +11 -8
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 spendgraph
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,100 +1,45 @@
|
|
|
1
1
|
# @spendgraph/sdk
|
|
2
2
|
|
|
3
|
-
Track
|
|
4
|
-
|
|
5
|
-
Tracking must never be the reason a request fails, so every path here is
|
|
6
|
-
non-blocking and swallows its own errors: `track()` returns `void`, network
|
|
7
|
-
failures retry once and then drop with a warning, and nothing throws into your
|
|
8
|
-
handler.
|
|
3
|
+
Track LLM input/output tokens and cost. Three functions, zero dependencies, fail-open.
|
|
9
4
|
|
|
10
5
|
```bash
|
|
11
6
|
npm install @spendgraph/sdk
|
|
12
7
|
```
|
|
13
8
|
|
|
14
|
-
## Wrap a client
|
|
15
|
-
|
|
16
|
-
The shortest path — no per-call code, and streaming, cache tokens and OpenAI
|
|
17
|
-
clients are all handled:
|
|
18
|
-
|
|
19
9
|
```ts
|
|
20
|
-
import { SpendGraph } from "@spendgraph/sdk";
|
|
21
10
|
import Anthropic from "@anthropic-ai/sdk";
|
|
11
|
+
import { SpendGraph } from "@spendgraph/sdk";
|
|
22
12
|
|
|
23
|
-
const meter = new SpendGraph({
|
|
24
|
-
apiKey: process.env.SPENDGRAPH_API_KEY,
|
|
25
|
-
baseUrl: "https://your-spendgraph.example.com",
|
|
26
|
-
});
|
|
27
|
-
|
|
13
|
+
const meter = new SpendGraph({ apiKey: process.env.SPENDGRAPH_API_KEY, baseUrl });
|
|
28
14
|
const anthropic = meter.wrap(new Anthropic());
|
|
29
15
|
```
|
|
30
16
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
```ts
|
|
34
|
-
meter.track({
|
|
35
|
-
model: "claude-sonnet-4-5",
|
|
36
|
-
inputTokens: 3211, // fresh tokens only
|
|
37
|
-
outputTokens: 842,
|
|
38
|
-
cacheReadTokens: 18004, // from cache_read_input_tokens
|
|
39
|
-
cacheWriteTokens: 3211, // from cache_creation_input_tokens
|
|
40
|
-
metadata: { feature: "chat", env: "prod" },
|
|
41
|
-
});
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
**The three token counts are disjoint.** Providers report them that way —
|
|
45
|
-
Anthropic's total input is `input + cache_read + cache_creation` — and spendgraph
|
|
46
|
-
prices them the same way. Do not fold cache tokens into `inputTokens` as well:
|
|
47
|
-
that bills the same tokens twice, at the wrong rate. Omitting them loses the
|
|
48
|
-
spend entirely.
|
|
49
|
-
|
|
50
|
-
## Serverless
|
|
51
|
-
|
|
52
|
-
Events batch in memory and flush every 5s or 20 events. Serverless platforms
|
|
53
|
-
suspend a function once it returns rather than exiting it, so neither the timer
|
|
54
|
-
nor `beforeExit` runs — **await `flush()` before your handler returns**:
|
|
55
|
-
|
|
56
|
-
```ts
|
|
57
|
-
export async function handler(event) {
|
|
58
|
-
const result = await callTheModel(event);
|
|
59
|
-
await meter.flush();
|
|
60
|
-
return result;
|
|
61
|
-
}
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
If a flush is ever stranded that way, the SDK notices on the next invocation,
|
|
65
|
-
sends the stragglers, and warns once explaining the fix.
|
|
66
|
-
|
|
67
|
-
## Other integrations
|
|
68
|
-
|
|
69
|
-
```ts
|
|
70
|
-
import { spendGraphHandler } from "@spendgraph/sdk/langchain";
|
|
71
|
-
await graph.invoke(state, { callbacks: [spendGraphHandler(meter)] });
|
|
72
|
-
|
|
73
|
-
import { trackAiResult } from "@spendgraph/sdk/ai";
|
|
74
|
-
trackAiResult(meter, await generateText({ model, prompt }));
|
|
75
|
-
```
|
|
76
|
-
|
|
77
|
-
## Options
|
|
78
|
-
|
|
79
|
-
| Option | Default | |
|
|
80
|
-
| --- | --- | --- |
|
|
81
|
-
| `apiKey` | — | Without it, `track()` is a no-op |
|
|
82
|
-
| `baseUrl` | — | Your spendgraph deployment |
|
|
83
|
-
| `flushIntervalMs` | `5000` | |
|
|
84
|
-
| `maxBatch` | `20` | Flush once this many events are queued |
|
|
17
|
+
Use the client exactly as before. Usage is read off each reply and reported for
|
|
18
|
+
you, and spend appears on the dashboard within seconds.
|
|
85
19
|
|
|
86
|
-
##
|
|
20
|
+
## What you get
|
|
87
21
|
|
|
88
|
-
|
|
89
|
-
|
|
22
|
+
- **One line to wire in.** `wrap()` proxies an Anthropic or OpenAI client and
|
|
23
|
+
reads the provider's own usage block, cache counts included.
|
|
24
|
+
- **It never throws into your code.** Batched, non-blocking, and it drops data
|
|
25
|
+
rather than take your app down when the meter is having a bad day.
|
|
26
|
+
- **Nothing about the conversation is sent** — the model, the counts, and
|
|
27
|
+
whatever metadata you attached.
|
|
28
|
+
- **The whole API, typed.** `Spendgraph` reaches prompts, tools, stats and
|
|
29
|
+
events, with retries and error shapes decided once.
|
|
90
30
|
|
|
91
|
-
|
|
92
|
-
> until the model is in the catalog.`
|
|
31
|
+
## Docs
|
|
93
32
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
33
|
+
| | |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| [Quickstart](https://spendgraph.locusgraph.com/docs/sdk/quickstart) | Two minutes to your first tracked call |
|
|
36
|
+
| [Tracking](https://spendgraph.locusgraph.com/docs/sdk/tracking) | wrap, track and flush |
|
|
37
|
+
| [The client](https://spendgraph.locusgraph.com/docs/sdk/client) | Spendgraph, and the two halves it reaches |
|
|
38
|
+
| [Errors and retries](https://spendgraph.locusgraph.com/docs/sdk/errors) | What throws, what retries, what never will |
|
|
39
|
+
| [HTTP API](https://spendgraph.locusgraph.com/docs/sdk/api) | Ingest, stats, events, CSV export |
|
|
40
|
+
| [Integrations](https://spendgraph.locusgraph.com/docs/sdk/integrations) | LangChain, LangGraph, Vercel AI |
|
|
41
|
+
| [Budgets and alerts](https://spendgraph.locusgraph.com/docs/sdk/budgets) | Thresholds, webhooks, what never happens |
|
|
97
42
|
|
|
98
43
|
## License
|
|
99
44
|
|
|
100
|
-
|
|
45
|
+
Apache-2.0
|
package/dist/ai.js
CHANGED
|
@@ -1,25 +1 @@
|
|
|
1
|
-
|
|
2
|
-
try {
|
|
3
|
-
const usage = result?.totalUsage ?? result?.usage;
|
|
4
|
-
let inputTokens = usage?.inputTokens ?? usage?.promptTokens;
|
|
5
|
-
const outputTokens = usage?.outputTokens ?? usage?.completionTokens;
|
|
6
|
-
if (typeof inputTokens !== "number" || typeof outputTokens !== "number")
|
|
7
|
-
return;
|
|
8
|
-
const cacheReadTokens = usage?.cachedInputTokens ?? 0;
|
|
9
|
-
inputTokens = Math.max(0, inputTokens - cacheReadTokens);
|
|
10
|
-
const model = options.model ??
|
|
11
|
-
result?.response?.modelId ??
|
|
12
|
-
result?.response?.model ??
|
|
13
|
-
result?.modelId ??
|
|
14
|
-
"unknown";
|
|
15
|
-
meter.track({
|
|
16
|
-
model,
|
|
17
|
-
inputTokens,
|
|
18
|
-
outputTokens,
|
|
19
|
-
cacheReadTokens,
|
|
20
|
-
metadata: options.metadata,
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
catch {
|
|
24
|
-
}
|
|
25
|
-
}
|
|
1
|
+
function p(c,e,n={}){try{const o=e?.totalUsage??e?.usage;let t=o?.inputTokens??o?.promptTokens;const a=o?.outputTokens??o?.completionTokens;if(typeof t!="number"||typeof a!="number")return;const s=o?.cachedInputTokens??0;t=Math.max(0,t-s);const m=n.model??e?.response?.modelId??e?.response?.model??e?.modelId??"unknown";c.track({model:m,inputTokens:t,outputTokens:a,cacheReadTokens:s,metadata:n.metadata})}catch{}}export{p as trackAiResult};
|
package/dist/client.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Client } from "./core/client/index.js";
|
|
2
2
|
import type { ClientOptions } from "./core/types.js";
|
|
3
|
-
import { Alerts, Cli, Credentials, Events, Ingest, Invites, Keys, Models, Playground, Pricing, Projects, Prompts, PromptsAdmin, Stats, Tools } from "./resources/index.js";
|
|
3
|
+
import { Alerts, Cli, Credentials, Events, Files, Ingest, Invites, Keys, Models, Playground, Pricing, Projects, Prompts, PromptsAdmin, Stats, Tools } from "./resources/index.js";
|
|
4
4
|
export interface SpendgraphOptions extends ClientOptions {
|
|
5
5
|
/** Scopes writes that accept one. A key is already pinned to its project. */
|
|
6
6
|
project?: string;
|
|
@@ -35,5 +35,6 @@ export declare class Spendgraph {
|
|
|
35
35
|
readonly credentials: Credentials;
|
|
36
36
|
readonly playground: Playground;
|
|
37
37
|
readonly tools: Tools;
|
|
38
|
+
readonly files: Files;
|
|
38
39
|
constructor(opts: SpendgraphOptions);
|
|
39
40
|
}
|
package/dist/client.js
CHANGED
|
@@ -1,38 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { Alerts, Cli, Credentials, Events, Ingest, Invites, Keys, Models, Playground, Pricing, Projects, Prompts, PromptsAdmin, Stats, Tools, } from "./resources/index.js";
|
|
3
|
-
export class Spendgraph {
|
|
4
|
-
http;
|
|
5
|
-
cli;
|
|
6
|
-
ingest;
|
|
7
|
-
stats;
|
|
8
|
-
events;
|
|
9
|
-
alerts;
|
|
10
|
-
prompts;
|
|
11
|
-
promptsAdmin;
|
|
12
|
-
keys;
|
|
13
|
-
projects;
|
|
14
|
-
invites;
|
|
15
|
-
pricing;
|
|
16
|
-
models;
|
|
17
|
-
credentials;
|
|
18
|
-
playground;
|
|
19
|
-
tools;
|
|
20
|
-
constructor(opts) {
|
|
21
|
-
this.http = new Client(opts);
|
|
22
|
-
this.cli = new Cli(this.http);
|
|
23
|
-
this.ingest = new Ingest(this.http, opts.project);
|
|
24
|
-
this.stats = new Stats(this.http);
|
|
25
|
-
this.events = new Events(this.http);
|
|
26
|
-
this.alerts = new Alerts(this.http);
|
|
27
|
-
this.prompts = new Prompts(this.http);
|
|
28
|
-
this.promptsAdmin = new PromptsAdmin(this.http);
|
|
29
|
-
this.keys = new Keys(this.http);
|
|
30
|
-
this.projects = new Projects(this.http);
|
|
31
|
-
this.invites = new Invites(this.http);
|
|
32
|
-
this.pricing = new Pricing(this.http);
|
|
33
|
-
this.models = new Models(this.http);
|
|
34
|
-
this.credentials = new Credentials(this.http);
|
|
35
|
-
this.playground = new Playground(this.http);
|
|
36
|
-
this.tools = new Tools(this.http);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
1
|
+
import{Client as s}from"./core/client/index.js";import{Alerts as i,Cli as e,Credentials as h,Events as n,Files as p,Ingest as r,Invites as o,Keys as l,Models as w,Playground as m,Pricing as c,Projects as a,Prompts as d,PromptsAdmin as g,Stats as v,Tools as y}from"./resources/index.js";class u{http;cli;ingest;stats;events;alerts;prompts;promptsAdmin;keys;projects;invites;pricing;models;credentials;playground;tools;files;constructor(t){this.http=new s(t),this.cli=new e(this.http),this.ingest=new r(this.http,t.project),this.stats=new v(this.http),this.events=new n(this.http),this.alerts=new i(this.http),this.prompts=new d(this.http),this.promptsAdmin=new g(this.http),this.keys=new l(this.http),this.projects=new a(this.http),this.invites=new o(this.http),this.pricing=new c(this.http),this.models=new w(this.http),this.credentials=new h(this.http),this.playground=new m(this.http),this.tools=new y(this.http),this.files=new p(this.http)}}export{u as Spendgraph};
|
|
@@ -11,8 +11,10 @@ export declare class Client {
|
|
|
11
11
|
private readonly baseUrl;
|
|
12
12
|
private readonly doFetch;
|
|
13
13
|
private readonly sleep;
|
|
14
|
+
private readonly random;
|
|
14
15
|
private readonly attempts;
|
|
15
16
|
private readonly maxWaitMs;
|
|
17
|
+
private readonly maxRetryAfterMs;
|
|
16
18
|
private readonly auth;
|
|
17
19
|
constructor(opts: ClientOptions);
|
|
18
20
|
/** True once anything is set that the server might accept. */
|
|
@@ -1,132 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
const DEFAULT_ATTEMPTS = 3;
|
|
3
|
-
const DEFAULT_MAX_WAIT_MS = 5_000;
|
|
4
|
-
const BACKOFF_BASE_MS = 250;
|
|
5
|
-
function retryAfterMs(res) {
|
|
6
|
-
const raw = res.headers.get("retry-after");
|
|
7
|
-
if (!raw)
|
|
8
|
-
return null;
|
|
9
|
-
const seconds = Number(raw);
|
|
10
|
-
return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : null;
|
|
11
|
-
}
|
|
12
|
-
export function queryString(query = {}) {
|
|
13
|
-
const params = new URLSearchParams();
|
|
14
|
-
for (const [key, value] of Object.entries(query)) {
|
|
15
|
-
if (value === undefined || value === null || value === "")
|
|
16
|
-
continue;
|
|
17
|
-
params.set(key, String(value));
|
|
18
|
-
}
|
|
19
|
-
const encoded = params.toString();
|
|
20
|
-
return encoded ? `?${encoded}` : "";
|
|
21
|
-
}
|
|
22
|
-
export class Client {
|
|
23
|
-
baseUrl;
|
|
24
|
-
doFetch;
|
|
25
|
-
sleep;
|
|
26
|
-
attempts;
|
|
27
|
-
maxWaitMs;
|
|
28
|
-
auth;
|
|
29
|
-
constructor(opts) {
|
|
30
|
-
this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
|
|
31
|
-
this.doFetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
32
|
-
this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
33
|
-
this.attempts = Math.max(1, opts.attempts ?? DEFAULT_ATTEMPTS);
|
|
34
|
-
this.maxWaitMs = opts.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;
|
|
35
|
-
this.auth = {
|
|
36
|
-
...opts.headers,
|
|
37
|
-
...(opts.apiKey ? { "x-api-key": opts.apiKey } : {}),
|
|
38
|
-
...(opts.session ? { cookie: opts.session } : {}),
|
|
39
|
-
...(opts.token ? { authorization: `Bearer ${opts.token}` } : {}),
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
get authenticated() {
|
|
43
|
-
return Object.keys(this.auth).length > 0;
|
|
44
|
-
}
|
|
45
|
-
async request(path, init = {}, opts = {}) {
|
|
46
|
-
if (!opts.anonymous && !this.authenticated) {
|
|
47
|
-
throw new SpendgraphError(401, "no_credentials", "No spendgraph apiKey, session or token set.");
|
|
48
|
-
}
|
|
49
|
-
const url = `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
|
|
50
|
-
let last;
|
|
51
|
-
for (let attempt = 1; attempt <= this.attempts; attempt++) {
|
|
52
|
-
let res;
|
|
53
|
-
try {
|
|
54
|
-
res = await this.doFetch(url, {
|
|
55
|
-
...init,
|
|
56
|
-
headers: { "content-type": "application/json", ...this.auth, ...init.headers },
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
catch (err) {
|
|
60
|
-
last = new SpendgraphError(0, "network_error", err.message, {
|
|
61
|
-
attempts: attempt,
|
|
62
|
-
});
|
|
63
|
-
if (attempt < this.attempts) {
|
|
64
|
-
await this.sleep(Math.min(this.maxWaitMs, BACKOFF_BASE_MS * 2 ** (attempt - 1)));
|
|
65
|
-
continue;
|
|
66
|
-
}
|
|
67
|
-
throw last;
|
|
68
|
-
}
|
|
69
|
-
if (res.ok)
|
|
70
|
-
return (await this.decode(res));
|
|
71
|
-
last = await this.toError(res, attempt);
|
|
72
|
-
if (!last.retryable || attempt === this.attempts)
|
|
73
|
-
throw last;
|
|
74
|
-
const wait = retryAfterMs(res) ?? BACKOFF_BASE_MS * 2 ** (attempt - 1);
|
|
75
|
-
await this.sleep(Math.min(this.maxWaitMs, wait));
|
|
76
|
-
}
|
|
77
|
-
throw last ?? new SpendgraphError(0, "unknown", "Request failed.");
|
|
78
|
-
}
|
|
79
|
-
get(path, query) {
|
|
80
|
-
return this.request(`${path}${queryString(query)}`);
|
|
81
|
-
}
|
|
82
|
-
post(path, body, query) {
|
|
83
|
-
return this.send("POST", path, body, query);
|
|
84
|
-
}
|
|
85
|
-
put(path, body, query) {
|
|
86
|
-
return this.send("PUT", path, body, query);
|
|
87
|
-
}
|
|
88
|
-
patch(path, body, query) {
|
|
89
|
-
return this.send("PATCH", path, body, query);
|
|
90
|
-
}
|
|
91
|
-
delete(path, query) {
|
|
92
|
-
return this.request(`${path}${queryString(query)}`, { method: "DELETE" });
|
|
93
|
-
}
|
|
94
|
-
postAnonymous(path, body) {
|
|
95
|
-
return this.request(path, { method: "POST", ...(body === undefined ? {} : { body: JSON.stringify(body) }) }, { anonymous: true });
|
|
96
|
-
}
|
|
97
|
-
send(method, path, body, query) {
|
|
98
|
-
return this.request(`${path}${queryString(query)}`, {
|
|
99
|
-
method,
|
|
100
|
-
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
101
|
-
});
|
|
102
|
-
}
|
|
103
|
-
async decode(res) {
|
|
104
|
-
if (res.status === 204)
|
|
105
|
-
return undefined;
|
|
106
|
-
const text = await res.text();
|
|
107
|
-
if (!text)
|
|
108
|
-
return undefined;
|
|
109
|
-
try {
|
|
110
|
-
return JSON.parse(text);
|
|
111
|
-
}
|
|
112
|
-
catch {
|
|
113
|
-
return text;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
async toError(res, attempt) {
|
|
117
|
-
let code = "http_error";
|
|
118
|
-
let message = `${res.status} ${res.statusText}`.trim();
|
|
119
|
-
try {
|
|
120
|
-
const body = (await res.json());
|
|
121
|
-
if (body?.error?.code)
|
|
122
|
-
code = body.error.code;
|
|
123
|
-
if (body?.error?.message)
|
|
124
|
-
message = body.error.message;
|
|
125
|
-
}
|
|
126
|
-
catch { }
|
|
127
|
-
return new SpendgraphError(res.status, code, message, {
|
|
128
|
-
attempts: attempt,
|
|
129
|
-
retryAfterMs: retryAfterMs(res),
|
|
130
|
-
});
|
|
131
|
-
}
|
|
132
|
-
}
|
|
1
|
+
import{SpendgraphError as h}from"./errors.js";const f=3,l=5e3,y=6e4,M=250;function c(i,t=Date.now()){const e=i.headers.get("retry-after");if(!e)return null;const r=Number(e);if(Number.isFinite(r)&&r>=0)return r*1e3;const s=Date.parse(e);return Number.isFinite(s)?Math.max(0,s-t):null}function m(i,t,e,r){return i!==null?Math.min(e.maxRetryAfterMs,i):Math.min(e.maxWaitMs,M*2**(t-1))*(.5+r())}function u(i={}){const t=new URLSearchParams;for(const[r,s]of Object.entries(i))s==null||s===""||t.set(r,String(s));const e=t.toString();return e?`?${e}`:""}class w{baseUrl;doFetch;sleep;random;attempts;maxWaitMs;maxRetryAfterMs;auth;constructor(t){this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.doFetch=t.fetch??globalThis.fetch.bind(globalThis),this.sleep=t.sleep??(e=>new Promise(r=>setTimeout(r,e))),this.random=t.random??Math.random,this.attempts=Math.max(1,t.attempts??f),this.maxWaitMs=t.maxWaitMs??l,this.maxRetryAfterMs=t.maxRetryAfterMs??y,this.auth={...t.headers,...t.apiKey?{"x-api-key":t.apiKey}:{},...t.session?{cookie:t.session}:{},...t.token?{authorization:`Bearer ${t.token}`}:{}}}get authenticated(){return Object.keys(this.auth).length>0}async request(t,e={},r={}){if(!r.anonymous&&!this.authenticated)throw new h(401,"no_credentials","No spendgraph apiKey, session or token set.");const s=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`;let a;for(let n=1;n<=this.attempts;n++){let o;try{o=await this.doFetch(s,{...e,headers:{"content-type":"application/json",...this.auth,...e.headers}})}catch(d){if(a=new h(0,"network_error",d.message,{attempts:n}),n<this.attempts){await this.sleep(m(null,n,{maxWaitMs:this.maxWaitMs,maxRetryAfterMs:this.maxRetryAfterMs},this.random));continue}throw a}if(o.ok)return await this.decode(o);if(a=await this.toError(o,n),!a.retryable||n===this.attempts)throw a;await this.sleep(m(c(o),n,{maxWaitMs:this.maxWaitMs,maxRetryAfterMs:this.maxRetryAfterMs},this.random))}throw a??new h(0,"unknown","Request failed.")}get(t,e){return this.request(`${t}${u(e)}`)}post(t,e,r){return this.send("POST",t,e,r)}put(t,e,r){return this.send("PUT",t,e,r)}patch(t,e,r){return this.send("PATCH",t,e,r)}delete(t,e){return this.request(`${t}${u(e)}`,{method:"DELETE"})}postAnonymous(t,e){return this.request(t,{method:"POST",...e===void 0?{}:{body:JSON.stringify(e)}},{anonymous:!0})}send(t,e,r,s){return this.request(`${e}${u(s)}`,{method:t,...r===void 0?{}:{body:JSON.stringify(r)}})}async decode(t){if(t.status===204)return;const e=await t.text();if(e)try{return JSON.parse(e)}catch{return e}}async toError(t,e){let r="http_error",s=`${t.status} ${t.statusText}`.trim();try{const a=await t.json();a?.error?.code&&(r=a.error.code),a?.error?.message&&(s=a.error.message)}catch{}return new h(t.status,r,s,{attempts:e,retryAfterMs:c(t)})}}export{w as Client,u as queryString};
|
|
@@ -1,17 +1 @@
|
|
|
1
|
-
|
|
2
|
-
status;
|
|
3
|
-
code;
|
|
4
|
-
attempts;
|
|
5
|
-
retryAfterMs;
|
|
6
|
-
constructor(status, code, message, opts = {}) {
|
|
7
|
-
super(message);
|
|
8
|
-
this.name = "SpendgraphError";
|
|
9
|
-
this.status = status;
|
|
10
|
-
this.code = code;
|
|
11
|
-
this.attempts = opts.attempts ?? 1;
|
|
12
|
-
this.retryAfterMs = opts.retryAfterMs ?? null;
|
|
13
|
-
}
|
|
14
|
-
get retryable() {
|
|
15
|
-
return this.status === 0 || this.status === 429 || this.status >= 500;
|
|
16
|
-
}
|
|
17
|
-
}
|
|
1
|
+
class h extends Error{status;code;attempts;retryAfterMs;constructor(r,s,e,t={}){super(e),this.name="SpendgraphError",this.status=r,this.code=s,this.attempts=t.attempts??1,this.retryAfterMs=t.retryAfterMs??null}get retryable(){return this.status===0||this.status===429||this.status>=500}}export{h as SpendgraphError};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { SpendgraphError } from "./errors.js";
|
|
1
|
+
import{Client as o,queryString as p}from"./client.js";import{SpendgraphError as n}from"./errors.js";export{o as Client,n as SpendgraphError,p as queryString};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
async function h(t,e,o){const a=new Array(t.length);let r=0;const l=Array.from({length:Math.max(1,Math.min(e,t.length))},async()=>{for(;r<t.length;){const n=r++;a[n]=await o(t[n],n)}});return await Promise.all(l),a}export{h as mapLimit};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A micro-USD integer as money somebody reads.
|
|
3
|
+
*
|
|
4
|
+
* Two decimal places, because that is what a person is owed for a price. The
|
|
5
|
+
* exception is the one that keeps this honest: an amount that is not zero but
|
|
6
|
+
* would print as `$0.00` is shown at the full six places instead, with trailing
|
|
7
|
+
* zeros trimmed. A judge call costing 250 micro-USD is a real cost, and a run
|
|
8
|
+
* of ten thousand of them is a real bill; rounding each to nothing and summing
|
|
9
|
+
* is how a report comes to say a paid run was free.
|
|
10
|
+
*
|
|
11
|
+
* Formatting only. The arithmetic stays in integers, which is the whole reason
|
|
12
|
+
* costs are micro-USD.
|
|
13
|
+
*/
|
|
14
|
+
export declare function formatMicros(micros: number, places?: number): string;
|
|
15
|
+
/**
|
|
16
|
+
* A price in dollars as the micro-USD integer everything else here holds.
|
|
17
|
+
*
|
|
18
|
+
* The one place a float is allowed: a price arrives from a rate card, an
|
|
19
|
+
* invoice or another system as `40.00`, and it has to become an integer once,
|
|
20
|
+
* here, rather than at every call site with a different rounding. Rounded to
|
|
21
|
+
* the nearest micro — below that there is nothing to represent.
|
|
22
|
+
*/
|
|
23
|
+
export declare function microsFromUsd(usd: number): number;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const c=1e6,u=6,e=(t,n)=>t.toLocaleString("en-US",{minimumFractionDigits:n,maximumFractionDigits:n});function a(t,n=2){if(!Number.isFinite(t))return"$\u2014";const o=t<0?"-":"",r=Math.abs(t)/1e6,i=e(r,n);if(t===0||/[1-9]/.test(i))return`${o}$${i}`;const s=e(r,6).replace(/0+$/,"");return`${o}$${s}`}function m(t){if(!Number.isFinite(t))throw new Error(`${t} is not an amount.`);return Math.round(t*1e6)}export{a as formatMicros,m as microsFromUsd};
|
package/dist/core/types.d.ts
CHANGED
|
@@ -25,6 +25,10 @@ export interface ClientOptions extends Credentials {
|
|
|
25
25
|
fetch?: typeof fetch;
|
|
26
26
|
/** Injected so tests do not actually wait out a backoff. */
|
|
27
27
|
sleep?: (ms: number) => Promise<void>;
|
|
28
|
+
/** Injected for tests. Spreads retries so clients do not wake in lockstep. */
|
|
29
|
+
random?: () => number;
|
|
30
|
+
/** Ceiling on a `retry-after` the server sent. Default 60000 — one window. */
|
|
31
|
+
maxRetryAfterMs?: number;
|
|
28
32
|
/** Total attempts including the first. Default 3. */
|
|
29
33
|
attempts?: number;
|
|
30
34
|
/** Never wait longer than this for one backoff. Default 5000. */
|
package/dist/core/types.js
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
export type { SpendgraphOptions } from "./client.js";
|
|
2
2
|
export { Spendgraph } from "./client.js";
|
|
3
3
|
export { Client, queryString, SpendgraphError } from "./core/client/index.js";
|
|
4
|
+
export { mapLimit } from "./core/concurrency.js";
|
|
5
|
+
export { formatMicros, microsFromUsd } from "./core/money.js";
|
|
4
6
|
export type { ClientOptions, Credentials as ClientCredentials, Query, Tag } from "./core/types.js";
|
|
5
7
|
export * from "./resources/index.js";
|
|
6
8
|
export type { RolloutInput, RolloutRecord, RolloutStep } from "./rollout/index.js";
|
|
7
|
-
export {
|
|
9
|
+
export { totalTokens } from "./rollout/index.js";
|
|
10
|
+
export { type FieldError, type FieldSpec, type FieldType, FieldValidationError, isMissing, serializeFields, toBoolean, toNumber, validateFields, } from "./schema/index.js";
|
|
8
11
|
export type { SpendGraphOptions, TrackEvent } from "./track/index.js";
|
|
9
12
|
export { SpendGraph } from "./track/index.js";
|