@paid-ai/paid-node 0.0.6 → 0.0.8-alpha0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Agent Paid Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,28 +1,45 @@
1
- # Paid TypeScript Library
2
1
 
3
- [![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen)](https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=https%3A%2F%2Fgithub.com%2FAgentPaid%2Fpaid-node)
4
- [![npm shield](https://img.shields.io/npm/v/@paid-ai/paid-node)](https://www.npmjs.com/package/@paid-ai/paid-node)
2
+ <div align="center">
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="./assets/paid_light.svg" width=600>
5
+ <source media="(prefers-color-scheme: light)" srcset="./assets/paid_dark.svg" width=600>
6
+ <img alt="Fallback image description" src="./assets/paid_light.svg" width=600>
7
+ </picture>
8
+ </div>
5
9
 
6
- The Paid TypeScript library provides convenient access to the Paid API from TypeScript.
10
+ #
11
+
12
+ <div align="center">
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">
14
+ <img src="https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen" alt="fern shield">
15
+ </a>
16
+ <a href="https://www.npmjs.com/package/@paid-ai/paid-node">
17
+ <img src="https://img.shields.io/npm/v/@paid-ai/paid-node" alt="npm shield">
18
+ </a>
19
+ </div>
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.
23
+
24
+ ## Documentation
25
+
26
+ See the full API docs [here](https://paid.docs.buildwithfern.com/api-reference/api-reference/customers/list)
7
27
 
8
28
  ## Installation
9
29
 
10
30
  ```sh
11
- npm i -s @paid-ai/paid-node
31
+ npm install -s @paid-ai/paid-node
12
32
  ```
13
33
 
14
- ## Reference
15
-
16
- A full reference for this library is available [here](https://github.com/AgentPaid/paid-node/blob/HEAD/./reference.md).
17
-
18
34
  ## Usage
19
35
 
20
- Instantiate and use the client with the following:
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).
21
37
 
22
38
  ```typescript
23
39
  import { PaidClient } from "@paid-ai/paid-node";
24
40
 
25
- const client = new PaidClient({ token: "YOUR_TOKEN" });
41
+ const client = new PaidClient({ token: "API_KEY" });
42
+
26
43
  await client.customers.create({
27
44
  name: "name",
28
45
  });
@@ -61,6 +78,73 @@ try {
61
78
  }
62
79
  ```
63
80
 
81
+ ## Cost Tracking
82
+
83
+ It's possible to track usage costs by using Paid wrappers around you AI provider API.
84
+ As of now, the following OpenAI APIs are supported:
85
+
86
+ ```
87
+ chat.completions.create()
88
+ responses.create()
89
+ images.generate()
90
+ embeddings.create()
91
+ ```
92
+
93
+ Example usage:
94
+
95
+ ```typescript
96
+ import { PaidClient, PaidOpenAI } from "@paid-ai/paid-node";
97
+ import OpenAI from "openai";
98
+
99
+ async function main() {
100
+ const client = new PaidClient({ token: "<your_paid_api_key>" });
101
+ const openaiClient = new OpenAI({ apiKey: "<your_openai_api_key" });
102
+
103
+ // initialize cost tracking
104
+ await client.initializeTracing()
105
+
106
+ // wrap openai in paid wrapper
107
+ const paidOpenAiWrapper = new PaidOpenAI(openaiClient);
108
+
109
+ // capture the call
110
+ await client.capture("<your_external_customer_id>", async () => {
111
+ const response = await paidOpenAiWrapper.images.generate({
112
+ prompt: "A beautiful sunset over the mountains",
113
+ n: 1,
114
+ size: "256x256"
115
+ });
116
+ if (response.data) {
117
+ console.log("Image generation:", response.data[0].url);
118
+ }
119
+ });
120
+ }
121
+ ```
122
+
123
+ ## Manual Cost Tracking
124
+
125
+ When using `client.usage.recordUsage()` API, it's possible to create cost traces manually
126
+ just by passing in the cost data.
127
+
128
+ ```typescript
129
+ const additionalData = {
130
+ costData: {
131
+ vendor: "<vendor_name>", // can be anything
132
+ cost : {
133
+ amount: 0.0001,
134
+ currency: "USD"
135
+ }
136
+ }
137
+ };
138
+ await client.usage.recordUsage({
139
+ agent_id: "<your_agent_id>",
140
+ event_name: "<your_signal_name>",
141
+ customer_id: "<your_customer_id>",
142
+ data: additionalData,
143
+ })
144
+
145
+ await client.usage.flush(); // need to flush to send usage immediately
146
+ ```
147
+
64
148
  ## Advanced
65
149
 
66
150
  ### Additional Headers
@@ -7,7 +7,7 @@ import { Customers } from "./api/resources/customers/client/Client.js";
7
7
  import { Agents } from "./api/resources/agents/client/Client.js";
8
8
  import { Contacts } from "./api/resources/contacts/client/Client.js";
9
9
  import { Orders } from "./api/resources/orders/client/Client.js";
10
- import { Usage } from "./api/resources/usage/client/Client.js";
10
+ import { Usage } from "./wrapper/BatchUsage.js";
11
11
  export declare namespace PaidClient {
12
12
  interface Options {
13
13
  environment?: core.Supplier<environments.PaidEnvironment | string>;
@@ -41,4 +41,6 @@ export declare class PaidClient {
41
41
  get contacts(): Contacts;
42
42
  get orders(): Orders;
43
43
  get usage(): Usage;
44
+ initializeTracing(): Promise<void>;
45
+ capture<T extends (...args: any[]) => any>(externalCustomerId: string, fn: T, ...args: Parameters<T>): Promise<ReturnType<T>>;
44
46
  }
@@ -35,6 +35,15 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  return result;
36
36
  };
37
37
  })();
38
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
39
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
40
+ return new (P || (P = Promise))(function (resolve, reject) {
41
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
42
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
43
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
44
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
45
+ });
46
+ };
38
47
  Object.defineProperty(exports, "__esModule", { value: true });
39
48
  exports.PaidClient = void 0;
40
49
  const core = __importStar(require("./core/index.js"));
@@ -43,7 +52,8 @@ const Client_js_1 = require("./api/resources/customers/client/Client.js");
43
52
  const Client_js_2 = require("./api/resources/agents/client/Client.js");
44
53
  const Client_js_3 = require("./api/resources/contacts/client/Client.js");
45
54
  const Client_js_4 = require("./api/resources/orders/client/Client.js");
46
- const Client_js_5 = require("./api/resources/usage/client/Client.js");
55
+ const BatchUsage_js_1 = require("./wrapper/BatchUsage.js");
56
+ const tracing_js_1 = require("./tracing/tracing.js");
47
57
  class PaidClient {
48
58
  constructor(_options) {
49
59
  this._options = Object.assign(Object.assign({}, _options), { headers: (0, headers_js_1.mergeHeaders)({
@@ -73,7 +83,20 @@ class PaidClient {
73
83
  }
74
84
  get usage() {
75
85
  var _a;
76
- return ((_a = this._usage) !== null && _a !== void 0 ? _a : (this._usage = new Client_js_5.Usage(this._options)));
86
+ return ((_a = this._usage) !== null && _a !== void 0 ? _a : (this._usage = new BatchUsage_js_1.Usage(this._options)));
87
+ }
88
+ initializeTracing() {
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ const tokenSupplier = this._options.token;
91
+ const token = typeof tokenSupplier === "function" ? yield tokenSupplier() : tokenSupplier;
92
+ const resolvedToken = yield Promise.resolve(token);
93
+ (0, tracing_js_1.initializeTracing)(resolvedToken);
94
+ });
95
+ }
96
+ capture(externalCustomerId, fn, ...args) {
97
+ return __awaiter(this, void 0, void 0, function* () {
98
+ return yield (0, tracing_js_1.capture)(externalCustomerId, fn, ...args);
99
+ });
77
100
  }
78
101
  }
79
102
  exports.PaidClient = PaidClient;
@@ -1,4 +1,6 @@
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";
5
+ export { PaidOpenAI } from "./tracing/wrappers/openAiWrapper.js";
6
+ export { initializeTracing, capture } from "./tracing/tracing.js";
package/dist/cjs/index.js CHANGED
@@ -33,12 +33,17 @@ 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.capture = exports.initializeTracing = 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; } });
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; } });
45
+ var openAiWrapper_js_1 = require("./tracing/wrappers/openAiWrapper.js");
46
+ Object.defineProperty(exports, "PaidOpenAI", { enumerable: true, get: function () { return openAiWrapper_js_1.PaidOpenAI; } });
47
+ var tracing_js_1 = require("./tracing/tracing.js");
48
+ Object.defineProperty(exports, "initializeTracing", { enumerable: true, get: function () { return tracing_js_1.initializeTracing; } });
49
+ Object.defineProperty(exports, "capture", { enumerable: true, get: function () { return tracing_js_1.capture; } });
@@ -0,0 +1 @@
1
+ export * from "./wrappers/openAiWrapper";
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./wrappers/openAiWrapper"), exports);
@@ -0,0 +1,4 @@
1
+ export declare const getCustomerId: () => string | null | undefined;
2
+ export declare const getTokenStorage: () => string | null | undefined;
3
+ export declare function initializeTracing(apiKey: string): void;
4
+ export declare function capture<T extends (...args: any[]) => any>(externalCustomerId: string, fn: T, ...args: Parameters<T>): Promise<ReturnType<T>>;
@@ -0,0 +1,79 @@
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.getTokenStorage = exports.getCustomerId = void 0;
13
+ exports.initializeTracing = initializeTracing;
14
+ exports.capture = capture;
15
+ const sdk_node_1 = require("@opentelemetry/sdk-node");
16
+ const exporter_trace_otlp_http_1 = require("@opentelemetry/exporter-trace-otlp-http");
17
+ const api_1 = require("@opentelemetry/api");
18
+ const async_hooks_1 = require("async_hooks");
19
+ const customerIdStorage = new async_hooks_1.AsyncLocalStorage();
20
+ const tokenStorage = new async_hooks_1.AsyncLocalStorage();
21
+ const getCustomerId = () => customerIdStorage.getStore();
22
+ exports.getCustomerId = getCustomerId;
23
+ const getTokenStorage = () => tokenStorage.getStore();
24
+ exports.getTokenStorage = getTokenStorage;
25
+ let _token;
26
+ const setToken = (token) => { _token = token; };
27
+ const getToken = () => { return _token; };
28
+ function initializeTracing(apiKey) {
29
+ setToken(apiKey);
30
+ const sdk = new sdk_node_1.NodeSDK({
31
+ traceExporter: new exporter_trace_otlp_http_1.OTLPTraceExporter({
32
+ url: 'https://collector.agentpaid.io:4318/v1/traces',
33
+ // url: 'http://localhost:4318/v1/traces',
34
+ }),
35
+ });
36
+ sdk.start();
37
+ // Graceful shutdown
38
+ ['SIGINT', 'SIGTERM'].forEach(signal => {
39
+ process.on(signal, () => {
40
+ sdk.shutdown()
41
+ .then(() => console.log('Paid tracing SDK shut down'))
42
+ .catch(error => console.error('Error shutting down Paid tracing SDK', error));
43
+ });
44
+ });
45
+ }
46
+ function capture(externalCustomerId, fn, ...args) {
47
+ return __awaiter(this, void 0, void 0, function* () {
48
+ const tracer = api_1.trace.getTracer('paid.node');
49
+ const token = getToken();
50
+ if (!token) {
51
+ console.warn('No token found - tracing will not be captured');
52
+ return fn(...args);
53
+ }
54
+ return tracer.startActiveSpan("paid.node", (span) => __awaiter(this, void 0, void 0, function* () {
55
+ span.setAttribute('external_customer_id', externalCustomerId);
56
+ span.setAttribute('token', token);
57
+ try {
58
+ const result = yield customerIdStorage.run(externalCustomerId, () => __awaiter(this, void 0, void 0, function* () {
59
+ return yield tokenStorage.run(token, () => __awaiter(this, void 0, void 0, function* () {
60
+ return yield fn(...args);
61
+ }));
62
+ }));
63
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
64
+ return result;
65
+ }
66
+ catch (error) {
67
+ span.setStatus({
68
+ code: api_1.SpanStatusCode.ERROR,
69
+ message: error.message,
70
+ });
71
+ span.recordException(error);
72
+ throw error;
73
+ }
74
+ finally {
75
+ span.end();
76
+ }
77
+ }));
78
+ });
79
+ }
@@ -0,0 +1,48 @@
1
+ import OpenAI from "openai";
2
+ import { Tracer } from "@opentelemetry/api";
3
+ import { ChatCompletion, ChatCompletionCreateParams } from "openai/resources/chat/completions";
4
+ import { EmbeddingCreateParams } from "openai/resources/embeddings";
5
+ import { ImagesResponse, ImageGenerateParams } from "openai/resources/images";
6
+ import { CreateEmbeddingResponse } from "openai/resources/embeddings";
7
+ export declare class PaidOpenAI {
8
+ private readonly openai;
9
+ private readonly tracer;
10
+ constructor(openaiClient: any);
11
+ get chat(): ChatWrapper;
12
+ get embeddings(): EmbeddingsWrapper;
13
+ get images(): ImagesWrapper;
14
+ get responses(): ResponsesWrapper;
15
+ }
16
+ declare class ChatWrapper {
17
+ private openai;
18
+ private tracer;
19
+ constructor(openai: OpenAI, tracer: Tracer);
20
+ get completions(): ChatCompletionsWrapper;
21
+ }
22
+ declare class ChatCompletionsWrapper {
23
+ private openai;
24
+ private tracer;
25
+ constructor(openai: OpenAI, tracer: Tracer);
26
+ create(params: ChatCompletionCreateParams): Promise<ChatCompletion>;
27
+ }
28
+ type ResponseCreateParams = any;
29
+ type Response = any;
30
+ declare class ResponsesWrapper {
31
+ private openai;
32
+ private tracer;
33
+ constructor(openai: any, tracer: Tracer);
34
+ create(params: ResponseCreateParams): Promise<Response>;
35
+ }
36
+ declare class EmbeddingsWrapper {
37
+ private openai;
38
+ private tracer;
39
+ constructor(openai: OpenAI, tracer: Tracer);
40
+ create(params: EmbeddingCreateParams): Promise<CreateEmbeddingResponse>;
41
+ }
42
+ declare class ImagesWrapper {
43
+ private openai;
44
+ private tracer;
45
+ constructor(openai: OpenAI, tracer: Tracer);
46
+ generate(params: ImageGenerateParams): Promise<ImagesResponse>;
47
+ }
48
+ export {};
@@ -0,0 +1,252 @@
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.PaidOpenAI = void 0;
13
+ const api_1 = require("@opentelemetry/api");
14
+ const tracing_1 = require("../tracing");
15
+ class PaidOpenAI {
16
+ constructor(openaiClient) {
17
+ this.openai = openaiClient;
18
+ this.tracer = api_1.trace.getTracer("paid.node");
19
+ }
20
+ get chat() {
21
+ return new ChatWrapper(this.openai, this.tracer);
22
+ }
23
+ get embeddings() {
24
+ return new EmbeddingsWrapper(this.openai, this.tracer);
25
+ }
26
+ get images() {
27
+ return new ImagesWrapper(this.openai, this.tracer);
28
+ }
29
+ get responses() {
30
+ return new ResponsesWrapper(this.openai, this.tracer);
31
+ }
32
+ }
33
+ exports.PaidOpenAI = PaidOpenAI;
34
+ class ChatWrapper {
35
+ constructor(openai, tracer) {
36
+ this.openai = openai;
37
+ this.tracer = tracer;
38
+ }
39
+ get completions() {
40
+ return new ChatCompletionsWrapper(this.openai, this.tracer);
41
+ }
42
+ }
43
+ class ChatCompletionsWrapper {
44
+ constructor(openai, tracer) {
45
+ this.openai = openai;
46
+ this.tracer = tracer;
47
+ }
48
+ create(params) {
49
+ return __awaiter(this, void 0, void 0, function* () {
50
+ const currentSpan = api_1.trace.getSpan(api_1.context.active());
51
+ if (!currentSpan) {
52
+ console.warn("No active span found, calling OpenAI directly without tracing.");
53
+ return this.openai.chat.completions.create(params);
54
+ }
55
+ const externalCustomerId = (0, tracing_1.getCustomerId)();
56
+ const token = (0, tracing_1.getTokenStorage)();
57
+ const model = params.model;
58
+ const spanName = `trace.chat ${model}`;
59
+ return this.tracer.startActiveSpan(spanName, (span) => __awaiter(this, void 0, void 0, function* () {
60
+ const attributes = {
61
+ "gen_ai.system": "openai",
62
+ "gen_ai.operation.name": "chat",
63
+ };
64
+ if (externalCustomerId) {
65
+ attributes["external_customer_id"] = externalCustomerId;
66
+ }
67
+ if (token) {
68
+ attributes["token"] = token;
69
+ }
70
+ span.setAttributes(attributes);
71
+ try {
72
+ const response = (yield this.openai.chat.completions.create(params));
73
+ if (response.usage) {
74
+ span.setAttributes({
75
+ "gen_ai.usage.input_tokens": response.usage.prompt_tokens,
76
+ "gen_ai.usage.output_tokens": response.usage.completion_tokens,
77
+ "gen_ai.response.model": response.model,
78
+ });
79
+ }
80
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
81
+ return response;
82
+ }
83
+ catch (error) {
84
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
85
+ span.recordException(error);
86
+ throw error;
87
+ }
88
+ finally {
89
+ span.end();
90
+ }
91
+ }));
92
+ });
93
+ }
94
+ }
95
+ class ResponsesWrapper {
96
+ constructor(openai, tracer) {
97
+ this.openai = openai;
98
+ this.tracer = tracer;
99
+ }
100
+ create(params) {
101
+ return __awaiter(this, void 0, void 0, function* () {
102
+ var _a;
103
+ const currentSpan = api_1.trace.getSpan(api_1.context.active());
104
+ if (!currentSpan) {
105
+ console.warn("No active span found, calling OpenAI directly without tracing.");
106
+ return this.openai.responses.create(params);
107
+ }
108
+ const externalCustomerId = (0, tracing_1.getCustomerId)();
109
+ const token = (0, tracing_1.getTokenStorage)();
110
+ const model = (_a = params.model) !== null && _a !== void 0 ? _a : "unknown";
111
+ const spanName = `trace.responses ${model}`;
112
+ return this.tracer.startActiveSpan(spanName, (span) => __awaiter(this, void 0, void 0, function* () {
113
+ const attributes = {
114
+ "gen_ai.system": "openai",
115
+ "gen_ai.operation.name": "chat", // Equivalent to chat.completions
116
+ };
117
+ if (externalCustomerId) {
118
+ attributes["external_customer_id"] = externalCustomerId;
119
+ }
120
+ if (token) {
121
+ attributes["token"] = token;
122
+ }
123
+ span.setAttributes(attributes);
124
+ try {
125
+ const response = yield this.openai.responses.create(params);
126
+ if (response.usage) {
127
+ span.setAttributes({
128
+ "gen_ai.usage.input_tokens": response.usage.prompt_tokens,
129
+ "gen_ai.usage.output_tokens": response.usage.completion_tokens,
130
+ "gen_ai.response.model": response.model,
131
+ });
132
+ }
133
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
134
+ return response;
135
+ }
136
+ catch (error) {
137
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
138
+ span.recordException(error);
139
+ throw error;
140
+ }
141
+ finally {
142
+ span.end();
143
+ }
144
+ }));
145
+ });
146
+ }
147
+ }
148
+ class EmbeddingsWrapper {
149
+ constructor(openai, tracer) {
150
+ this.openai = openai;
151
+ this.tracer = tracer;
152
+ }
153
+ create(params) {
154
+ return __awaiter(this, void 0, void 0, function* () {
155
+ var _a;
156
+ const currentSpan = api_1.trace.getSpan(api_1.context.active());
157
+ if (!currentSpan) {
158
+ console.warn("No active span found, calling OpenAI directly without tracing.");
159
+ return this.openai.embeddings.create(params);
160
+ }
161
+ const externalCustomerId = (0, tracing_1.getCustomerId)();
162
+ const token = (0, tracing_1.getTokenStorage)();
163
+ const model = (_a = params.model) !== null && _a !== void 0 ? _a : "unknown";
164
+ const spanName = `trace.embeddings ${model}`;
165
+ return this.tracer.startActiveSpan(spanName, (span) => __awaiter(this, void 0, void 0, function* () {
166
+ const attributes = {
167
+ "gen_ai.system": "openai",
168
+ "gen_ai.operation.name": "embeddings",
169
+ };
170
+ if (externalCustomerId) {
171
+ attributes["external_customer_id"] = externalCustomerId;
172
+ }
173
+ if (token) {
174
+ attributes["token"] = token;
175
+ }
176
+ span.setAttributes(attributes);
177
+ try {
178
+ const response = yield this.openai.embeddings.create(params);
179
+ if (response.usage) {
180
+ span.setAttributes({
181
+ "gen_ai.usage.input_tokens": response.usage.prompt_tokens,
182
+ "gen_ai.response.model": response.model,
183
+ });
184
+ }
185
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
186
+ return response;
187
+ }
188
+ catch (error) {
189
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
190
+ span.recordException(error);
191
+ throw error;
192
+ }
193
+ finally {
194
+ span.end();
195
+ }
196
+ }));
197
+ });
198
+ }
199
+ }
200
+ class ImagesWrapper {
201
+ constructor(openai, tracer) {
202
+ this.openai = openai;
203
+ this.tracer = tracer;
204
+ }
205
+ generate(params) {
206
+ return __awaiter(this, void 0, void 0, function* () {
207
+ var _a;
208
+ const currentSpan = api_1.trace.getSpan(api_1.context.active());
209
+ if (!currentSpan) {
210
+ console.warn("No active span found, calling OpenAI directly without tracing.");
211
+ return this.openai.images.generate(params);
212
+ }
213
+ const externalCustomerId = (0, tracing_1.getCustomerId)();
214
+ const token = (0, tracing_1.getTokenStorage)();
215
+ const model = (_a = params.model) !== null && _a !== void 0 ? _a : "dall-e-3";
216
+ const spanName = `trace.images ${model}`;
217
+ return this.tracer.startActiveSpan(spanName, (span) => __awaiter(this, void 0, void 0, function* () {
218
+ var _a, _b, _c;
219
+ const attributes = {
220
+ "gen_ai.request.model": model,
221
+ "gen_ai.system": "openai",
222
+ "gen_ai.operation.name": "image_generation",
223
+ };
224
+ if (externalCustomerId) {
225
+ attributes["external_customer_id"] = externalCustomerId;
226
+ }
227
+ if (token) {
228
+ attributes["token"] = token;
229
+ }
230
+ span.setAttributes(attributes);
231
+ try {
232
+ const response = yield this.openai.images.generate(params);
233
+ span.setAttributes({
234
+ "gen_ai.image.count": (_a = params.n) !== null && _a !== void 0 ? _a : 1,
235
+ "gen_ai.image.size": (_b = params.size) !== null && _b !== void 0 ? _b : "1024x1024",
236
+ "gen_ai.image.quality": (_c = params.quality) !== null && _c !== void 0 ? _c : "standard",
237
+ });
238
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
239
+ return response;
240
+ }
241
+ catch (error) {
242
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
243
+ span.recordException(error);
244
+ throw error;
245
+ }
246
+ finally {
247
+ span.end();
248
+ }
249
+ }));
250
+ });
251
+ }
252
+ }
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.0.6";
1
+ export declare const SDK_VERSION = "0.0.8-alpha0";
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SDK_VERSION = void 0;
4
- exports.SDK_VERSION = "0.0.6";
4
+ exports.SDK_VERSION = "0.0.8-alpha0";