@nevermined-io/payments 1.0.0-rc13 → 1.0.0-rc15
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/README.md +1 -1
- package/dist/api/base-payments.d.ts +8 -4
- package/dist/api/base-payments.d.ts.map +1 -1
- package/dist/api/base-payments.js +7 -3
- package/dist/api/base-payments.js.map +1 -1
- package/dist/api/observability-api.d.ts +31 -17
- package/dist/api/observability-api.d.ts.map +1 -1
- package/dist/api/observability-api.js +47 -54
- package/dist/api/observability-api.js.map +1 -1
- package/dist/common/types.d.ts +5 -0
- package/dist/common/types.d.ts.map +1 -1
- package/dist/common/types.js.map +1 -1
- package/dist/mcp/core/paywall.d.ts.map +1 -1
- package/dist/mcp/core/paywall.js +32 -8
- package/dist/mcp/core/paywall.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -187,7 +187,7 @@ const result = await payments.agents.registerAgent(agentMetadata, agentApi, paym
|
|
|
187
187
|
const orderResult = await payments.plans.orderPlan(creditsPlanId)
|
|
188
188
|
```
|
|
189
189
|
|
|
190
|
-
And get the
|
|
190
|
+
And get the balance of the purchased plan:
|
|
191
191
|
|
|
192
192
|
```typescript
|
|
193
193
|
const balance = await payments.plans.getPlanBalance(creditsPlanId)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { EnvironmentInfo } from '../environments.js';
|
|
1
|
+
import { EnvironmentInfo, EnvironmentName } from '../environments.js';
|
|
2
2
|
import { PaymentOptions } from '../common/types.js';
|
|
3
3
|
/**
|
|
4
4
|
* Base class extended by all Payments API classes.
|
|
@@ -7,18 +7,22 @@ import { PaymentOptions } from '../common/types.js';
|
|
|
7
7
|
export declare abstract class BasePaymentsAPI {
|
|
8
8
|
protected nvmApiKey: string;
|
|
9
9
|
protected environment: EnvironmentInfo;
|
|
10
|
+
protected environmentName: EnvironmentName;
|
|
10
11
|
protected returnUrl: string;
|
|
11
12
|
protected appId?: string;
|
|
12
13
|
protected version?: string;
|
|
13
|
-
protected accountAddress
|
|
14
|
-
protected heliconeApiKey
|
|
14
|
+
protected accountAddress: string;
|
|
15
|
+
protected heliconeApiKey: string;
|
|
15
16
|
isBrowserInstance: boolean;
|
|
16
17
|
constructor(options: PaymentOptions);
|
|
17
18
|
/**
|
|
18
19
|
* Parses the NVM API Key to extract the account address.
|
|
19
20
|
* @throws PaymentsError if the API key is invalid.
|
|
20
21
|
*/
|
|
21
|
-
protected parseNvmApiKey():
|
|
22
|
+
protected parseNvmApiKey(): {
|
|
23
|
+
accountAddress: string;
|
|
24
|
+
heliconeApiKey: string;
|
|
25
|
+
};
|
|
22
26
|
/**
|
|
23
27
|
* It returns the account address associated with the NVM API Key used to initialize the Payments Library instance.
|
|
24
28
|
* @returns The account address extracted from the NVM API Key
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-payments.d.ts","sourceRoot":"","sources":["../../src/api/base-payments.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,
|
|
1
|
+
{"version":3,"file":"base-payments.d.ts","sourceRoot":"","sources":["../../src/api/base-payments.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,eAAe,EAAgB,MAAM,oBAAoB,CAAA;AACnF,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAInD;;;GAGG;AACH,8BAAsB,eAAe;IACnC,SAAS,CAAC,SAAS,EAAE,MAAM,CAAA;IAC3B,SAAS,CAAC,WAAW,EAAE,eAAe,CAAA;IACtC,SAAS,CAAC,eAAe,EAAE,eAAe,CAAA;IAC1C,SAAS,CAAC,SAAS,EAAE,MAAM,CAAA;IAC3B,SAAS,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IACxB,SAAS,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IAC1B,SAAS,CAAC,cAAc,EAAE,MAAM,CAAA;IAChC,SAAS,CAAC,cAAc,EAAE,MAAM,CAAA;IACzB,iBAAiB,UAAO;gBAEnB,OAAO,EAAE,cAAc;IAYnC;;;OAGG;IACH,SAAS,CAAC,cAAc,IAAI;QAAE,cAAc,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAA;KAAE;IAc9E;;;OAGG;IACI,iBAAiB,IAAI,MAAM,GAAG,SAAS;IAI9C;;;;;;OAMG;IACH,SAAS,CAAC,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG;CAW3D"}
|
|
@@ -12,9 +12,12 @@ export class BasePaymentsAPI {
|
|
|
12
12
|
this.nvmApiKey = options.nvmApiKey;
|
|
13
13
|
this.returnUrl = options.returnUrl || '';
|
|
14
14
|
this.environment = Environments[options.environment];
|
|
15
|
+
this.environmentName = options.environment;
|
|
15
16
|
this.appId = options.appId;
|
|
16
17
|
this.version = options.version;
|
|
17
|
-
this.parseNvmApiKey();
|
|
18
|
+
const { accountAddress, heliconeApiKey } = this.parseNvmApiKey();
|
|
19
|
+
this.accountAddress = accountAddress;
|
|
20
|
+
this.heliconeApiKey = heliconeApiKey;
|
|
18
21
|
}
|
|
19
22
|
/**
|
|
20
23
|
* Parses the NVM API Key to extract the account address.
|
|
@@ -26,8 +29,9 @@ export class BasePaymentsAPI {
|
|
|
26
29
|
throw new PaymentsError('NVM API Key is required');
|
|
27
30
|
}
|
|
28
31
|
const jwt = decodeJwt(this.nvmApiKey);
|
|
29
|
-
|
|
30
|
-
|
|
32
|
+
const accountAddress = jwt.sub;
|
|
33
|
+
const heliconeApiKey = jwt.o11y;
|
|
34
|
+
return { accountAddress, heliconeApiKey };
|
|
31
35
|
}
|
|
32
36
|
catch (error) {
|
|
33
37
|
throw new PaymentsError('Invalid NVM API Key');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-payments.js","sourceRoot":"","sources":["../../src/api/base-payments.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAoC,YAAY,E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YACD,MAAM,GAAG,GAAG,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;YACrC,MAAM,cAAc,GAAG,GAAG,CAAC,GAAa,CAAA;YACxC,MAAM,cAAc,GAAG,GAAG,CAAC,IAAc,CAAA;YACzC,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,CAAA;QAC3C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,aAAa,CAAC,qBAAqB,CAAC,CAAA;QAChD,CAAC;IACH,CAAC;IAED;;;OAGG;IACI,iBAAiB;QACtB,OAAO,IAAI,CAAC,cAAc,CAAA;IAC5B,CAAC;IAED;;;;;;OAMG;IACO,qBAAqB,CAAC,MAAc,EAAE,IAAU;QACxD,OAAO;YACL,MAAM;YACN,OAAO,EAAE;gBACP,MAAM,EAAE,kBAAkB;gBAC1B,cAAc,EAAE,kBAAkB;gBAClC,aAAa,EAAE,UAAU,IAAI,CAAC,SAAS,EAAE;aAC1C;YACD,GAAG,CAAC,IAAI,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,YAAY,CAAC,EAAE,CAAC;SAC1D,CAAA;IACH,CAAC;CACF","sourcesContent":["import { jsonReplacer } from '../common/helper.js'\nimport { EnvironmentInfo, EnvironmentName, Environments } from '../environments.js'\nimport { PaymentOptions } from '../common/types.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport { decodeJwt } from 'jose'\n\n/**\n * Base class extended by all Payments API classes.\n * It provides common functionality such as parsing the NVM API Key and getting the account address.\n */\nexport abstract class BasePaymentsAPI {\n protected nvmApiKey: string\n protected environment: EnvironmentInfo\n protected environmentName: EnvironmentName\n protected returnUrl: string\n protected appId?: string\n protected version?: string\n protected accountAddress: string\n protected heliconeApiKey: string\n public isBrowserInstance = true\n\n constructor(options: PaymentOptions) {\n this.nvmApiKey = options.nvmApiKey\n this.returnUrl = options.returnUrl || ''\n this.environment = Environments[options.environment as EnvironmentName]\n this.environmentName = options.environment\n this.appId = options.appId\n this.version = options.version\n const { accountAddress, heliconeApiKey } = this.parseNvmApiKey()\n this.accountAddress = accountAddress\n this.heliconeApiKey = heliconeApiKey\n }\n\n /**\n * Parses the NVM API Key to extract the account address.\n * @throws PaymentsError if the API key is invalid.\n */\n protected parseNvmApiKey(): { accountAddress: string; heliconeApiKey: string } {\n try {\n if (!this.nvmApiKey) {\n throw new PaymentsError('NVM API Key is required')\n }\n const jwt = decodeJwt(this.nvmApiKey)\n const accountAddress = jwt.sub as string\n const heliconeApiKey = jwt.o11y as string\n return { accountAddress, heliconeApiKey }\n } catch (error) {\n throw new PaymentsError('Invalid NVM API Key')\n }\n }\n\n /**\n * It returns the account address associated with the NVM API Key used to initialize the Payments Library instance.\n * @returns The account address extracted from the NVM API Key\n */\n public getAccountAddress(): string | undefined {\n return this.accountAddress\n }\n\n /**\n * Returns the HTTP options required to query the backend.\n * @param method - HTTP method.\n * @param body - Optional request body.\n * @returns HTTP options object.\n * @internal\n */\n protected getBackendHTTPOptions(method: string, body?: any) {\n return {\n method,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.nvmApiKey}`,\n },\n ...(body && { body: JSON.stringify(body, jsonReplacer) }),\n }\n }\n}\n"]}
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
* Provides reusable utilities for wrapping API calls with Helicone logging for AI agents
|
|
4
4
|
*/
|
|
5
5
|
import { BasePaymentsAPI } from './base-payments.js';
|
|
6
|
-
import { PaymentOptions } from '../common/types.js';
|
|
6
|
+
import { PaymentOptions, StartAgentRequest } from '../common/types.js';
|
|
7
|
+
import { EnvironmentName } from '../environments.js';
|
|
7
8
|
/**
|
|
8
9
|
* Configuration for creating a Helicone payload
|
|
9
10
|
*/
|
|
@@ -41,14 +42,21 @@ export interface HeliconeResponseConfig {
|
|
|
41
42
|
};
|
|
42
43
|
systemFingerprint?: string;
|
|
43
44
|
}
|
|
44
|
-
export type CustomProperties =
|
|
45
|
-
|
|
46
|
-
sessionid: string;
|
|
47
|
-
} & Record<string, string | number>;
|
|
48
|
-
export type DefaultHeliconeHeaders = {
|
|
45
|
+
export type CustomProperties = Record<string, string>;
|
|
46
|
+
export type NeverminedHeliconeHeaders = {
|
|
49
47
|
'Helicone-Auth': string;
|
|
50
48
|
'Helicone-Property-accountAddress': string;
|
|
51
|
-
|
|
49
|
+
'Helicone-Property-consumerAddress': string;
|
|
50
|
+
'Helicone-Property-agentId': string;
|
|
51
|
+
'Helicone-Property-planId': string;
|
|
52
|
+
'Helicone-Property-planType': string;
|
|
53
|
+
'Helicone-Property-planName': string;
|
|
54
|
+
'Helicone-Property-agentName': string;
|
|
55
|
+
'Helicone-Property-agentRequestId': string;
|
|
56
|
+
'Helicone-Property-pricePerCredit': string;
|
|
57
|
+
'Helicone-Property-environmentName': string;
|
|
58
|
+
};
|
|
59
|
+
export type DefaultHeliconeHeaders = NeverminedHeliconeHeaders & CustomProperties;
|
|
52
60
|
export type ChatOpenAIConfiguration = {
|
|
53
61
|
model: string;
|
|
54
62
|
apiKey: string;
|
|
@@ -150,30 +158,34 @@ export declare function calculateDummySongUsage(): HeliconeResponseConfig['usage
|
|
|
150
158
|
/**
|
|
151
159
|
* Creates a ChatOpenAI configuration with Helicone logging enabled
|
|
152
160
|
*
|
|
153
|
-
* Usage: const llm = new ChatOpenAI(withHeliconeLangchain("gpt-4o-mini", apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, customProperties));
|
|
161
|
+
* Usage: const llm = new ChatOpenAI(withHeliconeLangchain("gpt-4o-mini", apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, agentRequest, customProperties));
|
|
154
162
|
*
|
|
155
163
|
* @param model - The OpenAI model to use (e.g., "gpt-4o-mini", "gpt-4")
|
|
156
164
|
* @param apiKey - The OpenAI API key
|
|
157
165
|
* @param heliconeApiKey - The Helicone API key for logging
|
|
158
166
|
* @param heliconeBaseLoggingUrl - The Helicone base logging endpoint URL
|
|
159
167
|
* @param accountAddress - The account address for logging purposes
|
|
160
|
-
* @param
|
|
168
|
+
* @param environmentName - The environment name for logging purposes
|
|
169
|
+
* @param agentRequest - The agent request for logging purposes
|
|
170
|
+
* @param customProperties - Custom properties to add as Helicone headers
|
|
161
171
|
* @returns Configuration object for ChatOpenAI constructor with Helicone enabled
|
|
162
172
|
*/
|
|
163
|
-
export declare function withHeliconeLangchain(model: string, apiKey: string, heliconeApiKey: string, heliconeBaseLoggingUrl: string, accountAddress: string, customProperties: CustomProperties): ChatOpenAIConfiguration;
|
|
173
|
+
export declare function withHeliconeLangchain(model: string, apiKey: string, heliconeApiKey: string, heliconeBaseLoggingUrl: string, accountAddress: string, environmentName: EnvironmentName, agentRequest: StartAgentRequest, customProperties: CustomProperties): ChatOpenAIConfiguration;
|
|
164
174
|
/**
|
|
165
175
|
* Creates an OpenAI client configuration with Helicone logging enabled
|
|
166
176
|
*
|
|
167
|
-
* Usage: const openai = new OpenAI(withHeliconeOpenAI(apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, customProperties));
|
|
177
|
+
* Usage: const openai = new OpenAI(withHeliconeOpenAI(apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, agentRequest, customProperties));
|
|
168
178
|
*
|
|
169
179
|
* @param apiKey - The OpenAI API key
|
|
170
180
|
* @param heliconeApiKey - The Helicone API key for logging
|
|
171
181
|
* @param heliconeBaseLoggingUrl - The Helicone base logging endpoint URL
|
|
172
182
|
* @param accountAddress - The account address for logging purposes
|
|
173
|
-
* @param
|
|
183
|
+
* @param environmentName - The environment name for logging purposes
|
|
184
|
+
* @param agentRequest - The agent request for logging purposes
|
|
185
|
+
* @param customProperties - Custom properties to add as Helicone headers
|
|
174
186
|
* @returns Configuration object for OpenAI constructor with Helicone enabled
|
|
175
187
|
*/
|
|
176
|
-
export declare function withHeliconeOpenAI(apiKey: string, heliconeApiKey: string, heliconeBaseLoggingUrl: string, accountAddress: string, customProperties: CustomProperties): OpenAIConfiguration;
|
|
188
|
+
export declare function withHeliconeOpenAI(apiKey: string, heliconeApiKey: string, heliconeBaseLoggingUrl: string, accountAddress: string, environmentName: EnvironmentName, agentRequest: StartAgentRequest, customProperties: CustomProperties): OpenAIConfiguration;
|
|
177
189
|
/**
|
|
178
190
|
* The ObservabilityAPI class provides methods to wrap API calls with Helicone logging
|
|
179
191
|
*/
|
|
@@ -204,25 +216,27 @@ export declare class ObservabilityAPI extends BasePaymentsAPI {
|
|
|
204
216
|
/**
|
|
205
217
|
* Creates a ChatOpenAI configuration with Helicone logging enabled
|
|
206
218
|
*
|
|
207
|
-
* Usage: const llm = new ChatOpenAI(observability.withHeliconeLangchain("gpt-4o-mini", apiKey, customProperties));
|
|
219
|
+
* Usage: const llm = new ChatOpenAI(observability.withHeliconeLangchain("gpt-4o-mini", apiKey, agentRequest, customProperties));
|
|
208
220
|
*
|
|
209
221
|
* @param model - The OpenAI model to use (e.g., "gpt-4o-mini", "gpt-4")
|
|
210
222
|
* @param apiKey - The OpenAI API key
|
|
223
|
+
* @param agentRequest - The agent request for logging purposes
|
|
211
224
|
* @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)
|
|
212
225
|
* @returns Configuration object for ChatOpenAI constructor with Helicone enabled
|
|
213
226
|
*/
|
|
214
|
-
withHeliconeLangchain(model: string, apiKey: string, customProperties: CustomProperties): ChatOpenAIConfiguration;
|
|
227
|
+
withHeliconeLangchain(model: string, apiKey: string, startAgentRequest: StartAgentRequest, customProperties: CustomProperties): ChatOpenAIConfiguration;
|
|
215
228
|
/**
|
|
216
229
|
* Creates an OpenAI client configuration with Helicone logging enabled
|
|
217
230
|
*
|
|
218
|
-
* Usage: const openai = new OpenAI(observability.withHeliconeOpenAI(apiKey, heliconeApiKey, customProperties));
|
|
231
|
+
* Usage: const openai = new OpenAI(observability.withHeliconeOpenAI(apiKey, heliconeApiKey, agentRequest, customProperties));
|
|
219
232
|
*
|
|
220
233
|
* @param apiKey - The OpenAI API key
|
|
221
234
|
* @param heliconeApiKey - The Helicone API key for logging
|
|
235
|
+
* @param agentRequest - The agent request for logging purposes
|
|
222
236
|
* @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)
|
|
223
237
|
* @returns Configuration object for OpenAI constructor with Helicone enabled
|
|
224
238
|
*/
|
|
225
|
-
withHeliconeOpenAI(apiKey: string, customProperties: CustomProperties): OpenAIConfiguration;
|
|
239
|
+
withHeliconeOpenAI(apiKey: string, agentRequest: StartAgentRequest, customProperties: CustomProperties): OpenAIConfiguration;
|
|
226
240
|
/**
|
|
227
241
|
* Helper function to calculate usage for image operations based on pixels
|
|
228
242
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"observability-api.d.ts","sourceRoot":"","sources":["../../src/api/observability-api.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;
|
|
1
|
+
{"version":3,"file":"observability-api.d.ts","sourceRoot":"","sources":["../../src/api/observability-api.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACpD,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AACtE,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAEpD;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,KAAK,EAAE,MAAM,CAAA;IACb,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC9B,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,CAAC,CAAC,EAAE,MAAM,CAAA;IACV,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB;AAED;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AM,EACb,MAAM,EAAE,MAAM,EACd,iBAAiB,EAAE,iBAAiB,EACpC,gBAAgB,EAAE,gBAAgB,GACjC,uBAAuB;IAa1B;;;;;;;;;;OAUG;IACH,kBAAkB,CAChB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,iBAAiB,EAC/B,gBAAgB,EAAE,gBAAgB,GACjC,mBAAmB;IAYtB;;OAEG;IACH,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,sBAAsB,CAAC,OAAO,CAAC;IAIpE;;OAEG;IACH,mBAAmB,IAAI,sBAAsB,CAAC,OAAO,CAAC;IAItD;;OAEG;IACH,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,sBAAsB,CAAC,OAAO,CAAC;IAInE;;OAEG;IACH,uBAAuB,IAAI,sBAAsB,CAAC,OAAO,CAAC;IAI1D;;OAEG;IACH,qBAAqB,CAAC,MAAM,EAAE,qBAAqB;;;;;;;;;;;;;IAInD;;OAEG;IACH,sBAAsB,CAAC,MAAM,EAAE,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAGtD"}
|
|
@@ -5,6 +5,31 @@
|
|
|
5
5
|
import { HeliconeManualLogger } from '@helicone/helpers';
|
|
6
6
|
import { generateDeterministicAgentId, generateSessionId, logSessionInfo } from '../utils.js';
|
|
7
7
|
import { BasePaymentsAPI } from './base-payments.js';
|
|
8
|
+
function getDefaultHeliconeHeaders(heliconeApiKey, accountAddress, environmentName, agentRequest, customProperties) {
|
|
9
|
+
const neverminedHeliconeHeaders = {
|
|
10
|
+
'Helicone-Auth': `Bearer ${heliconeApiKey}`,
|
|
11
|
+
'Helicone-Property-accountAddress': accountAddress,
|
|
12
|
+
'Helicone-Property-consumerAddress': agentRequest.balance.holderAddress,
|
|
13
|
+
'Helicone-Property-agentId': agentRequest.agentId,
|
|
14
|
+
'Helicone-Property-planId': agentRequest.balance.planId,
|
|
15
|
+
'Helicone-Property-planType': agentRequest.balance.planType,
|
|
16
|
+
'Helicone-Property-planName': agentRequest.balance.planName,
|
|
17
|
+
'Helicone-Property-agentName': agentRequest.agentName,
|
|
18
|
+
'Helicone-Property-agentRequestId': agentRequest.agentRequestId,
|
|
19
|
+
'Helicone-Property-pricePerCredit': agentRequest.balance.pricePerCredit.toString(),
|
|
20
|
+
'Helicone-Property-environmentName': environmentName,
|
|
21
|
+
};
|
|
22
|
+
// Build custom property headers from all properties
|
|
23
|
+
const customHeaders = {};
|
|
24
|
+
for (const [key, value] of Object.entries(customProperties)) {
|
|
25
|
+
// Convert property names to Helicone-Property format
|
|
26
|
+
customHeaders[`Helicone-Property-${key}`] = value;
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
...neverminedHeliconeHeaders,
|
|
30
|
+
...customHeaders,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
8
33
|
/**
|
|
9
34
|
* Creates a standardized Helicone payload for API logging
|
|
10
35
|
*/
|
|
@@ -195,84 +220,50 @@ export function calculateDummySongUsage() {
|
|
|
195
220
|
/**
|
|
196
221
|
* Creates a ChatOpenAI configuration with Helicone logging enabled
|
|
197
222
|
*
|
|
198
|
-
* Usage: const llm = new ChatOpenAI(withHeliconeLangchain("gpt-4o-mini", apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, customProperties));
|
|
223
|
+
* Usage: const llm = new ChatOpenAI(withHeliconeLangchain("gpt-4o-mini", apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, agentRequest, customProperties));
|
|
199
224
|
*
|
|
200
225
|
* @param model - The OpenAI model to use (e.g., "gpt-4o-mini", "gpt-4")
|
|
201
226
|
* @param apiKey - The OpenAI API key
|
|
202
227
|
* @param heliconeApiKey - The Helicone API key for logging
|
|
203
228
|
* @param heliconeBaseLoggingUrl - The Helicone base logging endpoint URL
|
|
204
229
|
* @param accountAddress - The account address for logging purposes
|
|
205
|
-
* @param
|
|
230
|
+
* @param environmentName - The environment name for logging purposes
|
|
231
|
+
* @param agentRequest - The agent request for logging purposes
|
|
232
|
+
* @param customProperties - Custom properties to add as Helicone headers
|
|
206
233
|
* @returns Configuration object for ChatOpenAI constructor with Helicone enabled
|
|
207
234
|
*/
|
|
208
|
-
export function withHeliconeLangchain(model, apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, customProperties) {
|
|
209
|
-
|
|
210
|
-
const agentId = customProperties.agentid
|
|
211
|
-
? String(customProperties.agentid)
|
|
212
|
-
: generateDeterministicAgentId('');
|
|
213
|
-
const sessionId = customProperties.sessionid
|
|
214
|
-
? String(customProperties.sessionid)
|
|
215
|
-
: generateSessionId();
|
|
216
|
-
// Log session info if these weren't provided in custom properties
|
|
217
|
-
if (!customProperties.agentid || !customProperties.sessionid) {
|
|
218
|
-
logSessionInfo(agentId, sessionId, 'LangChainChatOpenAI');
|
|
219
|
-
}
|
|
220
|
-
// Build custom property headers from all properties
|
|
221
|
-
const customHeaders = {};
|
|
222
|
-
for (const [key, value] of Object.entries(customProperties)) {
|
|
223
|
-
// Convert property names to Helicone-Property format and ensure string values
|
|
224
|
-
customHeaders[`Helicone-Property-${key}`] = String(value);
|
|
225
|
-
}
|
|
235
|
+
export function withHeliconeLangchain(model, apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, environmentName, agentRequest, customProperties) {
|
|
236
|
+
const defaultHeaders = getDefaultHeliconeHeaders(heliconeApiKey, accountAddress, environmentName, agentRequest, customProperties);
|
|
226
237
|
return {
|
|
227
238
|
model,
|
|
228
239
|
apiKey,
|
|
229
240
|
configuration: {
|
|
230
241
|
baseURL: heliconeBaseLoggingUrl,
|
|
231
|
-
defaultHeaders
|
|
232
|
-
'Helicone-Auth': `Bearer ${heliconeApiKey}`,
|
|
233
|
-
'Helicone-Property-accountAddress': accountAddress,
|
|
234
|
-
...customHeaders,
|
|
235
|
-
},
|
|
242
|
+
defaultHeaders,
|
|
236
243
|
},
|
|
237
244
|
};
|
|
238
245
|
}
|
|
239
246
|
/**
|
|
240
247
|
* Creates an OpenAI client configuration with Helicone logging enabled
|
|
241
248
|
*
|
|
242
|
-
* Usage: const openai = new OpenAI(withHeliconeOpenAI(apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, customProperties));
|
|
249
|
+
* Usage: const openai = new OpenAI(withHeliconeOpenAI(apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, agentRequest, customProperties));
|
|
243
250
|
*
|
|
244
251
|
* @param apiKey - The OpenAI API key
|
|
245
252
|
* @param heliconeApiKey - The Helicone API key for logging
|
|
246
253
|
* @param heliconeBaseLoggingUrl - The Helicone base logging endpoint URL
|
|
247
254
|
* @param accountAddress - The account address for logging purposes
|
|
248
|
-
* @param
|
|
255
|
+
* @param environmentName - The environment name for logging purposes
|
|
256
|
+
* @param agentRequest - The agent request for logging purposes
|
|
257
|
+
* @param customProperties - Custom properties to add as Helicone headers
|
|
249
258
|
* @returns Configuration object for OpenAI constructor with Helicone enabled
|
|
250
259
|
*/
|
|
251
|
-
export function withHeliconeOpenAI(apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, customProperties) {
|
|
252
|
-
|
|
253
|
-
const agentId = customProperties.agentid
|
|
254
|
-
? String(customProperties.agentid)
|
|
255
|
-
: generateDeterministicAgentId('');
|
|
256
|
-
const sessionId = customProperties.sessionid
|
|
257
|
-
? String(customProperties.sessionid)
|
|
258
|
-
: generateSessionId();
|
|
259
|
-
// Log session info if these weren't provided in custom properties
|
|
260
|
-
if (!customProperties.agentid || !customProperties.sessionid) {
|
|
261
|
-
logSessionInfo(agentId, sessionId, 'OpenAI');
|
|
262
|
-
}
|
|
263
|
-
// Build custom property headers from all properties
|
|
264
|
-
const customHeaders = {};
|
|
265
|
-
for (const [key, value] of Object.entries(customProperties)) {
|
|
266
|
-
// Convert property names to Helicone-Property format and ensure string values
|
|
267
|
-
customHeaders[`Helicone-Property-${key}`] = String(value);
|
|
268
|
-
}
|
|
260
|
+
export function withHeliconeOpenAI(apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, environmentName, agentRequest, customProperties) {
|
|
261
|
+
const defaultHeaders = getDefaultHeliconeHeaders(heliconeApiKey, accountAddress, environmentName, agentRequest, customProperties);
|
|
269
262
|
return {
|
|
270
263
|
apiKey,
|
|
271
264
|
baseURL: heliconeBaseLoggingUrl,
|
|
272
265
|
defaultHeaders: {
|
|
273
|
-
|
|
274
|
-
'Helicone-Property-accountAddress': accountAddress,
|
|
275
|
-
...customHeaders,
|
|
266
|
+
...defaultHeaders,
|
|
276
267
|
},
|
|
277
268
|
};
|
|
278
269
|
}
|
|
@@ -315,28 +306,30 @@ export class ObservabilityAPI extends BasePaymentsAPI {
|
|
|
315
306
|
/**
|
|
316
307
|
* Creates a ChatOpenAI configuration with Helicone logging enabled
|
|
317
308
|
*
|
|
318
|
-
* Usage: const llm = new ChatOpenAI(observability.withHeliconeLangchain("gpt-4o-mini", apiKey, customProperties));
|
|
309
|
+
* Usage: const llm = new ChatOpenAI(observability.withHeliconeLangchain("gpt-4o-mini", apiKey, agentRequest, customProperties));
|
|
319
310
|
*
|
|
320
311
|
* @param model - The OpenAI model to use (e.g., "gpt-4o-mini", "gpt-4")
|
|
321
312
|
* @param apiKey - The OpenAI API key
|
|
313
|
+
* @param agentRequest - The agent request for logging purposes
|
|
322
314
|
* @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)
|
|
323
315
|
* @returns Configuration object for ChatOpenAI constructor with Helicone enabled
|
|
324
316
|
*/
|
|
325
|
-
withHeliconeLangchain(model, apiKey, customProperties) {
|
|
326
|
-
return withHeliconeLangchain(model, apiKey, this.heliconeApiKey, this.heliconeBaseLoggingUrl, this.accountAddress, customProperties);
|
|
317
|
+
withHeliconeLangchain(model, apiKey, startAgentRequest, customProperties) {
|
|
318
|
+
return withHeliconeLangchain(model, apiKey, this.heliconeApiKey, this.heliconeBaseLoggingUrl, this.accountAddress, this.environmentName, startAgentRequest, customProperties);
|
|
327
319
|
}
|
|
328
320
|
/**
|
|
329
321
|
* Creates an OpenAI client configuration with Helicone logging enabled
|
|
330
322
|
*
|
|
331
|
-
* Usage: const openai = new OpenAI(observability.withHeliconeOpenAI(apiKey, heliconeApiKey, customProperties));
|
|
323
|
+
* Usage: const openai = new OpenAI(observability.withHeliconeOpenAI(apiKey, heliconeApiKey, agentRequest, customProperties));
|
|
332
324
|
*
|
|
333
325
|
* @param apiKey - The OpenAI API key
|
|
334
326
|
* @param heliconeApiKey - The Helicone API key for logging
|
|
327
|
+
* @param agentRequest - The agent request for logging purposes
|
|
335
328
|
* @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)
|
|
336
329
|
* @returns Configuration object for OpenAI constructor with Helicone enabled
|
|
337
330
|
*/
|
|
338
|
-
withHeliconeOpenAI(apiKey, customProperties) {
|
|
339
|
-
return withHeliconeOpenAI(apiKey, this.heliconeApiKey, this.heliconeBaseLoggingUrl, this.accountAddress, customProperties);
|
|
331
|
+
withHeliconeOpenAI(apiKey, agentRequest, customProperties) {
|
|
332
|
+
return withHeliconeOpenAI(apiKey, this.heliconeApiKey, this.heliconeBaseLoggingUrl, this.accountAddress, this.environmentName, agentRequest, customProperties);
|
|
340
333
|
}
|
|
341
334
|
/**
|
|
342
335
|
* Helper function to calculate usage for image operations based on pixels
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"observability-api.js","sourceRoot":"","sources":["../../src/api/observability-api.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,EAAE,4BAA4B,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC7F,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAmEpD;;GAEG;AACH,MAAM,UAAU,qBAAqB,CAAC,MAA6B;IACjE,OAAO;QACL,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,CAAC;QACpC,KAAK,EAAE,MAAM,CA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ACxB,gBAAkC;QAElC,OAAO,mBAAmB,CACxB,SAAS,EACT,aAAa,EACb,SAAS,EACT,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,IAAI,CAAC,cAAe,EACpB,IAAI,CAAC,wBAAwB,EAC7B,IAAI,CAAC,cAAe,EACpB,gBAAgB,CACjB,CAAA;IACH,CAAC;IAED;;;;;;;;;OASG;IACH,qBAAqB,CACnB,KAAa,EACb,MAAc,EACd,gBAAkC;QAElC,OAAO,qBAAqB,CAC1B,KAAK,EACL,MAAM,EACN,IAAI,CAAC,cAAe,EACpB,IAAI,CAAC,sBAAsB,EAC3B,IAAI,CAAC,cAAe,EACpB,gBAAgB,CACjB,CAAA;IACH,CAAC;IAED;;;;;;;;;OASG;IACH,kBAAkB,CAAC,MAAc,EAAE,gBAAkC;QACnE,OAAO,kBAAkB,CACvB,MAAM,EACN,IAAI,CAAC,cAAe,EACpB,IAAI,CAAC,sBAAsB,EAC3B,IAAI,CAAC,cAAe,EACpB,gBAAgB,CACjB,CAAA;IACH,CAAC;IAED;;OAEG;IACH,mBAAmB,CAAC,MAAc;QAChC,OAAO,mBAAmB,CAAC,MAAM,CAAC,CAAA;IACpC,CAAC;IAED;;OAEG;IACH,mBAAmB;QACjB,OAAO,mBAAmB,EAAE,CAAA;IAC9B,CAAC;IAED;;OAEG;IACH,kBAAkB,CAAC,MAAc;QAC/B,OAAO,kBAAkB,CAAC,MAAM,CAAC,CAAA;IACnC,CAAC;IAED;;OAEG;IACH,uBAAuB;QACrB,OAAO,uBAAuB,EAAE,CAAA;IAClC,CAAC;IAED;;OAEG;IACH,qBAAqB,CAAC,MAA6B;QACjD,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAA;IACtC,CAAC;IAED;;OAEG;IACH,sBAAsB,CAAC,MAA8B;QACnD,OAAO,sBAAsB,CAAC,MAAM,CAAC,CAAA;IACvC,CAAC;CACF","sourcesContent":["/**\n * observability-api.ts\n * Provides reusable utilities for wrapping API calls with Helicone logging for AI agents\n */\n\nimport { HeliconeManualLogger } from '@helicone/helpers'\nimport { generateDeterministicAgentId, generateSessionId, logSessionInfo } from '../utils.js'\nimport { BasePaymentsAPI } from './base-payments.js'\nimport { PaymentOptions } from '../common/types.js'\n\n/**\n * Configuration for creating a Helicone payload\n */\nexport interface HeliconePayloadConfig {\n model: string\n inputData: Record<string, any>\n temperature?: number\n top_p?: number\n frequency_penalty?: number\n presence_penalty?: number\n n?: number\n stream?: boolean\n}\n\n/**\n * Configuration for creating a Helicone response\n */\nexport interface HeliconeResponseConfig {\n idPrefix: string\n model: string\n resultData: any\n usage: {\n prompt_tokens: number\n completion_tokens: number\n total_tokens: number\n prompt_tokens_details?: {\n cached_tokens: number\n audio_tokens: number\n }\n completion_tokens_details?: {\n reasoning_tokens: number\n audio_tokens: number\n accepted_prediction_tokens: number\n rejected_prediction_tokens: number\n }\n }\n systemFingerprint?: string\n}\n\nexport type CustomProperties = {\n agentid: string\n sessionid: string\n} & Record<string, string | number>\n\nexport type DefaultHeliconeHeaders = {\n 'Helicone-Auth': string\n 'Helicone-Property-accountAddress': string\n} & Record<string, string>\n\nexport type ChatOpenAIConfiguration = {\n model: string\n apiKey: string\n configuration: {\n baseURL: string\n defaultHeaders: DefaultHeliconeHeaders\n }\n}\n\nexport type OpenAIConfiguration = {\n apiKey: string\n baseURL: string\n defaultHeaders: DefaultHeliconeHeaders\n}\n\n/**\n * Creates a standardized Helicone payload for API logging\n */\nexport function createHeliconePayload(config: HeliconePayloadConfig) {\n return {\n model: config.model,\n temperature: config.temperature ?? 1,\n top_p: config.top_p ?? 1,\n frequency_penalty: config.frequency_penalty ?? 0,\n presence_penalty: config.presence_penalty ?? 0,\n n: config.n ?? 1,\n stream: config.stream ?? false,\n messages: [\n {\n role: 'user',\n content: JSON.stringify(config.inputData),\n },\n ],\n }\n}\n\n/**\n * Creates a standardized Helicone response for API logging\n */\nexport function createHeliconeResponse(config: HeliconeResponseConfig) {\n const timestamp = Date.now()\n\n return {\n id: `${config.idPrefix}-${timestamp}`,\n object: 'chat.completion',\n created: Math.floor(timestamp / 1000),\n model: config.model,\n choices: [\n {\n index: 0,\n message: {\n role: 'assistant',\n content: JSON.stringify(config.resultData),\n refusal: null,\n annotations: [],\n },\n logprobs: null,\n finish_reason: 'stop',\n },\n ],\n usage: {\n prompt_tokens: config.usage.prompt_tokens,\n completion_tokens: config.usage.completion_tokens,\n total_tokens: config.usage.total_tokens,\n prompt_tokens_details: config.usage.prompt_tokens_details ?? {\n cached_tokens: 0,\n audio_tokens: 0,\n },\n completion_tokens_details: config.usage.completion_tokens_details ?? {\n reasoning_tokens: 0,\n audio_tokens: 0,\n accepted_prediction_tokens: 0,\n rejected_prediction_tokens: 0,\n },\n },\n service_tier: 'default',\n system_fingerprint: config.systemFingerprint ?? `fp_${timestamp}`,\n }\n}\n\n/**\n * Wraps an async operation with Helicone logging\n *\n * @param agentName - Name of the agent for logging purposes\n * @param payloadConfig - Configuration for the Helicone payload\n * @param operation - The async operation to execute (returns internal result with extra data)\n * @param resultExtractor - Function to extract the user-facing result from internal result\n * @param usageCalculator - Function to calculate usage metrics from the internal result\n * @param responseIdPrefix - Prefix for the response ID\n * @param heliconeApiKey - The Helicone API key for logging\n * @param heliconeManualLoggingUrl - The Helicone manual logging endpoint URL\n * @param accountAddress - The account address for logging purposes\n * @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)\n * @returns Promise that resolves to the extracted user result\n */\nexport async function withHeliconeLogging<TInternal = any, TExtracted = any>(\n agentName: string,\n payloadConfig: HeliconePayloadConfig,\n operation: () => Promise<TInternal>,\n resultExtractor: (internalResult: TInternal) => TExtracted,\n usageCalculator: (internalResult: TInternal) => HeliconeResponseConfig['usage'],\n responseIdPrefix: string,\n heliconeApiKey: string,\n heliconeManualLoggingUrl: string,\n accountAddress: string,\n customProperties: CustomProperties,\n): Promise<TExtracted> {\n // Extract agentId and sessionId from properties, or generate defaults\n const agentId = customProperties.agentid\n ? String(customProperties.agentid)\n : generateDeterministicAgentId('')\n const sessionId = customProperties.sessionid\n ? String(customProperties.sessionid)\n : generateSessionId()\n\n // Log session info if these weren't provided in custom properties\n if (!customProperties.agentid || !customProperties.sessionid) {\n logSessionInfo(agentId, sessionId, agentName)\n }\n\n // Build custom property headers from all properties\n const customHeaders: Record<string, string> = {}\n for (const [key, value] of Object.entries(customProperties)) {\n // Convert property names to Helicone-Property format and ensure string values\n customHeaders[`Helicone-Property-${key}`] = String(value)\n }\n\n const heliconeLogger = new HeliconeManualLogger({\n apiKey: heliconeApiKey,\n loggingEndpoint: heliconeManualLoggingUrl,\n headers: {\n ...customHeaders,\n 'Helicone-Property-accountAddress': accountAddress,\n },\n })\n\n const heliconePayload = createHeliconePayload(payloadConfig)\n\n return await heliconeLogger.logRequest(heliconePayload, async (resultRecorder: any) => {\n const internalResult = await operation()\n\n const usage = usageCalculator(internalResult)\n\n const extractedResult = resultExtractor(internalResult)\n\n const heliconeResponse = createHeliconeResponse({\n idPrefix: responseIdPrefix,\n model: payloadConfig.model,\n resultData: extractedResult,\n usage,\n systemFingerprint: (extractedResult as any)?.jobId\n ? `fp_${(extractedResult as any).jobId}`\n : undefined,\n })\n\n resultRecorder.appendResults(heliconeResponse)\n\n return extractedResult\n })\n}\n\n/**\n * Helper function to calculate usage for image operations based on pixels\n */\nexport function calculateImageUsage(pixels: number): HeliconeResponseConfig['usage'] {\n return {\n prompt_tokens: 0,\n completion_tokens: pixels,\n total_tokens: pixels,\n prompt_tokens_details: {\n cached_tokens: 0,\n audio_tokens: 0,\n },\n completion_tokens_details: {\n reasoning_tokens: 0,\n audio_tokens: 0,\n accepted_prediction_tokens: 0,\n rejected_prediction_tokens: 0,\n },\n }\n}\n\n/**\n * Helper function to calculate usage for video operations (typically 1 token)\n */\nexport function calculateVideoUsage(): HeliconeResponseConfig['usage'] {\n return {\n prompt_tokens: 0,\n completion_tokens: 1,\n total_tokens: 1,\n prompt_tokens_details: {\n cached_tokens: 0,\n audio_tokens: 0,\n },\n completion_tokens_details: {\n reasoning_tokens: 0,\n audio_tokens: 0,\n accepted_prediction_tokens: 0,\n rejected_prediction_tokens: 0,\n },\n }\n}\n\n/**\n * Helper function to calculate usage for song operations based on tokens/quota\n */\nexport function calculateSongUsage(tokens: number): HeliconeResponseConfig['usage'] {\n return {\n prompt_tokens: 0,\n completion_tokens: tokens,\n total_tokens: tokens,\n prompt_tokens_details: {\n cached_tokens: 0,\n audio_tokens: 0,\n },\n completion_tokens_details: {\n reasoning_tokens: 0,\n audio_tokens: 0,\n accepted_prediction_tokens: 0,\n rejected_prediction_tokens: 0,\n },\n }\n}\n\n/**\n * Helper function to calculate usage for dummy song operations\n */\nexport function calculateDummySongUsage(): HeliconeResponseConfig['usage'] {\n return calculateSongUsage(6) // Default dummy token count\n}\n\n/**\n * Creates a ChatOpenAI configuration with Helicone logging enabled\n *\n * Usage: const llm = new ChatOpenAI(withHeliconeLangchain(\"gpt-4o-mini\", apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, customProperties));\n *\n * @param model - The OpenAI model to use (e.g., \"gpt-4o-mini\", \"gpt-4\")\n * @param apiKey - The OpenAI API key\n * @param heliconeApiKey - The Helicone API key for logging\n * @param heliconeBaseLoggingUrl - The Helicone base logging endpoint URL\n * @param accountAddress - The account address for logging purposes\n * @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)\n * @returns Configuration object for ChatOpenAI constructor with Helicone enabled\n */\nexport function withHeliconeLangchain(\n model: string,\n apiKey: string,\n heliconeApiKey: string,\n heliconeBaseLoggingUrl: string,\n accountAddress: string,\n customProperties: CustomProperties,\n): ChatOpenAIConfiguration {\n // Extract agentId and sessionId from properties, or generate defaults\n const agentId = customProperties.agentid\n ? String(customProperties.agentid)\n : generateDeterministicAgentId('')\n const sessionId = customProperties.sessionid\n ? String(customProperties.sessionid)\n : generateSessionId()\n\n // Log session info if these weren't provided in custom properties\n if (!customProperties.agentid || !customProperties.sessionid) {\n logSessionInfo(agentId, sessionId, 'LangChainChatOpenAI')\n }\n\n // Build custom property headers from all properties\n const customHeaders: Record<string, string> = {}\n for (const [key, value] of Object.entries(customProperties)) {\n // Convert property names to Helicone-Property format and ensure string values\n customHeaders[`Helicone-Property-${key}`] = String(value)\n }\n\n return {\n model,\n apiKey,\n configuration: {\n baseURL: heliconeBaseLoggingUrl,\n defaultHeaders: {\n 'Helicone-Auth': `Bearer ${heliconeApiKey}`,\n 'Helicone-Property-accountAddress': accountAddress,\n ...customHeaders,\n },\n },\n }\n}\n\n/**\n * Creates an OpenAI client configuration with Helicone logging enabled\n *\n * Usage: const openai = new OpenAI(withHeliconeOpenAI(apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, customProperties));\n *\n * @param apiKey - The OpenAI API key\n * @param heliconeApiKey - The Helicone API key for logging\n * @param heliconeBaseLoggingUrl - The Helicone base logging endpoint URL\n * @param accountAddress - The account address for logging purposes\n * @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)\n * @returns Configuration object for OpenAI constructor with Helicone enabled\n */\nexport function withHeliconeOpenAI(\n apiKey: string,\n heliconeApiKey: string,\n heliconeBaseLoggingUrl: string,\n accountAddress: string,\n customProperties: CustomProperties,\n): OpenAIConfiguration {\n // Extract agentId and sessionId from properties, or generate defaults\n const agentId = customProperties.agentid\n ? String(customProperties.agentid)\n : generateDeterministicAgentId('')\n const sessionId = customProperties.sessionid\n ? String(customProperties.sessionid)\n : generateSessionId()\n\n // Log session info if these weren't provided in custom properties\n if (!customProperties.agentid || !customProperties.sessionid) {\n logSessionInfo(agentId, sessionId, 'OpenAI')\n }\n\n // Build custom property headers from all properties\n const customHeaders: Record<string, string> = {}\n for (const [key, value] of Object.entries(customProperties)) {\n // Convert property names to Helicone-Property format and ensure string values\n customHeaders[`Helicone-Property-${key}`] = String(value)\n }\n\n return {\n apiKey,\n baseURL: heliconeBaseLoggingUrl,\n defaultHeaders: {\n 'Helicone-Auth': `Bearer ${heliconeApiKey}`,\n 'Helicone-Property-accountAddress': accountAddress,\n ...customHeaders,\n },\n }\n}\n\n/**\n * The ObservabilityAPI class provides methods to wrap API calls with Helicone logging\n */\nexport class ObservabilityAPI extends BasePaymentsAPI {\n protected readonly heliconeBaseLoggingUrl: string\n protected readonly heliconeManualLoggingUrl: string\n\n constructor(options: PaymentOptions) {\n super(options)\n\n // TODO: For testing purposes only. Remove once helicone is deployed to staging\n // Get Helicone API key from environment variable and override the base class property\n this.heliconeApiKey = process.env.HELICONE_API_KEY ?? this.heliconeApiKey\n\n this.heliconeBaseLoggingUrl = new URL(\n 'jawn/v1/gateway/oai/v1',\n this.environment.heliconeUrl,\n ).toString()\n this.heliconeManualLoggingUrl = new URL(\n 'jawn/v1/trace/custom/log',\n this.environment.heliconeUrl,\n ).toString()\n }\n\n /**\n * This method is used to create a singleton instance of the ObservabilityAPI class.\n *\n * @param options - The options to initialize the payments class.\n * @returns The instance of the ObservabilityAPI class.\n */\n static getInstance(options: PaymentOptions): ObservabilityAPI {\n return new ObservabilityAPI(options)\n }\n\n /**\n * Wraps an async operation with Helicone logging\n *\n * @param agentName - Name of the agent for logging purposes\n * @param payloadConfig - Configuration for the Helicone payload\n * @param operation - The async operation to execute (returns internal result with extra data)\n * @param resultExtractor - Function to extract the user-facing result from internal result\n * @param usageCalculator - Function to calculate usage metrics from the internal result\n * @param responseIdPrefix - Prefix for the response ID\n * @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)\n * @returns Promise that resolves to the extracted user result\n */\n async withHeliconeLogging<TInternal = any, TExtracted = any>(\n agentName: string,\n payloadConfig: HeliconePayloadConfig,\n operation: () => Promise<TInternal>,\n resultExtractor: (internalResult: TInternal) => TExtracted,\n usageCalculator: (internalResult: TInternal) => HeliconeResponseConfig['usage'],\n responseIdPrefix: string,\n customProperties: CustomProperties,\n ): Promise<TExtracted> {\n return withHeliconeLogging(\n agentName,\n payloadConfig,\n operation,\n resultExtractor,\n usageCalculator,\n responseIdPrefix,\n this.heliconeApiKey!,\n this.heliconeManualLoggingUrl,\n this.accountAddress!,\n customProperties,\n )\n }\n\n /**\n * Creates a ChatOpenAI configuration with Helicone logging enabled\n *\n * Usage: const llm = new ChatOpenAI(observability.withHeliconeLangchain(\"gpt-4o-mini\", apiKey, customProperties));\n *\n * @param model - The OpenAI model to use (e.g., \"gpt-4o-mini\", \"gpt-4\")\n * @param apiKey - The OpenAI API key\n * @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)\n * @returns Configuration object for ChatOpenAI constructor with Helicone enabled\n */\n withHeliconeLangchain(\n model: string,\n apiKey: string,\n customProperties: CustomProperties,\n ): ChatOpenAIConfiguration {\n return withHeliconeLangchain(\n model,\n apiKey,\n this.heliconeApiKey!,\n this.heliconeBaseLoggingUrl,\n this.accountAddress!,\n customProperties,\n )\n }\n\n /**\n * Creates an OpenAI client configuration with Helicone logging enabled\n *\n * Usage: const openai = new OpenAI(observability.withHeliconeOpenAI(apiKey, heliconeApiKey, customProperties));\n *\n * @param apiKey - The OpenAI API key\n * @param heliconeApiKey - The Helicone API key for logging\n * @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)\n * @returns Configuration object for OpenAI constructor with Helicone enabled\n */\n withHeliconeOpenAI(apiKey: string, customProperties: CustomProperties): OpenAIConfiguration {\n return withHeliconeOpenAI(\n apiKey,\n this.heliconeApiKey!,\n this.heliconeBaseLoggingUrl,\n this.accountAddress!,\n customProperties,\n )\n }\n\n /**\n * Helper function to calculate usage for image operations based on pixels\n */\n calculateImageUsage(pixels: number): HeliconeResponseConfig['usage'] {\n return calculateImageUsage(pixels)\n }\n\n /**\n * Helper function to calculate usage for video operations (typically 1 token)\n */\n calculateVideoUsage(): HeliconeResponseConfig['usage'] {\n return calculateVideoUsage()\n }\n\n /**\n * Helper function to calculate usage for song operations based on tokens/quota\n */\n calculateSongUsage(tokens: number): HeliconeResponseConfig['usage'] {\n return calculateSongUsage(tokens)\n }\n\n /**\n * Helper function to calculate usage for dummy song operations\n */\n calculateDummySongUsage(): HeliconeResponseConfig['usage'] {\n return calculateDummySongUsage()\n }\n\n /**\n * Creates a standardized Helicone payload for API logging\n */\n createHeliconePayload(config: HeliconePayloadConfig) {\n return createHeliconePayload(config)\n }\n\n /**\n * Creates a standardized Helicone response for API logging\n */\n createHeliconeResponse(config: HeliconeResponseConfig) {\n return createHeliconeResponse(config)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"observability-api.js","sourceRoot":"","sources":["../../src/api/observability-api.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAA;AACxD,OAAO,EAAE,4BAA4B,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC7F,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AA4EpD,SAAS,yBAAyB,CAChC,cAAsB,EACtB,cAAsB,EACtB,eAAgC,EAChC,YAA+B,EAC/B,gBAAkC;IAElC,MAAM,yBAAyB,GAA8B;QAC3D,eAAe,EAAE,UAAU,cAAc,EAAE;QAC3C,kCAAkC,EAAE,cAAc;QAClD,mCAAmC,EAAE,YAAY,CAAC,OAAO,CAAC,aAAa;QACvE,2BAA2B,EAAE,YAAY,CAAC,OAAO;QACjD,0BAA0B,EAAE,YAAY,CAAC,OAAO,CAAC,MAAM;QACvD,4BAA4B,EAAE,YAAY,CAAC,OAAO,CAAC,QAAQ;QAC3D,4BAA4B,EAAE,YAAY,CAAC,OAAO,CAAC,QAAQ;QAC3D,6BAA6B,EAAE,YAAY,CAAC,SAAS;QACrD,kCAAkC,EAAE,YAAY,CAAC,cAAc;QAC/D,kCAAkC,EAAE,YAAY,CAAC,OAAO,CAAC,cAAc,CAAC,QAAQ,EAAE;QAClF,mCAAmC,EAAE,eAAe;KACrD,CAAA;IAED,oDAAoD;IACpD,MAAM,aAAa,GAAqB,EAAE,CAAA;IAC1C,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,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B,OAAO,uBAAuB,EAAE,CAAA;IAClC,CAAC;IAED;;OAEG;IACH,qBAAqB,CAAC,MAA6B;QACjD,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAA;IACtC,CAAC;IAED;;OAEG;IACH,sBAAsB,CAAC,MAA8B;QACnD,OAAO,sBAAsB,CAAC,MAAM,CAAC,CAAA;IACvC,CAAC;CACF","sourcesContent":["/**\n * observability-api.ts\n * Provides reusable utilities for wrapping API calls with Helicone logging for AI agents\n */\n\nimport { HeliconeManualLogger } from '@helicone/helpers'\nimport { generateDeterministicAgentId, generateSessionId, logSessionInfo } from '../utils.js'\nimport { BasePaymentsAPI } from './base-payments.js'\nimport { PaymentOptions, StartAgentRequest } from '../common/types.js'\nimport { EnvironmentName } from '../environments.js'\n\n/**\n * Configuration for creating a Helicone payload\n */\nexport interface HeliconePayloadConfig {\n model: string\n inputData: Record<string, any>\n temperature?: number\n top_p?: number\n frequency_penalty?: number\n presence_penalty?: number\n n?: number\n stream?: boolean\n}\n\n/**\n * Configuration for creating a Helicone response\n */\nexport interface HeliconeResponseConfig {\n idPrefix: string\n model: string\n resultData: any\n usage: {\n prompt_tokens: number\n completion_tokens: number\n total_tokens: number\n prompt_tokens_details?: {\n cached_tokens: number\n audio_tokens: number\n }\n completion_tokens_details?: {\n reasoning_tokens: number\n audio_tokens: number\n accepted_prediction_tokens: number\n rejected_prediction_tokens: number\n }\n }\n systemFingerprint?: string\n}\n\nexport type CustomProperties = Record<string, string>\n\nexport type NeverminedHeliconeHeaders = {\n 'Helicone-Auth': string\n 'Helicone-Property-accountAddress': string\n 'Helicone-Property-consumerAddress': string\n 'Helicone-Property-agentId': string\n 'Helicone-Property-planId': string\n 'Helicone-Property-planType': string\n 'Helicone-Property-planName': string\n 'Helicone-Property-agentName': string\n 'Helicone-Property-agentRequestId': string\n 'Helicone-Property-pricePerCredit': string\n 'Helicone-Property-environmentName': string\n}\n\nexport type DefaultHeliconeHeaders = NeverminedHeliconeHeaders & CustomProperties\n\nexport type ChatOpenAIConfiguration = {\n model: string\n apiKey: string\n configuration: {\n baseURL: string\n defaultHeaders: DefaultHeliconeHeaders\n }\n}\n\nexport type OpenAIConfiguration = {\n apiKey: string\n baseURL: string\n defaultHeaders: DefaultHeliconeHeaders\n}\n\nfunction getDefaultHeliconeHeaders(\n heliconeApiKey: string,\n accountAddress: string,\n environmentName: EnvironmentName,\n agentRequest: StartAgentRequest,\n customProperties: CustomProperties,\n): DefaultHeliconeHeaders {\n const neverminedHeliconeHeaders: NeverminedHeliconeHeaders = {\n 'Helicone-Auth': `Bearer ${heliconeApiKey}`,\n 'Helicone-Property-accountAddress': accountAddress,\n 'Helicone-Property-consumerAddress': agentRequest.balance.holderAddress,\n 'Helicone-Property-agentId': agentRequest.agentId,\n 'Helicone-Property-planId': agentRequest.balance.planId,\n 'Helicone-Property-planType': agentRequest.balance.planType,\n 'Helicone-Property-planName': agentRequest.balance.planName,\n 'Helicone-Property-agentName': agentRequest.agentName,\n 'Helicone-Property-agentRequestId': agentRequest.agentRequestId,\n 'Helicone-Property-pricePerCredit': agentRequest.balance.pricePerCredit.toString(),\n 'Helicone-Property-environmentName': environmentName,\n }\n\n // Build custom property headers from all properties\n const customHeaders: CustomProperties = {}\n for (const [key, value] of Object.entries(customProperties)) {\n // Convert property names to Helicone-Property format\n customHeaders[`Helicone-Property-${key}`] = value\n }\n\n return {\n ...neverminedHeliconeHeaders,\n ...customHeaders,\n }\n}\n\n/**\n * Creates a standardized Helicone payload for API logging\n */\nexport function createHeliconePayload(config: HeliconePayloadConfig) {\n return {\n model: config.model,\n temperature: config.temperature ?? 1,\n top_p: config.top_p ?? 1,\n frequency_penalty: config.frequency_penalty ?? 0,\n presence_penalty: config.presence_penalty ?? 0,\n n: config.n ?? 1,\n stream: config.stream ?? false,\n messages: [\n {\n role: 'user',\n content: JSON.stringify(config.inputData),\n },\n ],\n }\n}\n\n/**\n * Creates a standardized Helicone response for API logging\n */\nexport function createHeliconeResponse(config: HeliconeResponseConfig) {\n const timestamp = Date.now()\n\n return {\n id: `${config.idPrefix}-${timestamp}`,\n object: 'chat.completion',\n created: Math.floor(timestamp / 1000),\n model: config.model,\n choices: [\n {\n index: 0,\n message: {\n role: 'assistant',\n content: JSON.stringify(config.resultData),\n refusal: null,\n annotations: [],\n },\n logprobs: null,\n finish_reason: 'stop',\n },\n ],\n usage: {\n prompt_tokens: config.usage.prompt_tokens,\n completion_tokens: config.usage.completion_tokens,\n total_tokens: config.usage.total_tokens,\n prompt_tokens_details: config.usage.prompt_tokens_details ?? {\n cached_tokens: 0,\n audio_tokens: 0,\n },\n completion_tokens_details: config.usage.completion_tokens_details ?? {\n reasoning_tokens: 0,\n audio_tokens: 0,\n accepted_prediction_tokens: 0,\n rejected_prediction_tokens: 0,\n },\n },\n service_tier: 'default',\n system_fingerprint: config.systemFingerprint ?? `fp_${timestamp}`,\n }\n}\n\n/**\n * Wraps an async operation with Helicone logging\n *\n * @param agentName - Name of the agent for logging purposes\n * @param payloadConfig - Configuration for the Helicone payload\n * @param operation - The async operation to execute (returns internal result with extra data)\n * @param resultExtractor - Function to extract the user-facing result from internal result\n * @param usageCalculator - Function to calculate usage metrics from the internal result\n * @param responseIdPrefix - Prefix for the response ID\n * @param heliconeApiKey - The Helicone API key for logging\n * @param heliconeManualLoggingUrl - The Helicone manual logging endpoint URL\n * @param accountAddress - The account address for logging purposes\n * @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)\n * @returns Promise that resolves to the extracted user result\n */\nexport async function withHeliconeLogging<TInternal = any, TExtracted = any>(\n agentName: string,\n payloadConfig: HeliconePayloadConfig,\n operation: () => Promise<TInternal>,\n resultExtractor: (internalResult: TInternal) => TExtracted,\n usageCalculator: (internalResult: TInternal) => HeliconeResponseConfig['usage'],\n responseIdPrefix: string,\n heliconeApiKey: string,\n heliconeManualLoggingUrl: string,\n accountAddress: string,\n customProperties: CustomProperties,\n): Promise<TExtracted> {\n // Extract agentId and sessionId from properties, or generate defaults\n const agentId = customProperties.agentid\n ? String(customProperties.agentid)\n : generateDeterministicAgentId('')\n const sessionId = customProperties.sessionid\n ? String(customProperties.sessionid)\n : generateSessionId()\n\n // Log session info if these weren't provided in custom properties\n if (!customProperties.agentid || !customProperties.sessionid) {\n logSessionInfo(agentId, sessionId, agentName)\n }\n\n // Build custom property headers from all properties\n const customHeaders: Record<string, string> = {}\n for (const [key, value] of Object.entries(customProperties)) {\n // Convert property names to Helicone-Property format and ensure string values\n customHeaders[`Helicone-Property-${key}`] = String(value)\n }\n\n const heliconeLogger = new HeliconeManualLogger({\n apiKey: heliconeApiKey,\n loggingEndpoint: heliconeManualLoggingUrl,\n headers: {\n ...customHeaders,\n 'Helicone-Property-accountAddress': accountAddress,\n },\n })\n\n const heliconePayload = createHeliconePayload(payloadConfig)\n\n return await heliconeLogger.logRequest(heliconePayload, async (resultRecorder: any) => {\n const internalResult = await operation()\n\n const usage = usageCalculator(internalResult)\n\n const extractedResult = resultExtractor(internalResult)\n\n const heliconeResponse = createHeliconeResponse({\n idPrefix: responseIdPrefix,\n model: payloadConfig.model,\n resultData: extractedResult,\n usage,\n systemFingerprint: (extractedResult as any)?.jobId\n ? `fp_${(extractedResult as any).jobId}`\n : undefined,\n })\n\n resultRecorder.appendResults(heliconeResponse)\n\n return extractedResult\n })\n}\n\n/**\n * Helper function to calculate usage for image operations based on pixels\n */\nexport function calculateImageUsage(pixels: number): HeliconeResponseConfig['usage'] {\n return {\n prompt_tokens: 0,\n completion_tokens: pixels,\n total_tokens: pixels,\n prompt_tokens_details: {\n cached_tokens: 0,\n audio_tokens: 0,\n },\n completion_tokens_details: {\n reasoning_tokens: 0,\n audio_tokens: 0,\n accepted_prediction_tokens: 0,\n rejected_prediction_tokens: 0,\n },\n }\n}\n\n/**\n * Helper function to calculate usage for video operations (typically 1 token)\n */\nexport function calculateVideoUsage(): HeliconeResponseConfig['usage'] {\n return {\n prompt_tokens: 0,\n completion_tokens: 1,\n total_tokens: 1,\n prompt_tokens_details: {\n cached_tokens: 0,\n audio_tokens: 0,\n },\n completion_tokens_details: {\n reasoning_tokens: 0,\n audio_tokens: 0,\n accepted_prediction_tokens: 0,\n rejected_prediction_tokens: 0,\n },\n }\n}\n\n/**\n * Helper function to calculate usage for song operations based on tokens/quota\n */\nexport function calculateSongUsage(tokens: number): HeliconeResponseConfig['usage'] {\n return {\n prompt_tokens: 0,\n completion_tokens: tokens,\n total_tokens: tokens,\n prompt_tokens_details: {\n cached_tokens: 0,\n audio_tokens: 0,\n },\n completion_tokens_details: {\n reasoning_tokens: 0,\n audio_tokens: 0,\n accepted_prediction_tokens: 0,\n rejected_prediction_tokens: 0,\n },\n }\n}\n\n/**\n * Helper function to calculate usage for dummy song operations\n */\nexport function calculateDummySongUsage(): HeliconeResponseConfig['usage'] {\n return calculateSongUsage(6) // Default dummy token count\n}\n\n/**\n * Creates a ChatOpenAI configuration with Helicone logging enabled\n *\n * Usage: const llm = new ChatOpenAI(withHeliconeLangchain(\"gpt-4o-mini\", apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, agentRequest, customProperties));\n *\n * @param model - The OpenAI model to use (e.g., \"gpt-4o-mini\", \"gpt-4\")\n * @param apiKey - The OpenAI API key\n * @param heliconeApiKey - The Helicone API key for logging\n * @param heliconeBaseLoggingUrl - The Helicone base logging endpoint URL\n * @param accountAddress - The account address for logging purposes\n * @param environmentName - The environment name for logging purposes\n * @param agentRequest - The agent request for logging purposes\n * @param customProperties - Custom properties to add as Helicone headers\n * @returns Configuration object for ChatOpenAI constructor with Helicone enabled\n */\nexport function withHeliconeLangchain(\n model: string,\n apiKey: string,\n heliconeApiKey: string,\n heliconeBaseLoggingUrl: string,\n accountAddress: string,\n environmentName: EnvironmentName,\n agentRequest: StartAgentRequest,\n customProperties: CustomProperties,\n): ChatOpenAIConfiguration {\n const defaultHeaders = getDefaultHeliconeHeaders(\n heliconeApiKey,\n accountAddress,\n environmentName,\n agentRequest,\n customProperties,\n )\n\n return {\n model,\n apiKey,\n configuration: {\n baseURL: heliconeBaseLoggingUrl,\n defaultHeaders,\n },\n }\n}\n\n/**\n * Creates an OpenAI client configuration with Helicone logging enabled\n *\n * Usage: const openai = new OpenAI(withHeliconeOpenAI(apiKey, heliconeApiKey, heliconeBaseLoggingUrl, accountAddress, agentRequest, customProperties));\n *\n * @param apiKey - The OpenAI API key\n * @param heliconeApiKey - The Helicone API key for logging\n * @param heliconeBaseLoggingUrl - The Helicone base logging endpoint URL\n * @param accountAddress - The account address for logging purposes\n * @param environmentName - The environment name for logging purposes\n * @param agentRequest - The agent request for logging purposes\n * @param customProperties - Custom properties to add as Helicone headers\n * @returns Configuration object for OpenAI constructor with Helicone enabled\n */\nexport function withHeliconeOpenAI(\n apiKey: string,\n heliconeApiKey: string,\n heliconeBaseLoggingUrl: string,\n accountAddress: string,\n environmentName: EnvironmentName,\n agentRequest: StartAgentRequest,\n customProperties: CustomProperties,\n): OpenAIConfiguration {\n const defaultHeaders = getDefaultHeliconeHeaders(\n heliconeApiKey,\n accountAddress,\n environmentName,\n agentRequest,\n customProperties,\n )\n\n return {\n apiKey,\n baseURL: heliconeBaseLoggingUrl,\n defaultHeaders: {\n ...defaultHeaders,\n },\n }\n}\n\n/**\n * The ObservabilityAPI class provides methods to wrap API calls with Helicone logging\n */\nexport class ObservabilityAPI extends BasePaymentsAPI {\n protected readonly heliconeBaseLoggingUrl: string\n protected readonly heliconeManualLoggingUrl: string\n\n constructor(options: PaymentOptions) {\n super(options)\n\n // TODO: For testing purposes only. Remove once helicone is deployed to staging\n // Get Helicone API key from environment variable and override the base class property\n this.heliconeApiKey = process.env.HELICONE_API_KEY ?? this.heliconeApiKey\n\n this.heliconeBaseLoggingUrl = new URL(\n 'jawn/v1/gateway/oai/v1',\n this.environment.heliconeUrl,\n ).toString()\n this.heliconeManualLoggingUrl = new URL(\n 'jawn/v1/trace/custom/log',\n this.environment.heliconeUrl,\n ).toString()\n }\n\n /**\n * This method is used to create a singleton instance of the ObservabilityAPI class.\n *\n * @param options - The options to initialize the payments class.\n * @returns The instance of the ObservabilityAPI class.\n */\n static getInstance(options: PaymentOptions): ObservabilityAPI {\n return new ObservabilityAPI(options)\n }\n\n /**\n * Wraps an async operation with Helicone logging\n *\n * @param agentName - Name of the agent for logging purposes\n * @param payloadConfig - Configuration for the Helicone payload\n * @param operation - The async operation to execute (returns internal result with extra data)\n * @param resultExtractor - Function to extract the user-facing result from internal result\n * @param usageCalculator - Function to calculate usage metrics from the internal result\n * @param responseIdPrefix - Prefix for the response ID\n * @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)\n * @returns Promise that resolves to the extracted user result\n */\n async withHeliconeLogging<TInternal = any, TExtracted = any>(\n agentName: string,\n payloadConfig: HeliconePayloadConfig,\n operation: () => Promise<TInternal>,\n resultExtractor: (internalResult: TInternal) => TExtracted,\n usageCalculator: (internalResult: TInternal) => HeliconeResponseConfig['usage'],\n responseIdPrefix: string,\n customProperties: CustomProperties,\n ): Promise<TExtracted> {\n return withHeliconeLogging(\n agentName,\n payloadConfig,\n operation,\n resultExtractor,\n usageCalculator,\n responseIdPrefix,\n this.heliconeApiKey,\n this.heliconeManualLoggingUrl,\n this.accountAddress,\n customProperties,\n )\n }\n\n /**\n * Creates a ChatOpenAI configuration with Helicone logging enabled\n *\n * Usage: const llm = new ChatOpenAI(observability.withHeliconeLangchain(\"gpt-4o-mini\", apiKey, agentRequest, customProperties));\n *\n * @param model - The OpenAI model to use (e.g., \"gpt-4o-mini\", \"gpt-4\")\n * @param apiKey - The OpenAI API key\n * @param agentRequest - The agent request for logging purposes\n * @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)\n * @returns Configuration object for ChatOpenAI constructor with Helicone enabled\n */\n withHeliconeLangchain(\n model: string,\n apiKey: string,\n startAgentRequest: StartAgentRequest,\n customProperties: CustomProperties,\n ): ChatOpenAIConfiguration {\n return withHeliconeLangchain(\n model,\n apiKey,\n this.heliconeApiKey,\n this.heliconeBaseLoggingUrl,\n this.accountAddress,\n this.environmentName,\n startAgentRequest,\n customProperties,\n )\n }\n\n /**\n * Creates an OpenAI client configuration with Helicone logging enabled\n *\n * Usage: const openai = new OpenAI(observability.withHeliconeOpenAI(apiKey, heliconeApiKey, agentRequest, customProperties));\n *\n * @param apiKey - The OpenAI API key\n * @param heliconeApiKey - The Helicone API key for logging\n * @param agentRequest - The agent request for logging purposes\n * @param customProperties - Custom properties to add as Helicone headers (should include agentid and sessionid)\n * @returns Configuration object for OpenAI constructor with Helicone enabled\n */\n withHeliconeOpenAI(\n apiKey: string,\n agentRequest: StartAgentRequest,\n customProperties: CustomProperties,\n ): OpenAIConfiguration {\n return withHeliconeOpenAI(\n apiKey,\n this.heliconeApiKey,\n this.heliconeBaseLoggingUrl,\n this.accountAddress,\n this.environmentName,\n agentRequest,\n customProperties,\n )\n }\n\n /**\n * Helper function to calculate usage for image operations based on pixels\n */\n calculateImageUsage(pixels: number): HeliconeResponseConfig['usage'] {\n return calculateImageUsage(pixels)\n }\n\n /**\n * Helper function to calculate usage for video operations (typically 1 token)\n */\n calculateVideoUsage(): HeliconeResponseConfig['usage'] {\n return calculateVideoUsage()\n }\n\n /**\n * Helper function to calculate usage for song operations based on tokens/quota\n */\n calculateSongUsage(tokens: number): HeliconeResponseConfig['usage'] {\n return calculateSongUsage(tokens)\n }\n\n /**\n * Helper function to calculate usage for dummy song operations\n */\n calculateDummySongUsage(): HeliconeResponseConfig['usage'] {\n return calculateDummySongUsage()\n }\n\n /**\n * Creates a standardized Helicone payload for API logging\n */\n createHeliconePayload(config: HeliconePayloadConfig) {\n return createHeliconePayload(config)\n }\n\n /**\n * Creates a standardized Helicone response for API logging\n */\n createHeliconeResponse(config: HeliconeResponseConfig) {\n return createHeliconeResponse(config)\n }\n}\n"]}
|
package/dist/common/types.d.ts
CHANGED
|
@@ -150,13 +150,18 @@ export declare enum PlanRedemptionType {
|
|
|
150
150
|
}
|
|
151
151
|
export interface PlanBalance {
|
|
152
152
|
planId: string;
|
|
153
|
+
planName: string;
|
|
154
|
+
planType: string;
|
|
153
155
|
holderAddress: Address;
|
|
154
156
|
balance: bigint;
|
|
155
157
|
creditsContract: Address;
|
|
156
158
|
isSubscriber: boolean;
|
|
159
|
+
pricePerCredit: number;
|
|
157
160
|
}
|
|
158
161
|
export interface StartAgentRequest {
|
|
159
162
|
agentRequestId: string;
|
|
163
|
+
agentName: string;
|
|
164
|
+
agentId: string;
|
|
160
165
|
balance: PlanBalance;
|
|
161
166
|
urlMatching: string;
|
|
162
167
|
verbMatching: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/common/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAEpD;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;OAIG;IACH,WAAW,EAAE,eAAe,CAAA;IAE5B;;;;OAIG;IACH,SAAS,EAAE,MAAM,CAAA;IAEjB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAElB;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;IAEd;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,WAAW,QAAQ;IACvB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;CACvB;AAED,MAAM,WAAW,WAAW,CAAC,CAAC;IAC5B,OAAO,EAAE,OAAO,CAAA;IAChB,IAAI,CAAC,EAAE,CAAC,CAAA;IACR,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED,MAAM,MAAM,OAAO,GAAG,KAAK,MAAM,EAAE,CAAA;AAEnC;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,SAAS,EAAE,aAAa,CAAA;IACxB;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB;;;OAGG;IACH,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB;;;OAGG;IACH,SAAS,EAAE,MAAM,EAAE,CAAA;IACnB;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,WAAW,EAAE,eAAe,CAAA;IAC5B;;OAEG;IACH,cAAc,EAAE,kBAAkB,CAAA;IAClC;;OAEG;IACH,aAAa,EAAE,OAAO,CAAA;IACtB;;;OAGG;IACH,YAAY,EAAE,MAAM,CAAA;IACpB;;OAEG;IACH,MAAM,EAAE,MAAM,CAAA;IACd;;;OAGG;IACH,SAAS,EAAE,MAAM,CAAA;IACjB;;;OAGG;IACH,SAAS,EAAE,MAAM,CAAA;IACjB;;OAEG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB;AAED;;;;;;GAMG;AACH,oBAAY,aAAa;IACvB,WAAW,IAAA;IACX,gBAAgB,IAAA;IAChB,oBAAoB,IAAA;CACrB;AAED;;;;;;GAMG;AACH,oBAAY,eAAe;IACzB,SAAS,IAAA;IACT,KAAK,IAAA;IACL,OAAO,IAAA;CACR;AAED;;;;;;GAMG;AACH,oBAAY,kBAAkB;IAC5B,gBAAgB,IAAA,CAAE,qBAAqB;IACvC,UAAU,IAAA,CAAE,iBAAiB;IAC7B,cAAc,IAAA;CACf;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAA;IACd,aAAa,EAAE,OAAO,CAAA;IACtB,OAAO,EAAE,MAAM,CAAA;IACf,eAAe,EAAE,OAAO,CAAA;IACxB,YAAY,EAAE,OAAO,CAAA;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/common/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAEpD;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;OAIG;IACH,WAAW,EAAE,eAAe,CAAA;IAE5B;;;;OAIG;IACH,SAAS,E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;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,QAAQ,CAAA;IAChD;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED;;GAEG;AACH,qBAAa,iBAAiB;IAC5B;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;OAGG;IACH,SAAS,EAAE,KAAK,GAAG,MAAM,CAAS;IAClC;;;OAGG;IACH,IAAI,SAAI;IACR;;;OAGG;IACH,MAAM,SAAK;IAEX;;;OAGG;gBACS,OAAO,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC;IAShD;;;;OAIG;IACH,aAAa,IAAI,MAAM;CAWxB;AAED;;GAEG;AACH,oBAAY,eAAe;IACzB,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,OAAO,YAAY;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;OAEG;IACH,cAAc,EAAE,MAAM,CAAA;IAEtB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAA;IAExB;;OAEG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IAEpB;;OAEG;IACH,MAAM,CAAC,EAAE,eAAe,CAAA;CACzB"}
|
package/dist/common/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/common/types.ts"],"names":[],"mappings":"AA6HA;;;;;;GAMG;AACH,MAAM,CAAN,IAAY,aAIX;AAJD,WAAY,aAAa;IACvB,+DAAW,CAAA;IACX,yEAAgB,CAAA;IAChB,iFAAoB,CAAA;AACtB,CAAC,EAJW,aAAa,KAAb,aAAa,QAIxB;AAED;;;;;;GAMG;AACH,MAAM,CA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AC,CAAC,QAAQ,EAAE,CAAA;IAC/C,CAAC;CACF;AAED;;GAEG;AACH,MAAM,CAAN,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,sCAAmB,CAAA;IACnB,oCAAiB,CAAA;IACjB,sCAAmB,CAAA;AACrB,CAAC,EAJW,eAAe,KAAf,eAAe,QAI1B","sourcesContent":["import { EnvironmentName } from '../environments.js'\n\n/**\n * Options to initialize the Payments class.\n */\nexport interface PaymentOptions {\n /**\n * The Nevermined environment to connect to.\n * If you are developing an agent it's recommended to use the \"testing\" environment.\n * When deploying to production use the \"arbitrum\" environment.\n */\n environment: EnvironmentName\n\n /**\n * The Nevermined API Key. This key identify your user and is required to interact with the Nevermined API.\n * You can get your API key by logging in to the Nevermined App.\n * @see https://docs.nevermined.app/docs/tutorials/integration/nvm-api-keys\n */\n nvmApiKey: string\n\n /**\n * The URL to return to the app after a successful login.\n */\n returnUrl?: string\n\n /**\n * The app id. This attribute is optional and helps to associate assets registered into Nevermined with a common identifier.\n */\n appId?: string\n\n /**\n * The version of the API to use.\n */\n version?: string\n}\n\nexport interface Endpoint {\n [verb: string]: string\n}\n\nexport interface ApiResponse<T> {\n success: boolean\n data?: T\n error?: string\n}\n\nexport type Address = `0x${string}`\n\n/**\n * Definition of the price configuration for a Payment Plan\n */\nexport interface PlanPriceConfig {\n /**\n * The type or configuration of the price\n * @remarks 0 - crypto fixed price. 1 - fixed fiat price. 2 - smart contract price\n */\n priceType: PlanPriceType\n /**\n * The address of the token (ERC20 or Native if zero address) for paying the plan\n * @remarks only if priceType == FIXED_PRICE or SMART_CONTRACT_PRICE\n */\n tokenAddress?: Address\n /**\n * The amounts to be paid for the plan\n * @remarks only if priceType == FIXED_PRICE or FIXED_FIAT_PRICE\n */\n amounts: bigint[]\n /**\n * The receivers of the payments of the plan\n * @remarks only if priceType == FIXED_PRICE\n */\n receivers: string[]\n /**\n * The address of the smart contract that calculates the price\n * @remarks only if priceType == SMART_CONTRACT_PRICE\n */\n contractAddress?: Address // only if priceType == 2\n /**\n * The address of the fee controller contract, if any\n * @remarks if not given, the fee controller is the default one\n */\n feeController?: Address // only if priceType == 2\n}\n\n/**\n * Definition of the credits configuration for a payment plan\n */\nexport interface PlanCreditsConfig {\n /**\n * The type of configuration of the credits type\n */\n creditsType: PlanCreditsType\n /**\n * How the credits can be redeemed\n */\n redemptionType: PlanRedemptionType\n /**\n * Whether the credits burn proof signed by the user is required\n */\n proofRequired: boolean\n /**\n * The duration of the credits in seconds\n * @remarks only if creditsType == EXPIRABLE\n */\n durationSecs: bigint\n /**\n * The amount of credits that are granted when purchasing the plan\n */\n amount: bigint\n /**\n * The minimum number of credits redeemed when using the plan\n * @remarks only if creditsType == FIXED or DYNAMIC\n */\n minAmount: bigint\n /**\n * The maximum number of credits redeemed when using the plan\n * @remarks only if creditsType == DYNAMIC\n */\n maxAmount: bigint\n /**\n * The address of the NFT contract that represents the plan's credits\n */\n nftAddress?: Address\n}\n\n/**\n * Different types of prices that can be configured for a plan\n * @remarks 0 - FIXED_PRICE, 1 - FIXED_FIAT_PRICE, 2 - SMART_CONTRACT_PRICE\n * If FIXED_PRICE it means the plan can be paid in crypto by a fixed amount of a ERC20 or Native token\n * If FIXED_FIAT_PRICE it means the plan can be paid in fiat by a fixed amount (typically USD)\n * If SMART_CONTRACT_PRICE it means the plan can be paid in crypto and the amount to be paid is calculated by a smart contract\n */\nexport enum PlanPriceType {\n FIXED_PRICE,\n FIXED_FIAT_PRICE,\n SMART_CONTRACT_PRICE,\n}\n\n/**\n * Different types of credits that can be obtained when purchasing a plan\n * @remarks 0 - EXPIRABLE, 1 - FIXED, 2 - DYNAMIC\n * If EXPIRABLE it means the credits can be used for a fixed amount of time (calculated in seconds)\n * If FIXED it means the credits can be used for a fixed amount of times\n * If DYNAMIC it means the credits can be used but the redemption amount is dynamic\n */\nexport enum PlanCreditsType {\n EXPIRABLE,\n FIXED,\n DYNAMIC,\n}\n\n/**\n * Different types of redemptions criterias that can be used when redeeming credits\n * @remarks 0 - ONLY_GLOBAL_ROLE, 1 - ONLY_OWNER, 2 - ROLE_AND_OWNER\n * If ONLY_GLOBAL_ROLE it means the credits can be redeemed only by an account with the `CREDITS_BURNER_ROLE`\n * If ONLY_OWNER it means the credits can be redeemed only by the owner of the Plan\n * If ONLY_PLAN_ROLE it means the credits can be redeemed by an account with specifics grants for the plan\n */\nexport enum PlanRedemptionType {\n ONLY_GLOBAL_ROLE, // NVM Proxy can burn\n ONLY_OWNER, // Agent can burn\n ONLY_PLAN_ROLE,\n}\n\nexport interface PlanBalance {\n planId: string\n holderAddress: Address\n balance: bigint\n creditsContract: Address\n isSubscriber: boolean\n}\n\nexport interface StartAgentRequest {\n agentRequestId: string\n balance: PlanBalance\n urlMatching: string\n verbMatching: string\n}\n\nexport interface ValidationAgentRequest {\n balance: PlanBalance\n urlMatching: string\n verbMatching: string\n}\n\nexport interface AgentAccessCredentials {\n accessToken: string\n proxies?: string[]\n}\n\nexport interface SubscriberRequestStatus {\n planId: string\n agentId: string\n isValid: boolean\n code: number\n message?: string\n}\n\nexport interface NvmAPIResult {\n success: boolean\n message?: string\n txHash?: string\n httpStatus?: number\n data?: APIOutputData\n when?: Date\n}\n\nexport interface APIOutputData {\n [key: string]: any\n}\n\nexport interface StripeCheckoutResult {\n stripeCheckoutSessionId: string\n checkoutLink: string\n clientReferenceId: string\n paymentStatus?: string\n linkCreatedAt: number\n linkExpiresAt: number\n}\n\n/**\n * Metadata attributes describing the AI Agent.\n */\nexport interface AgentMetadata {\n /**\n * Name of the Agent\n */\n name: string\n /**\n * Description of the Agent\n */\n description?: string\n /**\n * The author of the Agent (organization or person) that own the Agent.\n */\n author?: string\n /**\n * The author of the Agent (organization or person) that own the Agent.\n */\n license?: string\n /**\n * Tags describing the AI Agent\n */\n tags?: string[]\n /**\n * Some description or instructions about how to integrate the Agent.\n */\n integration?: string\n /**\n * A link to some same usage of the Agent.\n */\n sampleLink?: string\n /**\n * Text describing the API of the Agent.\n */\n apiDescription?: string\n /**\n * The date when the Agent was created.\n */\n dateCreated?: Date\n\n // internalAttributes?: any\n}\n\n/**\n * Metadata attributes describing the Payment Plan.\n */\nexport interface PlanMetadata extends AgentMetadata {\n /**\n * Indicates if a payment plan is a Trial plan.\n * A Trial plan is a plan that allows users to test the AI Agents associated with it typically without any cost.\n * @remarks A Trial plan only can be purchased once by a user.\n */\n isTrialPlan?: boolean\n}\n\n/**\n * It describes the API exposed by an AI Agent.\n * This information is necessary to query the AI Agent and to know which endpoints are available.\n */\nexport interface AgentAPIAttributes {\n /**\n * The list endpoints of the upstream service. All these endpoints are protected and only accessible to subscribers of the Payment Plan.\n */\n endpoints: Endpoint[]\n /**\n * The list of endpoints of the upstream service that publicly available. The access to these endpoints don't require subscription to the Payment Plan. They are useful to expose documentation, etc.\n */\n openEndpoints?: string[]\n /**\n * The URL to the OpenAPI description of the Upstream API. The access to the OpenAPI definition don't require subscription to the Payment Plan.\n */\n openApiUrl?: string\n\n /////// AUTHORIZATION ///////\n\n /**\n * The upstream agent/service authentication type ('none', 'basic', 'bearer' or 'oauth').\n */\n authType?: 'none' | 'basic' | 'oauth' | 'bearer'\n /**\n * The upstream agent/service username for authentication. Only if `authType` is 'basic'.\n */\n username?: string\n /**\n * The upstream agent/service password for authentication. Only if `authType` is 'basic'.\n */\n password?: string\n /**\n * The upstream agent/service bearer token for authentication. Only if `authType` is 'bearer' or 'oauth'.\n */\n token?: string\n}\n\n/**\n * Options for pagination in API requests to the Nevermined API.\n */\nexport class PaginationOptions {\n /**\n * The field to sort the results by.\n * If not provided, the default sorting defined by the API will be applied.\n */\n sortBy?: string\n /**\n * The order in which to sort the results.\n * Default is 'desc' (descending).\n */\n sortOrder: 'asc' | 'desc' = 'desc'\n /**\n * The page number to retrieve.\n * Default is 1.\n */\n page = 1\n /**\n * The number of items per page.\n * Default is 10.\n */\n offset = 10\n\n /**\n * Constructs a new PaginationOptions instance.\n * @param options - Optional initial values for the pagination options.\n */\n constructor(options?: Partial<PaginationOptions>) {\n if (options) {\n this.sortBy = options.sortBy\n this.sortOrder = options.sortOrder || 'desc'\n this.page = options.page || 1\n this.offset = options.offset || 10\n }\n }\n\n /**\n * It returns a string representation of the pagination options\n * @returns A string representation of the pagination options as URL query parameters.\n * This can be used to append to API requests for pagination.\n */\n asQueryParams(): string {\n const params: Record<string, string> = {}\n if (this.sortBy) {\n params.sortBy = this.sortBy\n }\n params.sortOrder = this.sortOrder\n params.page = this.page.toString()\n params.pageSize = this.offset.toString()\n\n return new URLSearchParams(params).toString()\n }\n}\n\n/**\n * Status of an agent task\n */\nexport enum AgentTaskStatus {\n SUCCESS = 'SUCCESS',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n}\n\n/**\n * Data transfer object for tracking agent sub tasks\n */\nexport interface TrackAgentSubTaskDto {\n /**\n * The unique identifier of the agent task\n */\n agentRequestId: string\n\n /**\n * The number of credits burned in this agent sub task (optional)\n * @defaultValue 0\n */\n creditsToRedeem?: number\n\n /**\n * A tag to categorize this agent sub task (optional)\n */\n tag?: string\n\n /**\n * A description of this agent sub task (optional)\n */\n description?: string\n\n /**\n * The status of the agent sub task (optional)\n */\n status?: AgentTaskStatus\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/common/types.ts"],"names":[],"mappings":"AA6HA;;;;;;GAMG;AACH,MAAM,CAAN,IAAY,aAIX;AAJD,WAAY,aAAa;IACvB,+DAAW,CAAA;IACX,yEAAgB,CAAA;IAChB,iFAAoB,CAAA;AACtB,CAAC,EAJW,aAAa,KAAb,aAAa,QAIxB;AAED;;;;;;GAMG;AACH,MAAM,CAAN,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,+DAAS,CAAA;IACT,uDAAK,CAAA;IACL,2DAAO,CAAA;AACT,CAAC,EAJW,eAAe,KAAf,eAAe,QAI1B;AAED;;;;;;GAMG;AACH,MAAM,CAAN,IAAY,kBAIX;AAJD,WAAY,kBAAkB;IAC5B,mFAAgB,CAAA;IAChB,uEAAU,CAAA;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js'\n\n/**\n * Options to initialize the Payments class.\n */\nexport interface PaymentOptions {\n /**\n * The Nevermined environment to connect to.\n * If you are developing an agent it's recommended to use the \"testing\" environment.\n * When deploying to production use the \"arbitrum\" environment.\n */\n environment: EnvironmentName\n\n /**\n * The Nevermined API Key. This key identify your user and is required to interact with the Nevermined API.\n * You can get your API key by logging in to the Nevermined App.\n * @see https://docs.nevermined.app/docs/tutorials/integration/nvm-api-keys\n */\n nvmApiKey: string\n\n /**\n * The URL to return to the app after a successful login.\n */\n returnUrl?: string\n\n /**\n * The app id. This attribute is optional and helps to associate assets registered into Nevermined with a common identifier.\n */\n appId?: string\n\n /**\n * The version of the API to use.\n */\n version?: string\n}\n\nexport interface Endpoint {\n [verb: string]: string\n}\n\nexport interface ApiResponse<T> {\n success: boolean\n data?: T\n error?: string\n}\n\nexport type Address = `0x${string}`\n\n/**\n * Definition of the price configuration for a Payment Plan\n */\nexport interface PlanPriceConfig {\n /**\n * The type or configuration of the price\n * @remarks 0 - crypto fixed price. 1 - fixed fiat price. 2 - smart contract price\n */\n priceType: PlanPriceType\n /**\n * The address of the token (ERC20 or Native if zero address) for paying the plan\n * @remarks only if priceType == FIXED_PRICE or SMART_CONTRACT_PRICE\n */\n tokenAddress?: Address\n /**\n * The amounts to be paid for the plan\n * @remarks only if priceType == FIXED_PRICE or FIXED_FIAT_PRICE\n */\n amounts: bigint[]\n /**\n * The receivers of the payments of the plan\n * @remarks only if priceType == FIXED_PRICE\n */\n receivers: string[]\n /**\n * The address of the smart contract that calculates the price\n * @remarks only if priceType == SMART_CONTRACT_PRICE\n */\n contractAddress?: Address // only if priceType == 2\n /**\n * The address of the fee controller contract, if any\n * @remarks if not given, the fee controller is the default one\n */\n feeController?: Address // only if priceType == 2\n}\n\n/**\n * Definition of the credits configuration for a payment plan\n */\nexport interface PlanCreditsConfig {\n /**\n * The type of configuration of the credits type\n */\n creditsType: PlanCreditsType\n /**\n * How the credits can be redeemed\n */\n redemptionType: PlanRedemptionType\n /**\n * Whether the credits burn proof signed by the user is required\n */\n proofRequired: boolean\n /**\n * The duration of the credits in seconds\n * @remarks only if creditsType == EXPIRABLE\n */\n durationSecs: bigint\n /**\n * The amount of credits that are granted when purchasing the plan\n */\n amount: bigint\n /**\n * The minimum number of credits redeemed when using the plan\n * @remarks only if creditsType == FIXED or DYNAMIC\n */\n minAmount: bigint\n /**\n * The maximum number of credits redeemed when using the plan\n * @remarks only if creditsType == DYNAMIC\n */\n maxAmount: bigint\n /**\n * The address of the NFT contract that represents the plan's credits\n */\n nftAddress?: Address\n}\n\n/**\n * Different types of prices that can be configured for a plan\n * @remarks 0 - FIXED_PRICE, 1 - FIXED_FIAT_PRICE, 2 - SMART_CONTRACT_PRICE\n * If FIXED_PRICE it means the plan can be paid in crypto by a fixed amount of a ERC20 or Native token\n * If FIXED_FIAT_PRICE it means the plan can be paid in fiat by a fixed amount (typically USD)\n * If SMART_CONTRACT_PRICE it means the plan can be paid in crypto and the amount to be paid is calculated by a smart contract\n */\nexport enum PlanPriceType {\n FIXED_PRICE,\n FIXED_FIAT_PRICE,\n SMART_CONTRACT_PRICE,\n}\n\n/**\n * Different types of credits that can be obtained when purchasing a plan\n * @remarks 0 - EXPIRABLE, 1 - FIXED, 2 - DYNAMIC\n * If EXPIRABLE it means the credits can be used for a fixed amount of time (calculated in seconds)\n * If FIXED it means the credits can be used for a fixed amount of times\n * If DYNAMIC it means the credits can be used but the redemption amount is dynamic\n */\nexport enum PlanCreditsType {\n EXPIRABLE,\n FIXED,\n DYNAMIC,\n}\n\n/**\n * Different types of redemptions criterias that can be used when redeeming credits\n * @remarks 0 - ONLY_GLOBAL_ROLE, 1 - ONLY_OWNER, 2 - ROLE_AND_OWNER\n * If ONLY_GLOBAL_ROLE it means the credits can be redeemed only by an account with the `CREDITS_BURNER_ROLE`\n * If ONLY_OWNER it means the credits can be redeemed only by the owner of the Plan\n * If ONLY_PLAN_ROLE it means the credits can be redeemed by an account with specifics grants for the plan\n */\nexport enum PlanRedemptionType {\n ONLY_GLOBAL_ROLE, // NVM Proxy can burn\n ONLY_OWNER, // Agent can burn\n ONLY_PLAN_ROLE,\n}\n\nexport interface PlanBalance {\n planId: string\n planName: string\n planType: string\n holderAddress: Address\n balance: bigint\n creditsContract: Address\n isSubscriber: boolean\n pricePerCredit: number\n}\n\nexport interface StartAgentRequest {\n agentRequestId: string\n agentName: string\n agentId: string\n balance: PlanBalance\n urlMatching: string\n verbMatching: string\n}\n\nexport interface ValidationAgentRequest {\n balance: PlanBalance\n urlMatching: string\n verbMatching: string\n}\n\nexport interface AgentAccessCredentials {\n accessToken: string\n proxies?: string[]\n}\n\nexport interface SubscriberRequestStatus {\n planId: string\n agentId: string\n isValid: boolean\n code: number\n message?: string\n}\n\nexport interface NvmAPIResult {\n success: boolean\n message?: string\n txHash?: string\n httpStatus?: number\n data?: APIOutputData\n when?: Date\n}\n\nexport interface APIOutputData {\n [key: string]: any\n}\n\nexport interface StripeCheckoutResult {\n stripeCheckoutSessionId: string\n checkoutLink: string\n clientReferenceId: string\n paymentStatus?: string\n linkCreatedAt: number\n linkExpiresAt: number\n}\n\n/**\n * Metadata attributes describing the AI Agent.\n */\nexport interface AgentMetadata {\n /**\n * Name of the Agent\n */\n name: string\n /**\n * Description of the Agent\n */\n description?: string\n /**\n * The author of the Agent (organization or person) that own the Agent.\n */\n author?: string\n /**\n * The author of the Agent (organization or person) that own the Agent.\n */\n license?: string\n /**\n * Tags describing the AI Agent\n */\n tags?: string[]\n /**\n * Some description or instructions about how to integrate the Agent.\n */\n integration?: string\n /**\n * A link to some same usage of the Agent.\n */\n sampleLink?: string\n /**\n * Text describing the API of the Agent.\n */\n apiDescription?: string\n /**\n * The date when the Agent was created.\n */\n dateCreated?: Date\n\n // internalAttributes?: any\n}\n\n/**\n * Metadata attributes describing the Payment Plan.\n */\nexport interface PlanMetadata extends AgentMetadata {\n /**\n * Indicates if a payment plan is a Trial plan.\n * A Trial plan is a plan that allows users to test the AI Agents associated with it typically without any cost.\n * @remarks A Trial plan only can be purchased once by a user.\n */\n isTrialPlan?: boolean\n}\n\n/**\n * It describes the API exposed by an AI Agent.\n * This information is necessary to query the AI Agent and to know which endpoints are available.\n */\nexport interface AgentAPIAttributes {\n /**\n * The list endpoints of the upstream service. All these endpoints are protected and only accessible to subscribers of the Payment Plan.\n */\n endpoints: Endpoint[]\n /**\n * The list of endpoints of the upstream service that publicly available. The access to these endpoints don't require subscription to the Payment Plan. They are useful to expose documentation, etc.\n */\n openEndpoints?: string[]\n /**\n * The URL to the OpenAPI description of the Upstream API. The access to the OpenAPI definition don't require subscription to the Payment Plan.\n */\n openApiUrl?: string\n\n /////// AUTHORIZATION ///////\n\n /**\n * The upstream agent/service authentication type ('none', 'basic', 'bearer' or 'oauth').\n */\n authType?: 'none' | 'basic' | 'oauth' | 'bearer'\n /**\n * The upstream agent/service username for authentication. Only if `authType` is 'basic'.\n */\n username?: string\n /**\n * The upstream agent/service password for authentication. Only if `authType` is 'basic'.\n */\n password?: string\n /**\n * The upstream agent/service bearer token for authentication. Only if `authType` is 'bearer' or 'oauth'.\n */\n token?: string\n}\n\n/**\n * Options for pagination in API requests to the Nevermined API.\n */\nexport class PaginationOptions {\n /**\n * The field to sort the results by.\n * If not provided, the default sorting defined by the API will be applied.\n */\n sortBy?: string\n /**\n * The order in which to sort the results.\n * Default is 'desc' (descending).\n */\n sortOrder: 'asc' | 'desc' = 'desc'\n /**\n * The page number to retrieve.\n * Default is 1.\n */\n page = 1\n /**\n * The number of items per page.\n * Default is 10.\n */\n offset = 10\n\n /**\n * Constructs a new PaginationOptions instance.\n * @param options - Optional initial values for the pagination options.\n */\n constructor(options?: Partial<PaginationOptions>) {\n if (options) {\n this.sortBy = options.sortBy\n this.sortOrder = options.sortOrder || 'desc'\n this.page = options.page || 1\n this.offset = options.offset || 10\n }\n }\n\n /**\n * It returns a string representation of the pagination options\n * @returns A string representation of the pagination options as URL query parameters.\n * This can be used to append to API requests for pagination.\n */\n asQueryParams(): string {\n const params: Record<string, string> = {}\n if (this.sortBy) {\n params.sortBy = this.sortBy\n }\n params.sortOrder = this.sortOrder\n params.page = this.page.toString()\n params.pageSize = this.offset.toString()\n\n return new URLSearchParams(params).toString()\n }\n}\n\n/**\n * Status of an agent task\n */\nexport enum AgentTaskStatus {\n SUCCESS = 'SUCCESS',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n}\n\n/**\n * Data transfer object for tracking agent sub tasks\n */\nexport interface TrackAgentSubTaskDto {\n /**\n * The unique identifier of the agent task\n */\n agentRequestId: string\n\n /**\n * The number of credits burned in this agent sub task (optional)\n * @defaultValue 0\n */\n creditsToRedeem?: number\n\n /**\n * A tag to categorize this agent sub task (optional)\n */\n tag?: string\n\n /**\n * A description of this agent sub task (optional)\n */\n description?: string\n\n /**\n * The status of the agent sub task (optional)\n */\n status?: AgentTaskStatus\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paywall.d.ts","sourceRoot":"","sources":["../../../src/mcp/core/paywall.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAA;AAC7D,OAAO,EAEL,SAAS,EACT,WAAW,EACX,eAAe,EACf,aAAa,EACd,MAAM,2BAA2B,CAAA;
|
|
1
|
+
{"version":3,"file":"paywall.d.ts","sourceRoot":"","sources":["../../../src/mcp/core/paywall.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAA;AAC7D,OAAO,EAEL,SAAS,EACT,WAAW,EACX,eAAe,EACf,aAAa,EACd,MAAM,2BAA2B,CAAA;AAIlC;;GAEG;AACH,qBAAa,gBAAgB;IAQzB,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,aAAa;IACrB,OAAO,CAAC,cAAc;IARxB,OAAO,CAAC,MAAM,CAGb;gBAGS,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,oBAAoB,EACnC,cAAc,EAAE,sBAAsB;IAGhD;;OAEG;IACH,SAAS,CAAC,OAAO,EAAE,SAAS,GAAG,IAAI;IAOnC;;OAEG;IAEH,OAAO,CAAC,KAAK,GAAG,GAAG,EACjB,OAAO,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,GAAG,GAAG,EACzD,OAAO,EAAE,WAAW,GAAG,aAAa,GACnC,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC;IAC7C,OAAO,CACL,OAAO,EAAE,CACP,GAAG,EAAE,GAAG,EACR,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,EAC5C,KAAK,CAAC,EAAE,GAAG,KACR,OAAO,CAAC,GAAG,CAAC,GAAG,GAAG,EACvB,OAAO,EAAE,eAAe,GACvB,CAAC,GAAG,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC;IAKxF;;OAEG;IACH,OAAO,CAAC,oBAAoB;IAkE5B;;OAEG;YACW,aAAa;CAsB5B"}
|
package/dist/mcp/core/paywall.js
CHANGED
|
@@ -49,12 +49,21 @@ export class PaywallDecorator {
|
|
|
49
49
|
// 4. If the result is an AsyncIterable (stream), redeem on completion
|
|
50
50
|
if (isAsyncIterable(result)) {
|
|
51
51
|
const onFinally = async () => {
|
|
52
|
-
await this.redeemCredits(authResult.requestId, authResult.token, credits, options);
|
|
52
|
+
return await this.redeemCredits(authResult.requestId, authResult.token, credits, options);
|
|
53
53
|
};
|
|
54
|
-
return wrapAsyncIterable(result, onFinally);
|
|
54
|
+
return wrapAsyncIterable(result, onFinally, authResult.requestId, credits);
|
|
55
55
|
}
|
|
56
56
|
// 5. Non-streaming: redeem immediately
|
|
57
|
-
await this.redeemCredits(authResult.requestId, authResult.token, credits, options);
|
|
57
|
+
const creditsResult = await this.redeemCredits(authResult.requestId, authResult.token, credits, options);
|
|
58
|
+
if (creditsResult.success) {
|
|
59
|
+
result.metadata = {
|
|
60
|
+
...result.metadata,
|
|
61
|
+
txHash: creditsResult.txHash,
|
|
62
|
+
requestId: authResult.requestId,
|
|
63
|
+
creditsRedeemed: credits.toString(),
|
|
64
|
+
success: true,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
58
67
|
return result;
|
|
59
68
|
};
|
|
60
69
|
}
|
|
@@ -62,9 +71,13 @@ export class PaywallDecorator {
|
|
|
62
71
|
* Redeem credits after successful request
|
|
63
72
|
*/
|
|
64
73
|
async redeemCredits(requestId, token, credits, options) {
|
|
74
|
+
let ret = {
|
|
75
|
+
success: true,
|
|
76
|
+
txHash: '',
|
|
77
|
+
};
|
|
65
78
|
try {
|
|
66
79
|
if (credits && credits > 0n) {
|
|
67
|
-
await this.payments.requests.redeemCreditsFromRequest(requestId, token, credits);
|
|
80
|
+
ret = await this.payments.requests.redeemCreditsFromRequest(requestId, token, credits);
|
|
68
81
|
}
|
|
69
82
|
}
|
|
70
83
|
catch (e) {
|
|
@@ -73,6 +86,7 @@ export class PaywallDecorator {
|
|
|
73
86
|
}
|
|
74
87
|
// Default: ignore redemption errors
|
|
75
88
|
}
|
|
89
|
+
return ret;
|
|
76
90
|
}
|
|
77
91
|
}
|
|
78
92
|
/**
|
|
@@ -82,19 +96,29 @@ function isAsyncIterable(value) {
|
|
|
82
96
|
return value != null && typeof value[Symbol.asyncIterator] === 'function';
|
|
83
97
|
}
|
|
84
98
|
/**
|
|
85
|
-
* Wrap an AsyncIterable
|
|
86
|
-
* The wrapped iterable yields the same chunks and triggers onFinally in a finally block.
|
|
99
|
+
* Wrap an AsyncIterable with metadata injection at the end of the stream
|
|
87
100
|
*/
|
|
88
|
-
function wrapAsyncIterable(iterable, onFinally) {
|
|
101
|
+
function wrapAsyncIterable(iterable, onFinally, requestId, credits) {
|
|
89
102
|
async function* generator() {
|
|
103
|
+
let creditsResult = null;
|
|
90
104
|
try {
|
|
91
105
|
for await (const chunk of iterable) {
|
|
92
106
|
yield chunk;
|
|
93
107
|
}
|
|
94
108
|
}
|
|
95
109
|
finally {
|
|
96
|
-
await onFinally();
|
|
110
|
+
creditsResult = await onFinally();
|
|
97
111
|
}
|
|
112
|
+
// Yield a metadata chunk at the end with the redemption result
|
|
113
|
+
const metadataChunk = {
|
|
114
|
+
metadata: {
|
|
115
|
+
txHash: creditsResult?.txHash,
|
|
116
|
+
requestId: requestId,
|
|
117
|
+
creditsRedeemed: credits.toString(),
|
|
118
|
+
success: creditsResult?.success || false,
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
yield metadataChunk;
|
|
98
122
|
}
|
|
99
123
|
return generator();
|
|
100
124
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paywall.js","sourceRoot":"","sources":["../../../src/mcp/core/paywall.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;
|
|
1
|
+
{"version":3,"file":"paywall.js","sourceRoot":"","sources":["../../../src/mcp/core/paywall.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAGhE;;GAEG;AACH,MAAM,OAAO,gBAAgB;IAO3B,YACU,QAAkB,EAClB,aAAmC,EACnC,cAAsC;QAFtC,aAAQ,GAAR,QAAQ,CAAU;QAClB,kBAAa,GAAb,aAAa,CAAsB;QACnC,mBAA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,EAAE,MAAM;gBAC7B,SAAS,EAAE,SAAS;gBACpB,eAAe,EAAE,OAAO,CAAC,QAAQ,EAAE;gBACnC,OAAO,EAAE,aAAa,EAAE,OAAO,IAAI,KAAK;aACzC;SACF,CAAA;QACD,MAAM,aAAkB,CAAA;IAC1B,CAAC;IACD,OAAO,SAAS,EAAE,CAAA;AACpB,CAAC","sourcesContent":["/**\n * Main paywall decorator for MCP handlers (tools, resources, prompts)\n */\nimport type { Payments } from '../../payments.js'\nimport { PaywallAuthenticator } from './auth.js'\nimport { CreditsContextProvider } from './credits-context.js'\nimport {\n PaywallOptions,\n McpConfig,\n ToolOptions,\n ResourceOptions,\n PromptOptions,\n} from '../types/paywall.types.js'\nimport { ERROR_CODES, createRpcError } from '../utils/errors.js'\nimport { NvmAPIResult } from '../../common/types.js'\n\n/**\n * Main class for creating paywall-protected MCP handlers\n */\nexport class PaywallDecorator {\n // Internal config ensures serverName is always a concrete string\n private config: { agentId: string; serverName: string } = {\n agentId: '',\n serverName: 'mcp-server',\n }\n\n constructor(\n private payments: Payments,\n private authenticator: PaywallAuthenticator,\n private creditsContext: CreditsContextProvider,\n ) {}\n\n /**\n * Configure the paywall with agent and server information\n */\n configure(options: McpConfig): void {\n this.config = {\n agentId: options.agentId || this.config.agentId,\n serverName: options.serverName ?? this.config.serverName,\n }\n }\n\n /**\n * Create a paywall-protected handler (uncurried version only)\n */\n // Overloads per kind for stronger typing\n protect<TArgs = any>(\n handler: (args: TArgs, extra?: any) => Promise<any> | any,\n options: ToolOptions | PromptOptions,\n ): (args: TArgs, extra?: any) => Promise<any>\n protect(\n handler: (\n uri: URL,\n variables: Record<string, string | string[]>,\n extra?: any,\n ) => Promise<any> | any,\n options: ResourceOptions,\n ): (uri: URL, variables: Record<string, string | string[]>, extra?: any) => Promise<any>\n protect(handler: any, options: PaywallOptions): any {\n return this.createWrappedHandler(handler, options)\n }\n\n /**\n * Internal method to create the wrapped handler\n */\n private createWrappedHandler<TArgs = any>(\n handler: (args: TArgs, extra?: any) => Promise<any> | any,\n options: PaywallOptions,\n ): (...allArgs: any[]) => Promise<any> {\n return async (...allArgs: any[]): Promise<any> => {\n // Validate configuration\n if (!this.config.agentId) {\n throw createRpcError(\n ERROR_CODES.Misconfiguration,\n 'Server misconfiguration: missing agentId',\n )\n }\n\n const kind = options?.kind ?? 'tool'\n const name = options?.name ?? 'unnamed'\n\n // Detect resource signature: (url, variables, extra)\n const isResource = allArgs.length >= 2 && allArgs[0] instanceof URL\n const extra = isResource ? allArgs[2] : allArgs[1]\n const argsOrVars = isResource ? allArgs[1] : allArgs[0]\n\n // 1. Authenticate request\n const authResult = await this.authenticator.authenticate(\n extra,\n options,\n this.config.agentId,\n this.config.serverName,\n name,\n kind,\n argsOrVars,\n )\n\n // 2. Execute original handler\n const result = await (handler as any)(...allArgs)\n\n // 3. Resolve credits to burn (defaults to 1n when undefined)\n const credits = this.creditsContext.resolve(options?.credits, argsOrVars, result, authResult)\n\n // 4. If the result is an AsyncIterable (stream), redeem on completion\n if (isAsyncIterable(result)) {\n const onFinally = async () => {\n return await this.redeemCredits(authResult.requestId, authResult.token, credits, options)\n }\n return wrapAsyncIterable(result, onFinally, authResult.requestId, credits)\n }\n\n // 5. Non-streaming: redeem immediately\n const creditsResult = await this.redeemCredits(\n authResult.requestId,\n authResult.token,\n credits,\n options,\n )\n if (creditsResult.success) {\n result.metadata = {\n ...result.metadata,\n txHash: creditsResult.txHash,\n requestId: authResult.requestId,\n creditsRedeemed: credits.toString(),\n success: true,\n }\n }\n return result\n }\n }\n\n /**\n * Redeem credits after successful request\n */\n private async redeemCredits(\n requestId: string,\n token: string,\n credits: bigint,\n options: PaywallOptions,\n ): Promise<NvmAPIResult> {\n let ret: NvmAPIResult = {\n success: true,\n txHash: '',\n }\n try {\n if (credits && credits > 0n) {\n ret = await this.payments.requests.redeemCreditsFromRequest(requestId, token, credits)\n }\n } catch (e) {\n if (options.onRedeemError === 'propagate') {\n throw createRpcError(ERROR_CODES.Misconfiguration, 'Failed to redeem credits')\n }\n // Default: ignore redemption errors\n }\n return ret\n }\n}\n\n/**\n * Type guard to detect AsyncIterable values.\n */\nfunction isAsyncIterable<T = unknown>(value: any): value is AsyncIterable<T> {\n return value != null && typeof value[Symbol.asyncIterator] === 'function'\n}\n\n/**\n * Wrap an AsyncIterable with metadata injection at the end of the stream\n */\nfunction wrapAsyncIterable<T>(\n iterable: AsyncIterable<T>,\n onFinally: () => Promise<any>,\n requestId: string,\n credits: bigint,\n) {\n async function* generator() {\n let creditsResult: any = null\n try {\n for await (const chunk of iterable) {\n yield chunk as T\n }\n } finally {\n creditsResult = await onFinally()\n }\n\n // Yield a metadata chunk at the end with the redemption result\n const metadataChunk = {\n metadata: {\n txHash: creditsResult?.txHash,\n requestId: requestId,\n creditsRedeemed: credits.toString(),\n success: creditsResult?.success || false,\n },\n }\n yield metadataChunk as T\n }\n return generator()\n}\n"]}
|