@c9up/polaris 0.0.0-stage → 0.1.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.
Files changed (128) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +542 -2
  3. package/dist/Polaris.d.ts +76 -0
  4. package/dist/Polaris.d.ts.map +1 -0
  5. package/dist/Polaris.js +194 -0
  6. package/dist/Polaris.js.map +1 -0
  7. package/dist/PolarisClient.d.ts +136 -0
  8. package/dist/PolarisClient.d.ts.map +1 -0
  9. package/dist/PolarisClient.js +408 -0
  10. package/dist/PolarisClient.js.map +1 -0
  11. package/dist/PolarisProvider.d.ts +35 -0
  12. package/dist/PolarisProvider.d.ts.map +1 -0
  13. package/dist/PolarisProvider.js +47 -0
  14. package/dist/PolarisProvider.js.map +1 -0
  15. package/dist/augmentations.d.ts +15 -0
  16. package/dist/augmentations.d.ts.map +1 -0
  17. package/dist/augmentations.js +9 -0
  18. package/dist/augmentations.js.map +1 -0
  19. package/dist/budget.d.ts +44 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +67 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/cost.d.ts +48 -0
  24. package/dist/cost.d.ts.map +1 -0
  25. package/dist/cost.js +126 -0
  26. package/dist/cost.js.map +1 -0
  27. package/dist/drivers/anthropic.d.ts +39 -0
  28. package/dist/drivers/anthropic.d.ts.map +1 -0
  29. package/dist/drivers/anthropic.js +394 -0
  30. package/dist/drivers/anthropic.js.map +1 -0
  31. package/dist/drivers/openai-compatible.d.ts +54 -0
  32. package/dist/drivers/openai-compatible.d.ts.map +1 -0
  33. package/dist/drivers/openai-compatible.js +663 -0
  34. package/dist/drivers/openai-compatible.js.map +1 -0
  35. package/dist/drivers/status.d.ts +8 -0
  36. package/dist/drivers/status.d.ts.map +1 -0
  37. package/dist/drivers/status.js +21 -0
  38. package/dist/drivers/status.js.map +1 -0
  39. package/dist/errors.d.ts +55 -0
  40. package/dist/errors.d.ts.map +1 -0
  41. package/dist/errors.js +62 -0
  42. package/dist/errors.js.map +1 -0
  43. package/dist/extract.d.ts +38 -0
  44. package/dist/extract.d.ts.map +1 -0
  45. package/dist/extract.js +144 -0
  46. package/dist/extract.js.map +1 -0
  47. package/dist/index.d.ts +19 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +13 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/log.d.ts +47 -0
  52. package/dist/log.d.ts.map +1 -0
  53. package/dist/log.js +33 -0
  54. package/dist/log.js.map +1 -0
  55. package/dist/meter.d.ts +57 -0
  56. package/dist/meter.d.ts.map +1 -0
  57. package/dist/meter.js +91 -0
  58. package/dist/meter.js.map +1 -0
  59. package/dist/providers.d.ts +23 -0
  60. package/dist/providers.d.ts.map +1 -0
  61. package/dist/providers.js +21 -0
  62. package/dist/providers.js.map +1 -0
  63. package/dist/redact.d.ts +11 -0
  64. package/dist/redact.d.ts.map +1 -0
  65. package/dist/redact.js +76 -0
  66. package/dist/redact.js.map +1 -0
  67. package/dist/response.d.ts +21 -0
  68. package/dist/response.d.ts.map +1 -0
  69. package/dist/response.js +45 -0
  70. package/dist/response.js.map +1 -0
  71. package/dist/schema.d.ts +45 -0
  72. package/dist/schema.d.ts.map +1 -0
  73. package/dist/schema.js +43 -0
  74. package/dist/schema.js.map +1 -0
  75. package/dist/services/main.d.ts +23 -0
  76. package/dist/services/main.d.ts.map +1 -0
  77. package/dist/services/main.js +43 -0
  78. package/dist/services/main.js.map +1 -0
  79. package/dist/sse.d.ts +58 -0
  80. package/dist/sse.d.ts.map +1 -0
  81. package/dist/sse.js +91 -0
  82. package/dist/sse.js.map +1 -0
  83. package/dist/testing/FakeProvider.d.ts +85 -0
  84. package/dist/testing/FakeProvider.d.ts.map +1 -0
  85. package/dist/testing/FakeProvider.js +213 -0
  86. package/dist/testing/FakeProvider.js.map +1 -0
  87. package/dist/testing/index.d.ts +7 -0
  88. package/dist/testing/index.d.ts.map +1 -0
  89. package/dist/testing/index.js +7 -0
  90. package/dist/testing/index.js.map +1 -0
  91. package/dist/tools.d.ts +68 -0
  92. package/dist/tools.d.ts.map +1 -0
  93. package/dist/tools.js +107 -0
  94. package/dist/tools.js.map +1 -0
  95. package/dist/transport.d.ts +18 -0
  96. package/dist/transport.d.ts.map +1 -0
  97. package/dist/transport.js +68 -0
  98. package/dist/transport.js.map +1 -0
  99. package/dist/types.d.ts +293 -0
  100. package/dist/types.d.ts.map +1 -0
  101. package/dist/types.js +12 -0
  102. package/dist/types.js.map +1 -0
  103. package/package.json +76 -3
  104. package/src/Polaris.ts +280 -0
  105. package/src/PolarisClient.ts +591 -0
  106. package/src/PolarisProvider.ts +73 -0
  107. package/src/augmentations.ts +17 -0
  108. package/src/budget.ts +101 -0
  109. package/src/cost.ts +170 -0
  110. package/src/drivers/anthropic.ts +520 -0
  111. package/src/drivers/openai-compatible.ts +840 -0
  112. package/src/drivers/status.ts +30 -0
  113. package/src/errors.ts +161 -0
  114. package/src/extract.ts +214 -0
  115. package/src/index.ts +69 -0
  116. package/src/log.ts +84 -0
  117. package/src/meter.ts +188 -0
  118. package/src/providers.ts +25 -0
  119. package/src/redact.ts +78 -0
  120. package/src/response.ts +65 -0
  121. package/src/schema.ts +88 -0
  122. package/src/services/main.ts +49 -0
  123. package/src/sse.ts +128 -0
  124. package/src/testing/FakeProvider.ts +321 -0
  125. package/src/testing/index.ts +12 -0
  126. package/src/tools.ts +166 -0
  127. package/src/transport.ts +85 -0
  128. package/src/types.ts +328 -0
