@paid-ai/paid-node 0.0.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -11
  3. package/dist/cjs/Client.d.ts +22 -0
  4. package/dist/cjs/Client.js +45 -2
  5. package/dist/cjs/anthropic-wrapper/index.d.ts +1 -0
  6. package/dist/cjs/anthropic-wrapper/index.js +5 -0
  7. package/dist/cjs/api/resources/agents/client/Client.d.ts +52 -4
  8. package/dist/cjs/api/resources/agents/client/Client.js +52 -4
  9. package/dist/cjs/api/resources/agents/client/requests/AgentCreate.d.ts +4 -2
  10. package/dist/cjs/api/resources/contacts/client/Client.d.ts +4 -7
  11. package/dist/cjs/api/resources/contacts/client/Client.js +4 -7
  12. package/dist/cjs/api/resources/contacts/client/requests/ContactCreate.d.ts +8 -11
  13. package/dist/cjs/api/resources/customers/client/Client.d.ts +8 -2
  14. package/dist/cjs/api/resources/customers/client/Client.js +8 -2
  15. package/dist/cjs/api/resources/customers/client/requests/CustomerCreate.d.ts +2 -1
  16. package/dist/cjs/api/resources/orders/client/Client.d.ts +6 -5
  17. package/dist/cjs/api/resources/orders/client/Client.js +6 -5
  18. package/dist/cjs/api/resources/orders/client/requests/OrderCreate.d.ts +8 -7
  19. package/dist/cjs/api/resources/orders/resources/lines/client/Client.d.ts +11 -1
  20. package/dist/cjs/api/resources/orders/resources/lines/client/Client.js +11 -1
  21. package/dist/cjs/api/resources/orders/resources/lines/client/requests/LinesUpdateRequest.d.ts +11 -1
  22. package/dist/cjs/api/resources/usage/client/Client.d.ts +4 -2
  23. package/dist/cjs/api/resources/usage/client/Client.js +4 -2
  24. package/dist/cjs/api/resources/usage/client/requests/UsageRecordBulkRequest.d.ts +3 -1
  25. package/dist/cjs/api/types/BillingFrequency.d.ts +4 -4
  26. package/dist/cjs/api/types/BillingFrequency.js +3 -3
  27. package/dist/cjs/api/types/Pricing.d.ts +1 -0
  28. package/dist/cjs/api/types/PricingModelType.d.ts +2 -1
  29. package/dist/cjs/api/types/PricingModelType.js +1 -0
  30. package/dist/cjs/api/types/Signal.d.ts +1 -0
  31. package/dist/cjs/index.d.ts +1 -1
  32. package/dist/cjs/index.js +3 -3
  33. package/dist/cjs/langchain-wrapper/index.d.ts +1 -0
  34. package/dist/cjs/langchain-wrapper/index.js +5 -0
  35. package/dist/cjs/mistral-wrapper/index.d.ts +1 -0
  36. package/dist/cjs/mistral-wrapper/index.js +5 -0
  37. package/dist/cjs/openai-wrapper/index.d.ts +1 -0
  38. package/dist/cjs/openai-wrapper/index.js +5 -0
  39. package/dist/cjs/tracing/signal.d.ts +1 -0
  40. package/dist/cjs/tracing/signal.js +54 -0
  41. package/dist/cjs/tracing/tracing.d.ts +8 -0
  42. package/dist/cjs/tracing/tracing.js +127 -0
  43. package/dist/cjs/tracing/wrappers/anthropicWrapper.d.ts +16 -0
  44. package/dist/cjs/tracing/wrappers/anthropicWrapper.js +84 -0
  45. package/dist/cjs/tracing/wrappers/langchainCallback.d.ts +21 -0
  46. package/dist/cjs/tracing/wrappers/langchainCallback.js +142 -0
  47. package/dist/cjs/tracing/wrappers/mistralWrapper.d.ts +17 -0
  48. package/dist/cjs/tracing/wrappers/mistralWrapper.js +81 -0
  49. package/dist/cjs/tracing/wrappers/openAiWrapper.d.ts +48 -0
  50. package/dist/cjs/tracing/wrappers/openAiWrapper.js +241 -0
  51. package/dist/cjs/tracing/wrappers/vercelAIWrapper.d.ts +22 -0
  52. package/dist/cjs/tracing/wrappers/vercelAIWrapper.js +327 -0
  53. package/dist/cjs/vercel-wrapper/index.d.ts +1 -0
  54. package/dist/cjs/vercel-wrapper/index.js +10 -0
  55. package/dist/cjs/version.d.ts +1 -1
  56. package/dist/cjs/version.js +1 -1
  57. package/dist/cjs/wrapper/BatchUsage.d.ts +3 -3
  58. package/dist/cjs/wrapper/BatchUsage.js +4 -4
  59. package/dist/esm/Client.d.mts +22 -0
  60. package/dist/esm/Client.mjs +45 -2
  61. package/dist/esm/anthropic-wrapper/index.d.mts +1 -0
  62. package/dist/esm/anthropic-wrapper/index.mjs +1 -0
  63. package/dist/esm/api/resources/agents/client/Client.d.mts +52 -4
  64. package/dist/esm/api/resources/agents/client/Client.mjs +52 -4
  65. package/dist/esm/api/resources/agents/client/requests/AgentCreate.d.mts +4 -2
  66. package/dist/esm/api/resources/contacts/client/Client.d.mts +4 -7
  67. package/dist/esm/api/resources/contacts/client/Client.mjs +4 -7
  68. package/dist/esm/api/resources/contacts/client/requests/ContactCreate.d.mts +8 -11
  69. package/dist/esm/api/resources/customers/client/Client.d.mts +8 -2
  70. package/dist/esm/api/resources/customers/client/Client.mjs +8 -2
  71. package/dist/esm/api/resources/customers/client/requests/CustomerCreate.d.mts +2 -1
  72. package/dist/esm/api/resources/orders/client/Client.d.mts +6 -5
  73. package/dist/esm/api/resources/orders/client/Client.mjs +6 -5
  74. package/dist/esm/api/resources/orders/client/requests/OrderCreate.d.mts +8 -7
  75. package/dist/esm/api/resources/orders/resources/lines/client/Client.d.mts +11 -1
  76. package/dist/esm/api/resources/orders/resources/lines/client/Client.mjs +11 -1
  77. package/dist/esm/api/resources/orders/resources/lines/client/requests/LinesUpdateRequest.d.mts +11 -1
  78. package/dist/esm/api/resources/usage/client/Client.d.mts +4 -2
  79. package/dist/esm/api/resources/usage/client/Client.mjs +4 -2
  80. package/dist/esm/api/resources/usage/client/requests/UsageRecordBulkRequest.d.mts +3 -1
  81. package/dist/esm/api/types/BillingFrequency.d.mts +4 -4
  82. package/dist/esm/api/types/BillingFrequency.mjs +3 -3
  83. package/dist/esm/api/types/Pricing.d.mts +1 -0
  84. package/dist/esm/api/types/PricingModelType.d.mts +2 -1
  85. package/dist/esm/api/types/PricingModelType.mjs +1 -0
  86. package/dist/esm/api/types/Signal.d.mts +1 -0
  87. package/dist/esm/index.d.mts +1 -1
  88. package/dist/esm/index.mjs +1 -1
  89. package/dist/esm/langchain-wrapper/index.d.mts +1 -0
  90. package/dist/esm/langchain-wrapper/index.mjs +1 -0
  91. package/dist/esm/mistral-wrapper/index.d.mts +1 -0
  92. package/dist/esm/mistral-wrapper/index.mjs +1 -0
  93. package/dist/esm/openai-wrapper/index.d.mts +1 -0
  94. package/dist/esm/openai-wrapper/index.mjs +1 -0
  95. package/dist/esm/tracing/signal.d.mts +1 -0
  96. package/dist/esm/tracing/signal.mjs +51 -0
  97. package/dist/esm/tracing/tracing.d.mts +8 -0
  98. package/dist/esm/tracing/tracing.mjs +116 -0
  99. package/dist/esm/tracing/wrappers/anthropicWrapper.d.mts +16 -0
  100. package/dist/esm/tracing/wrappers/anthropicWrapper.mjs +80 -0
  101. package/dist/esm/tracing/wrappers/langchainCallback.d.mts +21 -0
  102. package/dist/esm/tracing/wrappers/langchainCallback.mjs +138 -0
  103. package/dist/esm/tracing/wrappers/mistralWrapper.d.mts +17 -0
  104. package/dist/esm/tracing/wrappers/mistralWrapper.mjs +77 -0
  105. package/dist/esm/tracing/wrappers/openAiWrapper.d.mts +48 -0
  106. package/dist/esm/tracing/wrappers/openAiWrapper.mjs +237 -0
  107. package/dist/esm/tracing/wrappers/vercelAIWrapper.d.mts +22 -0
  108. package/dist/esm/tracing/wrappers/vercelAIWrapper.mjs +319 -0
  109. package/dist/esm/vercel-wrapper/index.d.mts +1 -0
  110. package/dist/esm/vercel-wrapper/index.mjs +1 -0
  111. package/dist/esm/version.d.mts +1 -1
  112. package/dist/esm/version.mjs +1 -1
  113. package/dist/esm/wrapper/BatchUsage.d.mts +3 -3
  114. package/dist/esm/wrapper/BatchUsage.mjs +3 -3
  115. package/package.json +102 -4
  116. package/reference.md +96 -21
