@mupt-ai/dari-gateway 1.0.323 → 1.0.324

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.
@@ -20,6 +20,7 @@ import { providerIdentityFromModel } from "../interaction/provider_continuation_
20
20
  import { buildOptions, supportedThinkingLevels } from "./pi_options.js";
21
21
  import { eventsWithSafeguardResults, forwardsAnthropicSafeguards, messageWithSafeguardResults, safeguardResultsTap, } from "./anthropic_safeguards.js";
22
22
  import { anthropicWebSearchFor, eventsWithWebSearchResults, messageWithWebSearchResults, webSearchResultsTap, } from "./anthropic_web_search.js";
23
+ import { chargesWebSearch, eventsWithWebSearchFee, messageWithWebSearchFee, webSearchCountTap } from "./web_search_fee.js";
23
24
  import { eventsWithProviderReportedCost, messageWithProviderReportedCost, providerReportedCostTap, reportsProviderCost, } from "./provider_reported_cost.js";
24
25
  import { eventsWithSubscriptionCacheWrites, messageWithSubscriptionCacheWrites, modelPricingFromPiModel, } from "./subscription_usage.js";
25
26
  // Pi's built-in providers stream through these API implementations unchanged.
@@ -64,13 +65,17 @@ export async function completeInteractionModel(args) {
64
65
  const webSearch = anthropicWebSearchFor(args.request, model)
65
66
  ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
66
67
  : undefined;
67
- const options = buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, args.timeoutMs, args.signal, webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch);
68
+ const searchCount = chargesWebSearch(args.request)
69
+ ? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
70
+ : undefined;
71
+ const options = buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, args.timeoutMs, args.signal, searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch);
68
72
  const usageContext = subscriptionUsageContext(args.model, model, source);
69
73
  const message = options.emitProviderEvents === true
70
74
  ? await completeProviderEventStream(pi.streamSimple(model, context, options))
71
75
  : await pi.completeSimple(model, context, options);
72
76
  return {
73
- message: messageWithProviderReportedCost(messageWithSubscriptionCacheWrites(messageWithWebSearchResults(messageWithSafeguardResults(message, safeguards?.results()), webSearch?.results() ?? []), usageContext), costTap?.cost()),
77
+ // The search fee goes on last, over whatever cost the steps before set.
78
+ message: messageWithWebSearchFee(messageWithProviderReportedCost(messageWithSubscriptionCacheWrites(messageWithWebSearchResults(messageWithSafeguardResults(message, safeguards?.results()), webSearch?.results() ?? []), usageContext), costTap?.cost()), searchCount?.searches() ?? 0),
74
79
  source,
75
80
  };
76
81
  }
@@ -127,14 +132,18 @@ export async function streamInteractionModel(args) {
127
132
  const webSearch = anthropicWebSearchFor(args.request, model)
128
133
  ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
129
134
  : undefined;
130
- const events = pi.streamSimple(model, buildContext(args.request, source), buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, undefined, args.signal, webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch));
135
+ const searchCount = chargesWebSearch(args.request)
136
+ ? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
137
+ : undefined;
138
+ const events = pi.streamSimple(model, buildContext(args.request, source), buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, undefined, args.signal, searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch));
131
139
  const withSafeguardResults = safeguards ? eventsWithSafeguardResults(events, safeguards) : events;
132
140
  const withWebSearchResults = webSearch
133
141
  ? eventsWithWebSearchResults(withSafeguardResults, webSearch)
134
142
  : withSafeguardResults;
135
143
  const withCacheWrites = eventsWithSubscriptionCacheWrites(withWebSearchResults, subscriptionUsageContext(args.model, model, source));
144
+ const withReportedCost = costTap ? eventsWithProviderReportedCost(withCacheWrites, costTap) : withCacheWrites;
136
145
  return {
137
- events: costTap ? eventsWithProviderReportedCost(withCacheWrites, costTap) : withCacheWrites,
146
+ events: searchCount ? eventsWithWebSearchFee(withReportedCost, searchCount) : withReportedCost,
138
147
  source,
139
148
  };
140
149
  }