package/src/budget.ts ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Spending limits per scope (a user, a tenant), enforced before a request is
3
+ * sent.
4
+ *
5
+ * A request reserves its estimated cost first: the reservation is added to
6
+ * the scope's spend, and if the total goes past the limit the reservation is
7
+ * taken back and the request refused, before anything leaves the server.
8
+ * Once the reply is in, the reservation is replaced by the real cost.
9
+ * Reserving rather than reading the spend is what keeps two requests sent at
10
+ * the same moment from passing the limit together.
11
+ */
12
+
13
+ import { add, exceeds, isZero, subtract } from "./cost.js";
14
+ import { E_POLARIS_BUDGET_EXCEEDED } from "./errors.js";
15
+
16
+ /**
17
+ * Where spend is kept. `add` must be atomic (a Redis `INCRBYFLOAT`, an SQL
18
+ * `UPDATE … SET spent = spent + ?`): it is what reservations rely on.
19
+ */
20
+ export interface BudgetStore {
21
+ /** Add `amount` (a decimal string, possibly negative) to `scope`, and answer the new total. */
22
+ add(scope: string, amount: string): Promise<string>;
23
+ }
24
+
25
+ export interface BudgetConfig {
26
+ /** The limit of a scope, as a decimal string in the pricing currency; `undefined` for none. */
27
+ readonly limit:
28
+ | { readonly [scope: string]: string }
29
+ | ((scope: string) => string | undefined | Promise<string | undefined>);
30
+ /** Where spend is kept. Default: in memory, for one process and its lifetime. */
31
+ readonly store?: BudgetStore;
32
+ }
33
+
34
+ /** A spend store in memory: one process, lost on restart. For tests and a single instance. */
35
+ export function memoryBudgetStore(): BudgetStore {
36
+ const spent = new Map<string, string>();
37
+ return {
38
+ async add(scope, amount) {
39
+ const total = add(spent.get(scope) ?? "0", amount);
40
+ spent.set(scope, total);
41
+ return total;
42
+ },
43
+ };
44
+ }
45
+
46
+ /** What a reservation hands back to settle it. */
47
+ export interface Reservation {
48
+ /** Replace the reservation by what the request really cost. */
49
+ settle(cost: string): Promise<void>;
50
+ /** Take the whole reservation back (the request was never answered). */
51
+ release(): Promise<void>;
52
+ }
53
+
54
+ const NOTHING: Reservation = {
55
+ settle: async () => undefined,
56
+ release: async () => undefined,
57
+ };
58
+
59
+ /** Resolve the limit of `scope`. */
60
+ export async function limitOf(
61
+ config: BudgetConfig,
62
+ scope: string,
63
+ ): Promise<string | undefined> {
64
+ return typeof config.limit === "function"
65
+ ? config.limit(scope)
66
+ : Object.hasOwn(config.limit, scope)
67
+ ? config.limit[scope]
68
+ : undefined;
69
+ }
70
+
71
+ /**
72
+ * Reserve `estimate` on `scope`, or refuse with `E_POLARIS_BUDGET_EXCEEDED`
73
+ * when that would go past `limit`. With no limit, nothing is reserved.
74
+ */
75
+ export async function reserve(
76
+ store: BudgetStore,
77
+ scope: string,
78
+ limit: string | undefined,
79
+ estimate: string,
80
+ ): Promise<Reservation> {
81
+ if (limit === undefined) return NOTHING;
82
+ const total = await store.add(scope, estimate);
83
+ if (exceeds(total, limit)) {
84
+ await store.add(scope, `-${estimate}`);
85
+ throw new E_POLARIS_BUDGET_EXCEEDED([scope, limit]);
86
+ }
87
+ let open = true;
88
+ return {
89
+ async settle(cost) {
90
+ if (!open) return;
91
+ open = false;
92
+ const difference = subtract(cost, estimate);
93
+ if (!isZero(difference)) await store.add(scope, difference);
94
+ },
95
+ async release() {
96
+ if (!open) return;
97
+ open = false;
98
+ await store.add(scope, `-${estimate}`);
99
+ },
100
+ };
101
+ }
package/src/cost.ts ADDED
@@ -0,0 +1,170 @@
1
+ /**
2
+ * What a request costs, computed exactly (atom decimals, never floats), from
3
+ * a price table the application declares.
4
+ */
5
+
6
+ import { type Decimal, decimal } from "@c9up/atom";
7
+ import { E_POLARIS_INVALID_CONFIG } from "./errors.js";
8
+ import type { ChatRequest, EmbedRequest, Usage } from "./types.js";
9
+
10
+ /**
11
+ * A model's prices, per million tokens, as decimal strings (`"4"`, `"0.40"`).
12
+ * Cache prices default to the input price.
13
+ */
14
+ export interface ModelPrice {
15
+ readonly input: string;
16
+ readonly output?: string;
17
+ readonly cacheRead?: string;
18
+ readonly cacheWrite?: string;
19
+ }
20
+
21
+ export interface Pricing {
22
+ /** The currency every price is in, written on every cost: `USD`, `CHF`… */
23
+ readonly currency: string;
24
+ /** Prices by model id, as the provider names it in its responses. */
25
+ readonly models: { readonly [model: string]: ModelPrice };
26
+ }
27
+
28
+ /** An amount of money, as an exact decimal string. */
29
+ export interface Cost {
30
+ readonly amount: string;
31
+ readonly currency: string;
32
+ }
33
+
34
+ const MILLION = 1_000_000;
35
+ /** Digits kept when a price per million is brought down to a token. */
36
+ const PRECISION = 18;
37
+ /** What an image weighs in an estimate, in input tokens. */
38
+ const IMAGE_TOKENS = 1_600;
39
+ /** Characters per token in an estimate: few, so the estimate errs high. */
40
+ const CHARS_PER_TOKEN = 3;
41
+
42
+ /** Check a price table once, at boot: every price a non-negative decimal. */
43
+ export function checkPricing(pricing: Pricing): void {
44
+ if (typeof pricing.currency !== "string" || pricing.currency.trim() === "") {
45
+ throw new E_POLARIS_INVALID_CONFIG(["pricing.currency is required"]);
46
+ }
47
+ for (const [model, price] of Object.entries(pricing.models)) {
48
+ for (const [field, value] of Object.entries(price)) {
49
+ if (value === undefined) continue;
50
+ const parsed = typeof value === "string" ? safe(value) : undefined;
51
+ if (parsed === undefined || parsed.isNegative()) {
52
+ throw new E_POLARIS_INVALID_CONFIG([
53
+ `pricing.models['${model}'].${field} must be a non-negative decimal string`,
54
+ ]);
55
+ }
56
+ }
57
+ }
58
+ }
59
+
60
+ /** The price of `model`, if the table has one. */
61
+ export function priceFor(
62
+ pricing: Pricing | undefined,
63
+ model: string | undefined,
64
+ ): ModelPrice | undefined {
65
+ if (pricing === undefined || model === undefined) return undefined;
66
+ return Object.hasOwn(pricing.models, model)
67
+ ? pricing.models[model]
68
+ : undefined;
69
+ }
70
+
71
+ /** What `usage` cost at `price`. */
72
+ export function costOf(price: ModelPrice, usage: Usage): string {
73
+ const cacheRead = price.cacheRead ?? price.input;
74
+ const cacheWrite = price.cacheWrite ?? price.input;
75
+ return decimal(usage.inputTokens)
76
+ .times(price.input)
77
+ .plus(decimal(usage.outputTokens).times(price.output ?? "0"))
78
+ .plus(decimal(usage.cacheReadTokens).times(cacheRead))
79
+ .plus(decimal(usage.cacheWriteTokens).times(cacheWrite))
80
+ .div(MILLION, { precision: PRECISION })
81
+ .toString();
82
+ }
83
+
84
+ /**
85
+ * The most a chat request can cost: its input estimated from its length (few
86
+ * characters per token, so the estimate errs high), and its output at the
87
+ * full `maxTokens`.
88
+ */
89
+ export function estimateChat(
90
+ price: ModelPrice,
91
+ request: ChatRequest,
92
+ maxTokens: number,
93
+ ): string {
94
+ return costOf(price, {
95
+ inputTokens: estimateTokens(request),
96
+ outputTokens: maxTokens,
97
+ cacheReadTokens: 0,
98
+ cacheWriteTokens: 0,
99
+ });
100
+ }
101
+
102
+ /** The most an embedding request can cost. */
103
+ export function estimateEmbed(
104
+ price: ModelPrice,
105
+ request: EmbedRequest,
106
+ ): string {
107
+ const characters = request.inputs.reduce(
108
+ (total, input) => total + input.length,
109
+ 0,
110
+ );
111
+ return costOf(price, {
112
+ inputTokens: Math.ceil(characters / CHARS_PER_TOKEN),
113
+ outputTokens: 0,
114
+ cacheReadTokens: 0,
115
+ cacheWriteTokens: 0,
116
+ });
117
+ }
118
+
119
+ function estimateTokens(request: ChatRequest): number {
120
+ let characters = (request.system ?? "").length;
121
+ let images = 0;
122
+ for (const message of request.messages) {
123
+ if (typeof message.content === "string") {
124
+ characters += message.content.length;
125
+ continue;
126
+ }
127
+ for (const part of message.content) {
128
+ if (part.type === "image") images += 1;
129
+ else if (part.type === "text" || part.type === "reasoning") {
130
+ characters += part.text.length;
131
+ } else if (part.type === "tool_result") characters += part.content.length;
132
+ else if (part.type === "tool_call") {
133
+ characters += JSON.stringify(part.input ?? null).length;
134
+ }
135
+ }
136
+ }
137
+ for (const tool of request.tools ?? []) {
138
+ characters += tool.name.length + tool.description.length;
139
+ characters += JSON.stringify(tool.inputSchema).length;
140
+ }
141
+ if (request.output !== undefined) {
142
+ characters += JSON.stringify(request.output.schema).length;
143
+ }
144
+ return Math.ceil(characters / CHARS_PER_TOKEN) + images * IMAGE_TOKENS;
145
+ }
146
+
147
+ /** Whether `a` is more than `b`, both decimal strings. */
148
+ export function exceeds(a: string, b: string): boolean {
149
+ return decimal(a).gt(b);
150
+ }
151
+
152
+ export function add(a: string, b: string): string {
153
+ return decimal(a).plus(b).toString();
154
+ }
155
+
156
+ export function subtract(a: string, b: string): string {
157
+ return decimal(a).minus(b).toString();
158
+ }
159
+
160
+ export function isZero(value: string): boolean {
161
+ return decimal(value).isZero();
162
+ }
163
+
164
+ function safe(value: string): Decimal | undefined {
165
+ try {
166
+ return decimal(value);
167
+ } catch {
168
+ return undefined;
169
+ }
170
+ }