@@ -33,7 +33,17 @@ export declare class Lines {
33
33
  * @param {Lines.RequestOptions} requestOptions - Request-specific configuration.
34
34
  *
35
35
  * @example
36
- * await client.orders.lines.update("orderId")
36
+ * await client.orders.lines.update("orderId", {
37
+ * lines: [{
38
+ * agentExternalId: "acme-agent",
39
+ * name: "Order Line One",
40
+ * description: "Order Line One is an order line for Acme, Inc."
41
+ * }, {
42
+ * agentExternalId: "acme-agent-2",
43
+ * name: "Order Line Two",
44
+ * description: "Order Line Two is an order line for Acme, Inc."
45
+ * }]
46
+ * })
37
47
  */
38
48
  update(orderId: string, request?: Paid.orders.LinesUpdateRequest, requestOptions?: Lines.RequestOptions): core.HttpResponsePromise<Paid.Order>;
39
49
  private __update;
@@ -64,7 +64,17 @@ class Lines {
64
64
  * @param {Lines.RequestOptions} requestOptions - Request-specific configuration.
65
65
  *
66
66
  * @example
67
- * await client.orders.lines.update("orderId")
67
+ * await client.orders.lines.update("orderId", {
68
+ * lines: [{
69
+ * agentExternalId: "acme-agent",
70
+ * name: "Order Line One",
71
+ * description: "Order Line One is an order line for Acme, Inc."
72
+ * }, {
73
+ * agentExternalId: "acme-agent-2",
74
+ * name: "Order Line Two",
75
+ * description: "Order Line Two is an order line for Acme, Inc."
76
+ * }]
77
+ * })
68
78
  */
69
79
  update(orderId, request = {}, requestOptions) {
70
80
  return core.HttpResponsePromise.fromPromise(this.__update(orderId, request, requestOptions));
@@ -4,7 +4,17 @@
4
4
  import * as Paid from "../../../../../../index.js";
5
5
  /**
6
6
  * @example
7
- * {}
7
+ * {
8
+ * lines: [{
9
+ * agentExternalId: "acme-agent",
10
+ * name: "Order Line One",
11
+ * description: "Order Line One is an order line for Acme, Inc."
12
+ * }, {
13
+ * agentExternalId: "acme-agent-2",
14
+ * name: "Order Line Two",
15
+ * description: "Order Line Two is an order line for Acme, Inc."
16
+ * }]
17
+ * }
8
18
  */
9
19
  export interface LinesUpdateRequest {
10
20
  lines?: Paid.OrderLineCreate[];
@@ -32,9 +32,11 @@ export declare class Usage {
32
32
  * @param {Usage.RequestOptions} requestOptions - Request-specific configuration.
33
33
  *
34
34
  * @example
35
- * await client.usage.recordBulk()
35
+ * await client.usage.recordBulk({
36
+ * signals: [{}, {}, {}]
37
+ * })
36
38
  */
37
- recordBulk(request?: Paid.UsageRecordBulkRequest, requestOptions?: Usage.RequestOptions): core.HttpResponsePromise<unknown[]>;
39
+ recordBulk(request?: Paid.UsageRecordBulkRequest, requestOptions?: Usage.RequestOptions): core.HttpResponsePromise<void>;
38
40
  private __recordBulk;
39
41
  protected _getAuthorizationHeader(): Promise<string>;
40
42
  }
@@ -63,7 +63,9 @@ class Usage {
63
63
  * @param {Usage.RequestOptions} requestOptions - Request-specific configuration.
64
64
  *
65
65
  * @example
66
- * await client.usage.recordBulk()
66
+ * await client.usage.recordBulk({
67
+ * signals: [{}, {}, {}]
68
+ * })
67
69
  */
68
70
  recordBulk(request = {}, requestOptions) {
69
71
  return core.HttpResponsePromise.fromPromise(this.__recordBulk(request, requestOptions));
@@ -83,7 +85,7 @@ class Usage {
83
85
  abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal,
84
86
  });
85
87
  if (_response.ok) {
86
- return { data: _response.body, rawResponse: _response.rawResponse };
88
+ return { data: undefined, rawResponse: _response.rawResponse };
87
89
  }
88
90
  if (_response.error.reason === "status-code") {
89
91
  throw new errors.PaidError({
@@ -4,7 +4,9 @@
4
4
  import * as Paid from "../../../../index.js";
5
5
  /**
6
6
  * @example
7
- * {}
7
+ * {
8
+ * signals: [{}, {}, {}]
9
+ * }
8
10
  */
9
11
  export interface UsageRecordBulkRequest {
10
12
  signals?: Paid.Signal[];
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * This file was auto-generated by Fern from our API Definition.
3
3
  */
4
- export type BillingFrequency = "Monthly" | "Quarterly" | "Annual";
4
+ export type BillingFrequency = "monthly" | "quarterly" | "annual";
5
5
  export declare const BillingFrequency: {
6
- readonly Monthly: "Monthly";
7
- readonly Quarterly: "Quarterly";
8
- readonly Annual: "Annual";
6
+ readonly Monthly: "monthly";
7
+ readonly Quarterly: "quarterly";
8
+ readonly Annual: "annual";
9
9
  };
@@ -5,7 +5,7 @@
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.BillingFrequency = void 0;
7
7
  exports.BillingFrequency = {
8
- Monthly: "Monthly",
9
- Quarterly: "Quarterly",
10
- Annual: "Annual",
8
+ Monthly: "monthly",
9
+ Quarterly: "quarterly",
10
+ Annual: "annual",
11
11
  };
@@ -5,6 +5,7 @@ import * as Paid from "../index.js";
5
5
  export interface Pricing {
6
6
  eventName?: string;
7
7
  taxable: boolean;
8
+ creditCost?: number;
8
9
  chargeType: Paid.ChargeType;
9
10
  pricingModel: Paid.PricingModelType;
10
11
  billingFrequency: Paid.BillingFrequency;
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * This file was auto-generated by Fern from our API Definition.
3
3
  */
4
- export type PricingModelType = "PerUnit" | "VolumePricing" | "GraduatedPricing";
4
+ export type PricingModelType = "PerUnit" | "VolumePricing" | "GraduatedPricing" | "PrepaidCredits";
5
5
  export declare const PricingModelType: {
6
6
  readonly PerUnit: "PerUnit";
7
7
  readonly VolumePricing: "VolumePricing";
8
8
  readonly GraduatedPricing: "GraduatedPricing";
9
+ readonly PrepaidCredits: "PrepaidCredits";
9
10
  };
@@ -8,4 +8,5 @@ exports.PricingModelType = {
8
8
  PerUnit: "PerUnit",
9
9
  VolumePricing: "VolumePricing",
10
10
  GraduatedPricing: "GraduatedPricing",
11
+ PrepaidCredits: "PrepaidCredits",
11
12
  };
@@ -4,6 +4,7 @@
4
4
  export interface Signal {
5
5
  event_name?: string;
6
6
  agent_id?: string;
7
+ external_agent_id?: string;
7
8
  customer_id?: string;
8
9
  data?: Record<string, unknown>;
9
10
  }
@@ -1,4 +1,4 @@
1
1
  export * as Paid from "./api/index.js";
2
2
  export { PaidClient } from "./Client.js";
3
- export { PaidEnvironment } from "./environments.js";
4
3
  export { PaidError, PaidTimeoutError } from "./errors/index.js";
4
+ export { PaidEnvironment } from "./environments.js";
package/dist/cjs/index.js CHANGED
@@ -33,12 +33,12 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.PaidTimeoutError = exports.PaidError = exports.PaidEnvironment = exports.PaidClient = exports.Paid = void 0;
36
+ exports.PaidEnvironment = exports.PaidTimeoutError = exports.PaidError = exports.PaidClient = exports.Paid = void 0;
37
37
  exports.Paid = __importStar(require("./api/index.js"));
38
38
  var Client_js_1 = require("./Client.js");
39
39
  Object.defineProperty(exports, "PaidClient", { enumerable: true, get: function () { return Client_js_1.PaidClient; } });
40
- var environments_js_1 = require("./environments.js");
41
- Object.defineProperty(exports, "PaidEnvironment", { enumerable: true, get: function () { return environments_js_1.PaidEnvironment; } });
42
40
  var index_js_1 = require("./errors/index.js");
43
41
  Object.defineProperty(exports, "PaidError", { enumerable: true, get: function () { return index_js_1.PaidError; } });
44
42
  Object.defineProperty(exports, "PaidTimeoutError", { enumerable: true, get: function () { return index_js_1.PaidTimeoutError; } });
43
+ var environments_js_1 = require("./environments.js");
44
+ Object.defineProperty(exports, "PaidEnvironment", { enumerable: true, get: function () { return environments_js_1.PaidEnvironment; } });
@@ -0,0 +1 @@
1
+ export { PaidLangChainCallback } from "../tracing/wrappers/langchainCallback.js";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PaidLangChainCallback = void 0;
4
+ var langchainCallback_js_1 = require("../tracing/wrappers/langchainCallback.js");
5
+ Object.defineProperty(exports, "PaidLangChainCallback", { enumerable: true, get: function () { return langchainCallback_js_1.PaidLangChainCallback; } });
@@ -0,0 +1 @@
1
+ export { PaidMistral } from "../tracing/wrappers/mistralWrapper.js";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PaidMistral = void 0;
4
+ var mistralWrapper_js_1 = require("../tracing/wrappers/mistralWrapper.js");
5
+ Object.defineProperty(exports, "PaidMistral", { enumerable: true, get: function () { return mistralWrapper_js_1.PaidMistral; } });
@@ -0,0 +1 @@
1
+ export { PaidOpenAI } from "../tracing/wrappers/openAiWrapper.js";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PaidOpenAI = void 0;
4
+ var openAiWrapper_js_1 = require("../tracing/wrappers/openAiWrapper.js");
5
+ Object.defineProperty(exports, "PaidOpenAI", { enumerable: true, get: function () { return openAiWrapper_js_1.PaidOpenAI; } });
@@ -0,0 +1 @@
1
+ export declare function _signal(eventName: string, enableCostTracing: boolean, data?: Record<string, any>): void;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports._signal = _signal;
4
+ const api_1 = require("@opentelemetry/api");
5
+ const tracing_js_1 = require("./tracing.js");
6
+ const tracing_js_2 = require("./tracing.js");
7
+ function _signal(eventName, enableCostTracing, data) {
8
+ if (!eventName) {
9
+ throw new Error("Event name is required for signal.");
10
+ }
11
+ const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
12
+ const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
13
+ const token = (0, tracing_js_1.getTokenStorage)();
14
+ if (!externalCustomerId || !externalAgentId || !token) {
15
+ throw new Error(`Missing some of: external_customer_id: ${externalCustomerId}, external_agent_id: ${externalAgentId}, or token. Make sure to call signal() within trace()`);
16
+ }
17
+ tracing_js_2.paidTracer.startActiveSpan("trace.signal", (span) => {
18
+ try {
19
+ const attributes = {
20
+ external_customer_id: externalCustomerId,
21
+ external_agent_id: externalAgentId,
22
+ event_name: eventName,
23
+ token: token,
24
+ };
25
+ if (enableCostTracing) {
26
+ // let the app know to associate this signal with cost traces
27
+ attributes["enable_cost_tracing"] = true;
28
+ if (data === undefined) {
29
+ data = { paid: { enable_cost_tracing: true } };
30
+ }
31
+ else {
32
+ data["paid"] = { enable_cost_tracing: true };
33
+ }
34
+ }
35
+ // Optional data (ex. manual cost tracking)
36
+ if (data) {
37
+ attributes["data"] = JSON.stringify(data);
38
+ }
39
+ span.setAttributes(attributes);
40
+ // Mark span as successful
41
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
42
+ }
43
+ catch (error) {
44
+ span.setStatus({
45
+ code: api_1.SpanStatusCode.ERROR,
46
+ message: error.message,
47
+ });
48
+ span.recordException(error);
49
+ }
50
+ finally {
51
+ span.end();
52
+ }
53
+ });
54
+ }
@@ -0,0 +1,8 @@
1
+ import winston from "winston";
2
+ export declare const logger: winston.Logger;
3
+ export declare let paidTracer: import("@opentelemetry/api").Tracer;
4
+ export declare const getCustomerIdStorage: () => string | null | undefined;
5
+ export declare const getAgentIdStorage: () => string | null | undefined;
6
+ export declare const getTokenStorage: () => string | null | undefined;
7
+ export declare function _initializeTracing(apiKey: string, collectorEndpoint?: string): void;
8
+ export declare function _trace<T extends (...args: any[]) => any>(externalCustomerId: string, fn: T, externalAgentId: string | undefined, ...args: Parameters<T>): Promise<ReturnType<T>>;
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.getTokenStorage = exports.getAgentIdStorage = exports.getCustomerIdStorage = exports.paidTracer = exports.logger = void 0;
16
+ exports._initializeTracing = _initializeTracing;
17
+ exports._trace = _trace;
18
+ const sdk_trace_node_1 = require("@opentelemetry/sdk-trace-node");
19
+ const exporter_trace_otlp_http_1 = require("@opentelemetry/exporter-trace-otlp-http");
20
+ const sdk_trace_base_1 = require("@opentelemetry/sdk-trace-base");
21
+ const api_1 = require("@opentelemetry/api");
22
+ const async_hooks_1 = require("async_hooks");
23
+ const winston_1 = __importDefault(require("winston"));
24
+ exports.logger = winston_1.default.createLogger({
25
+ level: "silent", // Default to 'silent' to avoid logging unless set via environment variable
26
+ format: winston_1.default.format.simple(),
27
+ transports: [new winston_1.default.transports.Console()],
28
+ });
29
+ const logLevel = process.env.PAID_LOG_LEVEL;
30
+ if (logLevel) {
31
+ exports.logger.level = logLevel;
32
+ }
33
+ const COLLECTOR_ENDPOINT = process.env.PAID_COLLECTOR_ENDPOINT || "https://collector.agentpaid.io:4318/v1/traces";
34
+ // set up default tracing provider
35
+ let paidExporter = new exporter_trace_otlp_http_1.OTLPTraceExporter({ url: COLLECTOR_ENDPOINT });
36
+ let spanProcessor = new sdk_trace_base_1.BatchSpanProcessor(paidExporter);
37
+ let paidTracerProvider = new sdk_trace_node_1.NodeTracerProvider({ spanProcessors: [spanProcessor] });
38
+ paidTracerProvider.register();
39
+ exports.paidTracer = paidTracerProvider.getTracer("paid.node");
40
+ // storage for passing info to child spans
41
+ const customerIdStorage = new async_hooks_1.AsyncLocalStorage();
42
+ const agentIdStorage = new async_hooks_1.AsyncLocalStorage();
43
+ const tokenStorage = new async_hooks_1.AsyncLocalStorage();
44
+ const getCustomerIdStorage = () => customerIdStorage.getStore();
45
+ exports.getCustomerIdStorage = getCustomerIdStorage;
46
+ const getAgentIdStorage = () => agentIdStorage.getStore();
47
+ exports.getAgentIdStorage = getAgentIdStorage;
48
+ const getTokenStorage = () => tokenStorage.getStore();
49
+ exports.getTokenStorage = getTokenStorage;
50
+ let _token;
51
+ const setToken = (token) => {
52
+ _token = token;
53
+ };
54
+ const getToken = () => {
55
+ return _token;
56
+ };
57
+ let _isShuttingDown = false;
58
+ function setupGracefulShutdown(shuttable) {
59
+ ["SIGINT", "SIGTERM", "beforeExit", "uncaughtException", "unhandledRejection"].forEach((signal) => {
60
+ process.on(signal, () => {
61
+ if (_isShuttingDown) {
62
+ return;
63
+ }
64
+ _isShuttingDown = true;
65
+ shuttable
66
+ .shutdown()
67
+ .then(() => exports.logger.info(`Paid tracing SDK shut down from signal: ${signal}`))
68
+ .catch((error) => exports.logger.error(`Error shutting down Paid tracing SDK ${error}`));
69
+ });
70
+ });
71
+ }
72
+ function _initializeTracing(apiKey, collectorEndpoint) {
73
+ if (getToken()) {
74
+ throw new Error("Tracing SDK is already initialized.");
75
+ }
76
+ if (!apiKey) {
77
+ throw new Error("Cannot initialize tracing SDK - first initialize the PaidClient with an API key");
78
+ }
79
+ if (collectorEndpoint) {
80
+ paidExporter = new exporter_trace_otlp_http_1.OTLPTraceExporter({ url: collectorEndpoint });
81
+ spanProcessor = new sdk_trace_base_1.BatchSpanProcessor(paidExporter);
82
+ paidTracerProvider = new sdk_trace_node_1.NodeTracerProvider({ spanProcessors: [spanProcessor] });
83
+ paidTracerProvider.register();
84
+ exports.paidTracer = paidTracerProvider.getTracer("paid.node");
85
+ }
86
+ setupGracefulShutdown(spanProcessor);
87
+ setToken(apiKey);
88
+ const collectorAddress = collectorEndpoint || COLLECTOR_ENDPOINT;
89
+ exports.logger.info(`Paid tracing SDK initialized with collector endpoint: ${collectorAddress}`);
90
+ }
91
+ function _trace(externalCustomerId, fn, externalAgentId, ...args) {
92
+ return __awaiter(this, void 0, void 0, function* () {
93
+ const token = getToken();
94
+ if (!token || !externalCustomerId) {
95
+ throw new Error(`Paid tracing is not initialized. Make sure to call initializeTracing() first.`);
96
+ }
97
+ return exports.paidTracer.startActiveSpan("paid.node", (span) => __awaiter(this, void 0, void 0, function* () {
98
+ span.setAttribute("external_customer_id", externalCustomerId);
99
+ span.setAttribute("token", token);
100
+ if (externalAgentId) {
101
+ span.setAttribute("external_agent_id", externalAgentId);
102
+ }
103
+ try {
104
+ const result = yield customerIdStorage.run(externalCustomerId, () => __awaiter(this, void 0, void 0, function* () {
105
+ return yield agentIdStorage.run(externalAgentId !== null && externalAgentId !== void 0 ? externalAgentId : null, () => __awaiter(this, void 0, void 0, function* () {
106
+ return yield tokenStorage.run(token, () => __awaiter(this, void 0, void 0, function* () {
107
+ return yield fn(...args);
108
+ }));
109
+ }));
110
+ }));
111
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
112
+ return result;
113
+ }
114
+ catch (error) {
115
+ span.setStatus({
116
+ code: api_1.SpanStatusCode.ERROR,
117
+ message: error.message,
118
+ });
119
+ span.recordException(error);
120
+ throw error;
121
+ }
122
+ finally {
123
+ span.end();
124
+ }
125
+ }));
126
+ });
127
+ }
@@ -0,0 +1,16 @@
1
+ import Anthropic from "@anthropic-ai/sdk";
2
+ import { Tracer } from "@opentelemetry/api";
3
+ import { MessageCreateParams } from "@anthropic-ai/sdk/resources/messages";
4
+ export declare class PaidAnthropic {
5
+ private readonly anthropic;
6
+ private readonly tracer;
7
+ constructor(anthropicClient: Anthropic);
8
+ get messages(): MessagesWrapper;
9
+ }
10
+ declare class MessagesWrapper {
11
+ private anthropic;
12
+ private tracer;
13
+ constructor(anthropic: Anthropic, tracer: Tracer);
14
+ create(params: MessageCreateParams): Promise<any>;
15
+ }
16
+ export {};
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.PaidAnthropic = void 0;
13
+ const api_1 = require("@opentelemetry/api");
14
+ const tracing_js_1 = require("../tracing.js");
15
+ class PaidAnthropic {
16
+ constructor(anthropicClient) {
17
+ this.anthropic = anthropicClient;
18
+ this.tracer = tracing_js_1.paidTracer;
19
+ }
20
+ get messages() {
21
+ return new MessagesWrapper(this.anthropic, this.tracer);
22
+ }
23
+ }
24
+ exports.PaidAnthropic = PaidAnthropic;
25
+ class MessagesWrapper {
26
+ constructor(anthropic, tracer) {
27
+ this.anthropic = anthropic;
28
+ this.tracer = tracer;
29
+ }
30
+ create(params) {
31
+ return __awaiter(this, void 0, void 0, function* () {
32
+ const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
33
+ const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
34
+ const token = (0, tracing_js_1.getTokenStorage)();
35
+ if (!token || !externalCustomerId) {
36
+ throw new Error("No token or externalCustomerId: This wrapper should be used inside a callback to paid.trace().");
37
+ }
38
+ return this.tracer.startActiveSpan("trace.anthropic.messages", (span) => __awaiter(this, void 0, void 0, function* () {
39
+ const attributes = {
40
+ "gen_ai.system": "anthropic",
41
+ "gen_ai.operation.name": "messages",
42
+ external_customer_id: externalCustomerId,
43
+ token: token,
44
+ };
45
+ if (externalAgentId) {
46
+ attributes["external_agent_id"] = externalAgentId;
47
+ }
48
+ // Set request model from params
49
+ if (params.model) {
50
+ attributes["gen_ai.request.model"] = params.model;
51
+ }
52
+ span.setAttributes(attributes);
53
+ try {
54
+ const response = (yield this.anthropic.messages.create(params));
55
+ // Add usage information from response
56
+ if (response.usage) {
57
+ span.setAttributes({
58
+ "gen_ai.usage.input_tokens": response.usage.input_tokens,
59
+ "gen_ai.usage.output_tokens": response.usage.output_tokens,
60
+ "gen_ai.response.model": response.model,
61
+ });
62
+ // Add Anthropic-specific cache usage if available
63
+ if ("cache_creation_input_tokens" in response.usage && response.usage.cache_creation_input_tokens) {
64
+ span.setAttribute("gen_ai.usage.cache_creation_input_tokens", response.usage.cache_creation_input_tokens);
65
+ }
66
+ if ("cache_read_input_tokens" in response.usage && response.usage.cache_read_input_tokens) {
67
+ span.setAttribute("gen_ai.usage.cache_read_input_tokens", response.usage.cache_read_input_tokens);
68
+ }
69
+ }
70
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
71
+ return response;
72
+ }
73
+ catch (error) {
74
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
75
+ span.recordException(error);
76
+ throw error;
77
+ }
78
+ finally {
79
+ span.end();
80
+ }
81
+ }));
82
+ });
83
+ }
84
+ }
@@ -0,0 +1,21 @@
1
+ import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
2
+ interface SerializedData {
3
+ id?: string[];
4
+ [key: string]: any;
5
+ }
6
+ interface Metadata {
7
+ ls_model_type?: string;
8
+ ls_model_name?: string;
9
+ [key: string]: any;
10
+ }
11
+ export declare class PaidLangChainCallback extends BaseCallbackHandler {
12
+ name: string;
13
+ private tracer;
14
+ private spans;
15
+ constructor();
16
+ private extractProvider;
17
+ handleLLMStart(llm: SerializedData, prompts: string[], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Metadata): Promise<void>;
18
+ handleLLMEnd(output: any, runId: string, parentRunId?: string): Promise<void>;
19
+ handleLLMError(err: Error, runId: string, parentRunId?: string): Promise<void>;
20
+ }
21
+ export {};