@@ -0,0 +1,11 @@
1
+ import type { InteractionRequest } from "../interaction/types.js";
2
+ import type { ProviderFetch } from "./response_capture.js";
3
+ export declare const WEB_SEARCH_USD_PER_SEARCH = 0.01;
4
+ export declare function chargesWebSearch(request: Pick<InteractionRequest, "tools" | "toolChoice" | "items">): boolean;
5
+ export type WebSearchCountTap = {
6
+ fetch: ProviderFetch;
7
+ searches: () => number;
8
+ };
9
+ export declare function webSearchCountTap(fetch?: ProviderFetch): WebSearchCountTap;
10
+ export declare function messageWithWebSearchFee(message: Record<string, unknown>, searches: number): Record<string, unknown>;
11
+ export declare function eventsWithWebSearchFee(events: AsyncIterable<Record<string, unknown>>, tap: WebSearchCountTap): AsyncIterable<Record<string, unknown>>;
@@ -0,0 +1,73 @@
1
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
+ import { requiredCapabilitiesFor } from "../interaction/capabilities.js";
3
+ import { sseEventScanner } from "./anthropic_safeguards.js";
4
+ // Anthropic and OpenAI charge for each web search on top of tokens: $10 per
5
+ // 1,000 searches, a search that fails is not charged.
6
+ // https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#usage-and-pricing
7
+ // https://developers.openai.com/api/docs/pricing
8
+ export const WEB_SEARCH_USD_PER_SEARCH = 0.01;
9
+ // Whether the request can make the provider run a web search it charges for.
10
+ export function chargesWebSearch(request) {
11
+ const capabilities = requiredCapabilitiesFor(request);
12
+ return capabilities.includes("anthropic_web_search") || capabilities.includes("openai_hosted_web_search");
13
+ }
14
+ // Counts the searches the provider charged for, from its own stream:
15
+ // Anthropic's usage reports them (`server_tool_use.web_search_requests`, the
16
+ // running total for the response), and OpenAI lists each completed
17
+ // `web_search_call`.
18
+ export function webSearchCountTap(fetch = globalThis.fetch) {
19
+ let anthropic = 0;
20
+ let openai = new Set();
21
+ return {
22
+ searches: () => anthropic + openai.size,
23
+ fetch: async (input, init) => {
24
+ const response = await fetch(input, init);
25
+ if (!response.ok || response.body === null)
26
+ return response;
27
+ anthropic = 0;
28
+ openai = new Set();
29
+ return new Response(response.body.pipeThrough(sseEventScanner("\"web_search", (event) => {
30
+ const usage = event.type === "message_delta" ? event.usage
31
+ : event.type === "message_start" && isRecord(event.message) ? event.message.usage
32
+ : undefined;
33
+ const requests = isRecord(usage) && isRecord(usage.server_tool_use)
34
+ ? usage.server_tool_use.web_search_requests
35
+ : undefined;
36
+ if (typeof requests === "number" && Number.isFinite(requests) && requests >= 0) {
37
+ anthropic = Math.max(anthropic, Math.trunc(requests));
38
+ }
39
+ const item = event.type === "response.output_item.done" ? event.item : undefined;
40
+ if (isRecord(item) && item.type === "web_search_call" && item.status === "completed" && typeof item.id === "string") {
41
+ openai.add(item.id);
42
+ }
43
+ })), { status: response.status, statusText: response.statusText, headers: response.headers });
44
+ },
45
+ };
46
+ }
47
+ // Adds the searches' fee to the message's cost, which is what a managed key
48
+ // is billed. Keys the customer owns and subscriptions are not billed here.
49
+ export function messageWithWebSearchFee(message, searches) {
50
+ if (searches <= 0 || !isRecord(message.usage) || !isRecord(message.usage.cost))
51
+ return message;
52
+ const cost = message.usage.cost;
53
+ const total = typeof cost.total === "number" && Number.isFinite(cost.total) ? cost.total : 0;
54
+ return {
55
+ ...message,
56
+ usage: { ...message.usage, cost: { ...cost, total: total + searches * WEB_SEARCH_USD_PER_SEARCH } },
57
+ };
58
+ }
59
+ // Aborted and failed calls end in an error event carrying the partial
60
+ // message; a search the provider completed before the end is still charged.
61
+ export async function* eventsWithWebSearchFee(events, tap) {
62
+ for await (const event of events) {
63
+ if (event.type === "done" && isRecord(event.message)) {
64
+ yield { ...event, message: messageWithWebSearchFee(event.message, tap.searches()) };
65
+ continue;
66
+ }
67
+ if (event.type === "error" && isRecord(event.error)) {
68
+ yield { ...event, error: messageWithWebSearchFee(event.error, tap.searches()) };
69
+ continue;
70
+ }
71
+ yield event;
72
+ }
73
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.323",
3
+ "version": "1.0.324",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-sts": "3.1063.0",
55
- "@mupt-ai/dari-router": "1.0.323",
55
+ "@mupt-ai/dari-router": "1.0.324",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.1"
57
57
  },
