@paid-ai/paid-node 0.0.8-alpha1 → 0.0.8-alpha2
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 +17 -16
- package/dist/cjs/Client.d.ts +4 -2
- package/dist/cjs/Client.js +21 -4
- package/dist/cjs/index.d.ts +3 -1
- package/dist/cjs/index.js +7 -4
- package/dist/cjs/tracing/signal.d.ts +1 -0
- package/dist/cjs/tracing/signal.js +49 -0
- package/dist/cjs/tracing/tracing.d.ts +8 -3
- package/dist/cjs/tracing/tracing.js +100 -28
- package/dist/cjs/tracing/wrappers/anthropicWrapper.d.ts +16 -0
- package/dist/cjs/tracing/wrappers/anthropicWrapper.js +88 -0
- package/dist/cjs/tracing/wrappers/langchainCallback.d.ts +21 -0
- package/dist/cjs/tracing/wrappers/langchainCallback.js +146 -0
- package/dist/cjs/tracing/wrappers/mistralWrapper.d.ts +17 -0
- package/dist/cjs/tracing/wrappers/mistralWrapper.js +85 -0
- package/dist/cjs/tracing/wrappers/openAiWrapper.js +48 -46
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/wrapper/BatchUsage.d.ts +1 -1
- package/dist/cjs/wrapper/BatchUsage.js +2 -2
- package/dist/esm/Client.d.mts +4 -2
- package/dist/esm/Client.mjs +22 -5
- package/dist/esm/index.d.mts +3 -1
- package/dist/esm/index.mjs +3 -1
- package/dist/esm/tracing/signal.d.mts +1 -0
- package/dist/esm/tracing/signal.mjs +46 -0
- package/dist/esm/tracing/tracing.d.mts +8 -3
- package/dist/esm/tracing/tracing.mjs +94 -27
- package/dist/esm/tracing/wrappers/anthropicWrapper.d.mts +16 -0
- package/dist/esm/tracing/wrappers/anthropicWrapper.mjs +84 -0
- package/dist/esm/tracing/wrappers/langchainCallback.d.mts +21 -0
- package/dist/esm/tracing/wrappers/langchainCallback.mjs +142 -0
- package/dist/esm/tracing/wrappers/mistralWrapper.d.mts +17 -0
- package/dist/esm/tracing/wrappers/mistralWrapper.mjs +81 -0
- package/dist/esm/tracing/wrappers/openAiWrapper.mjs +44 -42
- package/dist/esm/version.d.mts +1 -1
- package/dist/esm/version.mjs +1 -1
- package/dist/esm/wrapper/BatchUsage.d.mts +1 -1
- package/dist/esm/wrapper/BatchUsage.mjs +1 -1
- package/package.json +7 -3
- package/dist/cjs/tracing/index.d.ts +0 -1
- package/dist/cjs/tracing/index.js +0 -17
- package/dist/esm/tracing/index.d.mts +0 -1
- package/dist/esm/tracing/index.mjs +0 -1
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
</picture>
|
|
8
8
|
</div>
|
|
9
9
|
|
|
10
|
-
#
|
|
10
|
+
#
|
|
11
11
|
|
|
12
12
|
<div align="center">
|
|
13
13
|
<a href="https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=https%3A%2F%2Fgithub.com%2FAgentPaid%2Fpaid-node">
|
|
@@ -18,8 +18,8 @@
|
|
|
18
18
|
</a>
|
|
19
19
|
</div>
|
|
20
20
|
|
|
21
|
-
Paid is the all-in-one, drop-in Business Engine for AI Agents that handles your pricing, subscriptions, margins, billing, and renewals with just 5 lines of code.
|
|
22
|
-
The Paid TypeScript library provides convenient access to the Paid API from TypeScript.
|
|
21
|
+
Paid is the all-in-one, drop-in Business Engine for AI Agents that handles your pricing, subscriptions, margins, billing, and renewals with just 5 lines of code.
|
|
22
|
+
The Paid TypeScript library provides convenient access to the Paid API from TypeScript.
|
|
23
23
|
|
|
24
24
|
## Documentation
|
|
25
25
|
|
|
@@ -33,7 +33,7 @@ npm install -s @paid-ai/paid-node
|
|
|
33
33
|
|
|
34
34
|
## Usage
|
|
35
35
|
|
|
36
|
-
The client needs to be configured with your account's API key, which is available in the [Paid dashboard](https://app.paid.ai/agent-integration/api-keys).
|
|
36
|
+
The client needs to be configured with your account's API key, which is available in the [Paid dashboard](https://app.paid.ai/agent-integration/api-keys).
|
|
37
37
|
|
|
38
38
|
```typescript
|
|
39
39
|
import { PaidClient } from "@paid-ai/paid-node";
|
|
@@ -78,17 +78,18 @@ try {
|
|
|
78
78
|
}
|
|
79
79
|
```
|
|
80
80
|
|
|
81
|
+
## Logging
|
|
82
|
+
Logs are silent by default.
|
|
83
|
+
|
|
84
|
+
To enable logs, set the `PAID_LOG_LEVEL` environment variable. Available levels include:
|
|
85
|
+
`error`, `warn`, `info`, `http`, `verbose`, `debug`, and `silly`.
|
|
86
|
+
|
|
87
|
+
Example: `PAID_LOG_LEVEL=debug node your-app.js`
|
|
88
|
+
|
|
81
89
|
## Cost Tracking
|
|
82
90
|
|
|
83
91
|
It's possible to track usage costs by using Paid wrappers around you AI provider API.
|
|
84
|
-
As of now, the following
|
|
85
|
-
|
|
86
|
-
```
|
|
87
|
-
chat.completions.create()
|
|
88
|
-
responses.create()
|
|
89
|
-
images.generate()
|
|
90
|
-
embeddings.create()
|
|
91
|
-
```
|
|
92
|
+
As of now, the following AI providers are supported: `OpenAI`, `Anthropic`, `Mistral` (OCR), and `Langchain`.
|
|
92
93
|
|
|
93
94
|
Example usage:
|
|
94
95
|
|
|
@@ -98,16 +99,16 @@ import OpenAI from "openai";
|
|
|
98
99
|
|
|
99
100
|
async function main() {
|
|
100
101
|
const client = new PaidClient({ token: "<your_paid_api_key>" });
|
|
101
|
-
const openaiClient = new OpenAI({ apiKey: "<your_openai_api_key" });
|
|
102
102
|
|
|
103
103
|
// initialize cost tracking
|
|
104
104
|
await client.initializeTracing()
|
|
105
105
|
|
|
106
106
|
// wrap openai in paid wrapper
|
|
107
|
+
const openaiClient = new OpenAI({ apiKey: "<your_openai_api_key" });
|
|
107
108
|
const paidOpenAiWrapper = new PaidOpenAI(openaiClient);
|
|
108
109
|
|
|
109
|
-
//
|
|
110
|
-
await client.
|
|
110
|
+
// trace the call
|
|
111
|
+
await client.trace("<your_external_customer_id>", async () => {
|
|
111
112
|
const response = await paidOpenAiWrapper.images.generate({
|
|
112
113
|
prompt: "A beautiful sunset over the mountains",
|
|
113
114
|
n: 1,
|
|
@@ -116,7 +117,7 @@ async function main() {
|
|
|
116
117
|
if (response.data) {
|
|
117
118
|
console.log("Image generation:", response.data[0].url);
|
|
118
119
|
}
|
|
119
|
-
});
|
|
120
|
+
}, "<optional_external_agent_id>");
|
|
120
121
|
}
|
|
121
122
|
```
|
|
122
123
|
|
package/dist/cjs/Client.d.ts
CHANGED
|
@@ -41,6 +41,8 @@ export declare class PaidClient {
|
|
|
41
41
|
get contacts(): Contacts;
|
|
42
42
|
get orders(): Orders;
|
|
43
43
|
get usage(): Usage;
|
|
44
|
-
initializeTracing(): Promise<void>;
|
|
45
|
-
|
|
44
|
+
initializeTracing(collectorEndpoint?: string): Promise<void>;
|
|
45
|
+
trace<T extends (...args: any[]) => any>(externalCustomerId: string, fn: T, externalAgentId?: string, ...args: Parameters<T>): Promise<ReturnType<T>>;
|
|
46
|
+
signal(eventName: string, data?: Record<string, any>): void;
|
|
47
|
+
getSpanProcessorAndInitialize(collectorEndpoint?: string): Promise<import("@opentelemetry/sdk-trace-base").SpanProcessor>;
|
|
46
48
|
}
|
package/dist/cjs/Client.js
CHANGED
|
@@ -54,6 +54,7 @@ const Client_js_3 = require("./api/resources/contacts/client/Client.js");
|
|
|
54
54
|
const Client_js_4 = require("./api/resources/orders/client/Client.js");
|
|
55
55
|
const BatchUsage_js_1 = require("./wrapper/BatchUsage.js");
|
|
56
56
|
const tracing_js_1 = require("./tracing/tracing.js");
|
|
57
|
+
const signal_js_1 = require("./tracing/signal.js");
|
|
57
58
|
class PaidClient {
|
|
58
59
|
constructor(_options) {
|
|
59
60
|
this._options = Object.assign(Object.assign({}, _options), { headers: (0, headers_js_1.mergeHeaders)({
|
|
@@ -85,17 +86,33 @@ class PaidClient {
|
|
|
85
86
|
var _a;
|
|
86
87
|
return ((_a = this._usage) !== null && _a !== void 0 ? _a : (this._usage = new BatchUsage_js_1.Usage(this._options)));
|
|
87
88
|
}
|
|
89
|
+
// Use this method if you want paid to initialize tracing automatically.
|
|
88
90
|
initializeTracing() {
|
|
89
|
-
return __awaiter(this,
|
|
91
|
+
return __awaiter(this, arguments, void 0, function* (collectorEndpoint = "https://collector.agentpaid.io:4318/v1/traces") {
|
|
90
92
|
const tokenSupplier = this._options.token;
|
|
91
93
|
const token = typeof tokenSupplier === "function" ? yield tokenSupplier() : tokenSupplier;
|
|
92
94
|
const resolvedToken = yield Promise.resolve(token);
|
|
93
|
-
(0, tracing_js_1.
|
|
95
|
+
(0, tracing_js_1._initializeTracing)(resolvedToken, collectorEndpoint);
|
|
94
96
|
});
|
|
95
97
|
}
|
|
96
|
-
|
|
98
|
+
// Use this method to track actions like LLM usage and sending signals.
|
|
99
|
+
// The callback to this function is the work that you want to trace.
|
|
100
|
+
trace(externalCustomerId, fn, externalAgentId, ...args) {
|
|
97
101
|
return __awaiter(this, void 0, void 0, function* () {
|
|
98
|
-
return yield (0, tracing_js_1.
|
|
102
|
+
return yield (0, tracing_js_1._trace)(externalCustomerId, fn, externalAgentId, ...args);
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
// sends Paid signal. This needs to called as part of callback to Paid.trace()
|
|
106
|
+
signal(eventName, data) {
|
|
107
|
+
return (0, signal_js_1._signal)(eventName, data);
|
|
108
|
+
}
|
|
109
|
+
// Use this method if you're setting up OTEL SDK in your code and want to add Paid's span processor.
|
|
110
|
+
getSpanProcessorAndInitialize() {
|
|
111
|
+
return __awaiter(this, arguments, void 0, function* (collectorEndpoint = "https://collector.agentpaid.io:4318/v1/traces") {
|
|
112
|
+
const tokenSupplier = this._options.token;
|
|
113
|
+
const token = typeof tokenSupplier === "function" ? yield tokenSupplier() : tokenSupplier;
|
|
114
|
+
const resolvedToken = yield Promise.resolve(token);
|
|
115
|
+
return (0, tracing_js_1._getSpanProcessorAndInitialize)(resolvedToken, collectorEndpoint);
|
|
99
116
|
});
|
|
100
117
|
}
|
|
101
118
|
}
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -3,4 +3,6 @@ export { PaidClient } from "./Client.js";
|
|
|
3
3
|
export { PaidError, PaidTimeoutError } from "./errors/index.js";
|
|
4
4
|
export { PaidEnvironment } from "./environments.js";
|
|
5
5
|
export { PaidOpenAI } from "./tracing/wrappers/openAiWrapper.js";
|
|
6
|
-
export {
|
|
6
|
+
export { PaidAnthropic } from "./tracing/wrappers/anthropicWrapper.js";
|
|
7
|
+
export { PaidMistral } from "./tracing/wrappers/mistralWrapper.js";
|
|
8
|
+
export { PaidLangChainCallback } from "./tracing/wrappers/langchainCallback.js";
|
package/dist/cjs/index.js
CHANGED
|
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.
|
|
36
|
+
exports.PaidLangChainCallback = exports.PaidMistral = exports.PaidAnthropic = exports.PaidOpenAI = 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; } });
|
|
@@ -44,6 +44,9 @@ var environments_js_1 = require("./environments.js");
|
|
|
44
44
|
Object.defineProperty(exports, "PaidEnvironment", { enumerable: true, get: function () { return environments_js_1.PaidEnvironment; } });
|
|
45
45
|
var openAiWrapper_js_1 = require("./tracing/wrappers/openAiWrapper.js");
|
|
46
46
|
Object.defineProperty(exports, "PaidOpenAI", { enumerable: true, get: function () { return openAiWrapper_js_1.PaidOpenAI; } });
|
|
47
|
-
var
|
|
48
|
-
Object.defineProperty(exports, "
|
|
49
|
-
|
|
47
|
+
var anthropicWrapper_js_1 = require("./tracing/wrappers/anthropicWrapper.js");
|
|
48
|
+
Object.defineProperty(exports, "PaidAnthropic", { enumerable: true, get: function () { return anthropicWrapper_js_1.PaidAnthropic; } });
|
|
49
|
+
var mistralWrapper_js_1 = require("./tracing/wrappers/mistralWrapper.js");
|
|
50
|
+
Object.defineProperty(exports, "PaidMistral", { enumerable: true, get: function () { return mistralWrapper_js_1.PaidMistral; } });
|
|
51
|
+
var langchainCallback_js_1 = require("./tracing/wrappers/langchainCallback.js");
|
|
52
|
+
Object.defineProperty(exports, "PaidLangChainCallback", { enumerable: true, get: function () { return langchainCallback_js_1.PaidLangChainCallback; } });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function _signal(eventName: string, data?: Record<string, any>): void;
|
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
function _signal(eventName, data) {
|
|
7
|
+
if (!eventName) {
|
|
8
|
+
throw new Error("Event name is required for signal.");
|
|
9
|
+
}
|
|
10
|
+
// Check if there's an active span (from _trace())
|
|
11
|
+
const currentSpan = api_1.trace.getActiveSpan();
|
|
12
|
+
if (!currentSpan) {
|
|
13
|
+
throw new Error("Cannot send signal: you should call signal() within trace()");
|
|
14
|
+
}
|
|
15
|
+
const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
|
|
16
|
+
const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
|
|
17
|
+
const token = (0, tracing_js_1.getTokenStorage)();
|
|
18
|
+
if (!externalCustomerId || !externalAgentId || !token) {
|
|
19
|
+
throw new Error(`Missing some of: external_customer_id: ${externalCustomerId}, external_agent_id: ${externalAgentId}, or token. Make sure to call signal() within trace()`);
|
|
20
|
+
}
|
|
21
|
+
const tracer = api_1.trace.getTracer("paid.node");
|
|
22
|
+
tracer.startActiveSpan("trace.signal", (span) => {
|
|
23
|
+
try {
|
|
24
|
+
const attributes = {
|
|
25
|
+
external_customer_id: externalCustomerId,
|
|
26
|
+
external_agent_id: externalAgentId,
|
|
27
|
+
event_name: eventName,
|
|
28
|
+
token: token,
|
|
29
|
+
};
|
|
30
|
+
// Optional data (ex. manual cost tracking)
|
|
31
|
+
if (data) {
|
|
32
|
+
attributes["data"] = JSON.stringify(data);
|
|
33
|
+
}
|
|
34
|
+
span.setAttributes(attributes);
|
|
35
|
+
// Mark span as successful
|
|
36
|
+
span.setStatus({ code: api_1.SpanStatusCode.OK });
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
span.setStatus({
|
|
40
|
+
code: api_1.SpanStatusCode.ERROR,
|
|
41
|
+
message: error.message,
|
|
42
|
+
});
|
|
43
|
+
span.recordException(error);
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
span.end();
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
}
|
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
import { SpanProcessor } from "@opentelemetry/sdk-trace-base";
|
|
2
|
+
import winston from "winston";
|
|
3
|
+
export declare const logger: winston.Logger;
|
|
4
|
+
export declare const getCustomerIdStorage: () => string | null | undefined;
|
|
5
|
+
export declare const getAgentIdStorage: () => string | null | undefined;
|
|
2
6
|
export declare const getTokenStorage: () => string | null | undefined;
|
|
3
|
-
export declare function
|
|
4
|
-
export declare function
|
|
7
|
+
export declare function _initializeTracing(apiKey: string, collectorEndpoint: string): void;
|
|
8
|
+
export declare function _getSpanProcessorAndInitialize(apiKey: string, collectorEndpoint: string): SpanProcessor;
|
|
9
|
+
export declare function _trace<T extends (...args: any[]) => any>(externalCustomerId: string, fn: T, externalAgentId: string | undefined, ...args: Parameters<T>): Promise<ReturnType<T>>;
|
|
@@ -8,56 +8,128 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
8
8
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
+
};
|
|
11
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.getTokenStorage = exports.
|
|
13
|
-
exports.
|
|
14
|
-
exports.
|
|
15
|
+
exports.getTokenStorage = exports.getAgentIdStorage = exports.getCustomerIdStorage = exports.logger = void 0;
|
|
16
|
+
exports._initializeTracing = _initializeTracing;
|
|
17
|
+
exports._getSpanProcessorAndInitialize = _getSpanProcessorAndInitialize;
|
|
18
|
+
exports._trace = _trace;
|
|
15
19
|
const sdk_node_1 = require("@opentelemetry/sdk-node");
|
|
16
20
|
const exporter_trace_otlp_http_1 = require("@opentelemetry/exporter-trace-otlp-http");
|
|
21
|
+
const sdk_trace_base_1 = require("@opentelemetry/sdk-trace-base");
|
|
17
22
|
const api_1 = require("@opentelemetry/api");
|
|
18
23
|
const async_hooks_1 = require("async_hooks");
|
|
24
|
+
const winston_1 = __importDefault(require("winston"));
|
|
25
|
+
exports.logger = winston_1.default.createLogger({
|
|
26
|
+
level: "silent", // Default to 'silent' to avoid logging unless set via environment variable
|
|
27
|
+
format: winston_1.default.format.simple(),
|
|
28
|
+
transports: [new winston_1.default.transports.Console()],
|
|
29
|
+
});
|
|
30
|
+
const logLevel = process.env.PAID_LOG_LEVEL;
|
|
31
|
+
if (logLevel) {
|
|
32
|
+
exports.logger.level = logLevel;
|
|
33
|
+
}
|
|
34
|
+
// storage for passing info to child spans
|
|
19
35
|
const customerIdStorage = new async_hooks_1.AsyncLocalStorage();
|
|
36
|
+
const agentIdStorage = new async_hooks_1.AsyncLocalStorage();
|
|
20
37
|
const tokenStorage = new async_hooks_1.AsyncLocalStorage();
|
|
21
|
-
const
|
|
22
|
-
exports.
|
|
38
|
+
const getCustomerIdStorage = () => customerIdStorage.getStore();
|
|
39
|
+
exports.getCustomerIdStorage = getCustomerIdStorage;
|
|
40
|
+
const getAgentIdStorage = () => agentIdStorage.getStore();
|
|
41
|
+
exports.getAgentIdStorage = getAgentIdStorage;
|
|
23
42
|
const getTokenStorage = () => tokenStorage.getStore();
|
|
24
43
|
exports.getTokenStorage = getTokenStorage;
|
|
25
44
|
let _token;
|
|
26
|
-
const setToken = (token) => {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
45
|
+
const setToken = (token) => {
|
|
46
|
+
_token = token;
|
|
47
|
+
};
|
|
48
|
+
const getToken = () => {
|
|
49
|
+
return _token;
|
|
50
|
+
};
|
|
51
|
+
let _isShuttingDown = false;
|
|
52
|
+
function setupGracefulShutdown(shuttable) {
|
|
53
|
+
["SIGINT", "SIGTERM", "beforeExit", "uncaughtException", "unhandledRejection"].forEach((signal) => {
|
|
54
|
+
process.on(signal, () => {
|
|
55
|
+
if (_isShuttingDown) {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
_isShuttingDown = true;
|
|
59
|
+
shuttable
|
|
60
|
+
.shutdown()
|
|
61
|
+
.then(() => exports.logger.info(`Paid tracing SDK shut down from signal: ${signal}`))
|
|
62
|
+
.catch((error) => exports.logger.error(`Error shutting down Paid tracing SDK ${error}`));
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function isOTELInitialized() {
|
|
67
|
+
const provider = api_1.trace.getTracerProvider();
|
|
68
|
+
if (!provider) {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
if (provider.constructor.name !== "ProxyTracerProvider" && provider.constructor.name !== "NodeTracerProvider") {
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
if (provider._delegate) {
|
|
75
|
+
return provider._delegate.constructor.name !== "NoopTracerProvider";
|
|
76
|
+
}
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
function _initializeTracing(apiKey, collectorEndpoint) {
|
|
80
|
+
if (getToken()) {
|
|
81
|
+
throw new Error("Tracing SDK is already initialized.");
|
|
82
|
+
}
|
|
83
|
+
if (!apiKey) {
|
|
84
|
+
throw new Error("Cannot initialize tracing SDK - first initialize the PaidClient with an API key");
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
new URL(collectorEndpoint);
|
|
88
|
+
}
|
|
89
|
+
catch (_a) {
|
|
90
|
+
throw new Error(`Collector endpoint [${collectorEndpoint}] must be a valid URL`);
|
|
91
|
+
}
|
|
92
|
+
if (isOTELInitialized()) {
|
|
93
|
+
throw new Error("OTEL SDK is already initialized with a different provider.\n" +
|
|
94
|
+
"If you're already using OTEL in your code - " +
|
|
95
|
+
"please use function Paid.getSpanProcessorAndInitialize() " +
|
|
96
|
+
"and add the span processor to your OTEL SDK initialization");
|
|
97
|
+
}
|
|
30
98
|
const sdk = new sdk_node_1.NodeSDK({
|
|
31
99
|
traceExporter: new exporter_trace_otlp_http_1.OTLPTraceExporter({
|
|
32
|
-
url:
|
|
33
|
-
// url: 'http://localhost:4318/v1/traces',
|
|
100
|
+
url: collectorEndpoint,
|
|
34
101
|
}),
|
|
35
102
|
});
|
|
36
103
|
sdk.start();
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
104
|
+
setupGracefulShutdown(sdk);
|
|
105
|
+
setToken(apiKey);
|
|
106
|
+
exports.logger.info(`Paid tracing SDK initialized with collector endpoint: ${collectorEndpoint}`);
|
|
107
|
+
}
|
|
108
|
+
function _getSpanProcessorAndInitialize(apiKey, collectorEndpoint) {
|
|
109
|
+
setToken(apiKey);
|
|
110
|
+
const spanProcessor = new sdk_trace_base_1.BatchSpanProcessor(new exporter_trace_otlp_http_1.OTLPTraceExporter({ url: collectorEndpoint }));
|
|
111
|
+
setupGracefulShutdown(spanProcessor);
|
|
112
|
+
return spanProcessor;
|
|
45
113
|
}
|
|
46
|
-
function
|
|
114
|
+
function _trace(externalCustomerId, fn, externalAgentId, ...args) {
|
|
47
115
|
return __awaiter(this, void 0, void 0, function* () {
|
|
48
|
-
const tracer = api_1.trace.getTracer(
|
|
116
|
+
const tracer = api_1.trace.getTracer("paid.node");
|
|
49
117
|
const token = getToken();
|
|
50
|
-
if (!token) {
|
|
51
|
-
|
|
52
|
-
return fn(...args);
|
|
118
|
+
if (!token || !externalCustomerId) {
|
|
119
|
+
throw new Error(`Token [${token}] or external customer ID [${externalCustomerId}] is missing`);
|
|
53
120
|
}
|
|
54
121
|
return tracer.startActiveSpan("paid.node", (span) => __awaiter(this, void 0, void 0, function* () {
|
|
55
|
-
span.setAttribute(
|
|
56
|
-
span.setAttribute(
|
|
122
|
+
span.setAttribute("external_customer_id", externalCustomerId);
|
|
123
|
+
span.setAttribute("token", token);
|
|
124
|
+
if (externalAgentId) {
|
|
125
|
+
span.setAttribute("external_agent_id", externalAgentId);
|
|
126
|
+
}
|
|
57
127
|
try {
|
|
58
128
|
const result = yield customerIdStorage.run(externalCustomerId, () => __awaiter(this, void 0, void 0, function* () {
|
|
59
|
-
return yield
|
|
60
|
-
return yield
|
|
129
|
+
return yield agentIdStorage.run(externalAgentId !== null && externalAgentId !== void 0 ? externalAgentId : null, () => __awaiter(this, void 0, void 0, function* () {
|
|
130
|
+
return yield tokenStorage.run(token, () => __awaiter(this, void 0, void 0, function* () {
|
|
131
|
+
return yield fn(...args);
|
|
132
|
+
}));
|
|
61
133
|
}));
|
|
62
134
|
}));
|
|
63
135
|
span.setStatus({ code: api_1.SpanStatusCode.OK });
|
|
@@ -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,88 @@
|
|
|
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 = api_1.trace.getTracer("paid.node");
|
|
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 currentSpan = api_1.trace.getSpan(api_1.context.active());
|
|
33
|
+
if (!currentSpan) {
|
|
34
|
+
throw new Error("No active span found, make sure to call this inside of a callback to paid.trace().");
|
|
35
|
+
}
|
|
36
|
+
const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
|
|
37
|
+
const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
|
|
38
|
+
const token = (0, tracing_js_1.getTokenStorage)();
|
|
39
|
+
if (!token || !externalCustomerId) {
|
|
40
|
+
throw new Error("No token or externalCustomerId: This wrapper should be used inside a callback to paid.trace().");
|
|
41
|
+
}
|
|
42
|
+
return this.tracer.startActiveSpan("trace.anthropic.messages", (span) => __awaiter(this, void 0, void 0, function* () {
|
|
43
|
+
const attributes = {
|
|
44
|
+
"gen_ai.system": "anthropic",
|
|
45
|
+
"gen_ai.operation.name": "messages",
|
|
46
|
+
external_customer_id: externalCustomerId,
|
|
47
|
+
token: token,
|
|
48
|
+
};
|
|
49
|
+
if (externalAgentId) {
|
|
50
|
+
attributes["external_agent_id"] = externalAgentId;
|
|
51
|
+
}
|
|
52
|
+
// Set request model from params
|
|
53
|
+
if (params.model) {
|
|
54
|
+
attributes["gen_ai.request.model"] = params.model;
|
|
55
|
+
}
|
|
56
|
+
span.setAttributes(attributes);
|
|
57
|
+
try {
|
|
58
|
+
const response = (yield this.anthropic.messages.create(params));
|
|
59
|
+
// Add usage information from response
|
|
60
|
+
if (response.usage) {
|
|
61
|
+
span.setAttributes({
|
|
62
|
+
"gen_ai.usage.input_tokens": response.usage.input_tokens,
|
|
63
|
+
"gen_ai.usage.output_tokens": response.usage.output_tokens,
|
|
64
|
+
"gen_ai.response.model": response.model,
|
|
65
|
+
});
|
|
66
|
+
// Add Anthropic-specific cache usage if available
|
|
67
|
+
if ("cache_creation_input_tokens" in response.usage && response.usage.cache_creation_input_tokens) {
|
|
68
|
+
span.setAttribute("gen_ai.usage.cache_creation_input_tokens", response.usage.cache_creation_input_tokens);
|
|
69
|
+
}
|
|
70
|
+
if ("cache_read_input_tokens" in response.usage && response.usage.cache_read_input_tokens) {
|
|
71
|
+
span.setAttribute("gen_ai.usage.cache_read_input_tokens", response.usage.cache_read_input_tokens);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
span.setStatus({ code: api_1.SpanStatusCode.OK });
|
|
75
|
+
return response;
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
|
|
79
|
+
span.recordException(error);
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
span.end();
|
|
84
|
+
}
|
|
85
|
+
}));
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -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 {};
|