58
58
  "devDependencies": {
@@ -53,6 +53,7 @@ import {
53
53
  messageWithWebSearchResults,
54
54
  webSearchResultsTap,
55
55
  } from "./anthropic_web_search.js";
56
+ import { chargesWebSearch, eventsWithWebSearchFee, messageWithWebSearchFee, webSearchCountTap } from "./web_search_fee.js";
56
57
  import {
57
58
  eventsWithProviderReportedCost,
58
59
  messageWithProviderReportedCost,
@@ -161,6 +162,9 @@ export async function completeInteractionModel(args: {
161
162
  const webSearch = anthropicWebSearchFor(args.request, model)
162
163
  ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
163
164
  : undefined;
165
+ const searchCount = chargesWebSearch(args.request)
166
+ ? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
167
+ : undefined;
164
168
  const options = buildOptions(
165
169
  args.request,
166
170
  args.auth ?? args.apiKey,
@@ -171,22 +175,26 @@ export async function completeInteractionModel(args: {
171
175
  args.selectedReasoningEffort,
172
176
  args.timeoutMs,
173
177
  args.signal,
174
- webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
178
+ searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
175
179
  );
176
180
  const usageContext = subscriptionUsageContext(args.model, model, source);
177
181
  const message = options.emitProviderEvents === true
178
182
  ? await completeProviderEventStream(pi.streamSimple(model, context, options))
179
183
  : await pi.completeSimple(model, context, options);
180
184
  return {
181
- message: messageWithProviderReportedCost(
182
- messageWithSubscriptionCacheWrites(
183
- messageWithWebSearchResults(
184
- messageWithSafeguardResults(message, safeguards?.results()),
185
- webSearch?.results() ?? [],
185
+ // The search fee goes on last, over whatever cost the steps before set.
186
+ message: messageWithWebSearchFee(
187
+ messageWithProviderReportedCost(
188
+ messageWithSubscriptionCacheWrites(
189
+ messageWithWebSearchResults(
190
+ messageWithSafeguardResults(message, safeguards?.results()),
191
+ webSearch?.results() ?? [],
192
+ ),
193
+ usageContext
186
194
  ),
187
- usageContext
195
+ costTap?.cost(),
188
196
  ),
189
- costTap?.cost(),
197
+ searchCount?.searches() ?? 0,
190
198
  ),
191
199
  source,
192
200
  };
@@ -266,6 +274,9 @@ export async function streamInteractionModel(args: {
266
274
  const webSearch = anthropicWebSearchFor(args.request, model)
267
275
  ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
268
276
  : undefined;
277
+ const searchCount = chargesWebSearch(args.request)
278
+ ? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
279
+ : undefined;
269
280
  const events = pi.streamSimple(
270
281
  model,
271
282
  buildContext(args.request, source),
@@ -279,7 +290,7 @@ export async function streamInteractionModel(args: {
279
290
  args.selectedReasoningEffort,
280
291
  undefined,
281
292
  args.signal,
282
- webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
293
+ searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
283
294
  )
284
295
  );
285
296
  const withSafeguardResults = safeguards ? eventsWithSafeguardResults(events, safeguards) : events;
@@ -290,8 +301,9 @@ export async function streamInteractionModel(args: {
290
301
  withWebSearchResults,
291
302
  subscriptionUsageContext(args.model, model, source)
292
303
  );
304
+ const withReportedCost = costTap ? eventsWithProviderReportedCost(withCacheWrites, costTap) : withCacheWrites;
293
305
  return {
294
- events: costTap ? eventsWithProviderReportedCost(withCacheWrites, costTap) : withCacheWrites,
306
+ events: searchCount ? eventsWithWebSearchFee(withReportedCost, searchCount) : withReportedCost,
295
307
  source,
296
308
  };
297
309
  }
@@ -0,0 +1,93 @@
1
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
+
3
+ import { requiredCapabilitiesFor } from "../interaction/capabilities.js";
4
+ import type { InteractionRequest } from "../interaction/types.js";
5
+ import { sseEventScanner } from "./anthropic_safeguards.js";
6
+ import type { ProviderFetch } from "./response_capture.js";
7
+
8
+ // Anthropic and OpenAI charge for each web search on top of tokens: $10 per
9
+ // 1,000 searches, a search that fails is not charged.
10
+ // https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#usage-and-pricing
11
+ // https://developers.openai.com/api/docs/pricing
12
+ export const WEB_SEARCH_USD_PER_SEARCH = 0.01;
13
+
14
+ // Whether the request can make the provider run a web search it charges for.
15
+ export function chargesWebSearch(request: Pick<InteractionRequest, "tools" | "toolChoice" | "items">): boolean {
16
+ const capabilities = requiredCapabilitiesFor(request);
17
+ return capabilities.includes("anthropic_web_search") || capabilities.includes("openai_hosted_web_search");
18
+ }
19
+
20
+ export type WebSearchCountTap = {
21
+ fetch: ProviderFetch;
22
+ searches: () => number;
23
+ };
24
+
25
+ // Counts the searches the provider charged for, from its own stream:
26
+ // Anthropic's usage reports them (`server_tool_use.web_search_requests`, the
27
+ // running total for the response), and OpenAI lists each completed
28
+ // `web_search_call`.
29
+ export function webSearchCountTap(fetch: ProviderFetch = globalThis.fetch): WebSearchCountTap {
30
+ let anthropic = 0;
31
+ let openai = new Set<string>();
32
+ return {
33
+ searches: () => anthropic + openai.size,
34
+ fetch: async (input, init) => {
35
+ const response = await fetch(input, init);
36
+ if (!response.ok || response.body === null) return response;
37
+ anthropic = 0;
38
+ openai = new Set();
39
+ return new Response(
40
+ response.body.pipeThrough(sseEventScanner("\"web_search", (event) => {
41
+ const usage = event.type === "message_delta" ? event.usage
42
+ : event.type === "message_start" && isRecord(event.message) ? event.message.usage
43
+ : undefined;
44
+ const requests = isRecord(usage) && isRecord(usage.server_tool_use)
45
+ ? usage.server_tool_use.web_search_requests
46
+ : undefined;
47
+ if (typeof requests === "number" && Number.isFinite(requests) && requests >= 0) {
48
+ anthropic = Math.max(anthropic, Math.trunc(requests));
49
+ }
50
+ const item = event.type === "response.output_item.done" ? event.item : undefined;
51
+ if (isRecord(item) && item.type === "web_search_call" && item.status === "completed" && typeof item.id === "string") {
52
+ openai.add(item.id);
53
+ }
54
+ })),
55
+ { status: response.status, statusText: response.statusText, headers: response.headers },
56
+ );
57
+ },
58
+ };
59
+ }
60
+
61
+ // Adds the searches' fee to the message's cost, which is what a managed key
62
+ // is billed. Keys the customer owns and subscriptions are not billed here.
63
+ export function messageWithWebSearchFee(
64
+ message: Record<string, unknown>,
65
+ searches: number,
66
+ ): Record<string, unknown> {
67
+ if (searches <= 0 || !isRecord(message.usage) || !isRecord(message.usage.cost)) return message;
68
+ const cost = message.usage.cost;
69
+ const total = typeof cost.total === "number" && Number.isFinite(cost.total) ? cost.total : 0;
70
+ return {
71
+ ...message,
72
+ usage: { ...message.usage, cost: { ...cost, total: total + searches * WEB_SEARCH_USD_PER_SEARCH } },
73
+ };
74
+ }
75
+
76
+ // Aborted and failed calls end in an error event carrying the partial
77
+ // message; a search the provider completed before the end is still charged.
78
+ export async function* eventsWithWebSearchFee(
79
+ events: AsyncIterable<Record<string, unknown>>,
80
+ tap: WebSearchCountTap,
81
+ ): AsyncIterable<Record<string, unknown>> {
82
+ for await (const event of events) {
83
+ if (event.type === "done" && isRecord(event.message)) {
84
+ yield { ...event, message: messageWithWebSearchFee(event.message, tap.searches()) };
85
+ continue;
86
+ }
87
+ if (event.type === "error" && isRecord(event.error)) {
88
+ yield { ...event, error: messageWithWebSearchFee(event.error, tap.searches()) };
89
+ continue;
90
+ }
91
+ yield event;
92
+ }
93
+ }