@paid-ai/paid-node 0.0.8-alpha2 → 0.0.8-alpha4

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.
@@ -44,5 +44,4 @@ export declare class PaidClient {
44
44
  initializeTracing(collectorEndpoint?: string): Promise<void>;
45
45
  trace<T extends (...args: any[]) => any>(externalCustomerId: string, fn: T, externalAgentId?: string, ...args: Parameters<T>): Promise<ReturnType<T>>;
46
46
  signal(eventName: string, data?: Record<string, any>): void;
47
- getSpanProcessorAndInitialize(collectorEndpoint?: string): Promise<import("@opentelemetry/sdk-trace-base").SpanProcessor>;
48
47
  }
@@ -86,9 +86,9 @@ class PaidClient {
86
86
  var _a;
87
87
  return ((_a = this._usage) !== null && _a !== void 0 ? _a : (this._usage = new BatchUsage_js_1.Usage(this._options)));
88
88
  }
89
- // Use this method if you want paid to initialize tracing automatically.
90
- initializeTracing() {
91
- return __awaiter(this, arguments, void 0, function* (collectorEndpoint = "https://collector.agentpaid.io:4318/v1/traces") {
89
+ // Need to call this method before using tracing or creating wrappers.
90
+ initializeTracing(collectorEndpoint) {
91
+ return __awaiter(this, void 0, void 0, function* () {
92
92
  const tokenSupplier = this._options.token;
93
93
  const token = typeof tokenSupplier === "function" ? yield tokenSupplier() : tokenSupplier;
94
94
  const resolvedToken = yield Promise.resolve(token);
@@ -106,14 +106,5 @@ class PaidClient {
106
106
  signal(eventName, data) {
107
107
  return (0, signal_js_1._signal)(eventName, data);
108
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);
116
- });
117
- }
118
109
  }
119
110
  exports.PaidClient = PaidClient;
@@ -3,22 +3,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports._signal = _signal;
4
4
  const api_1 = require("@opentelemetry/api");
5
5
  const tracing_js_1 = require("./tracing.js");
6
+ const tracing_js_2 = require("./tracing.js");
6
7
  function _signal(eventName, data) {
7
8
  if (!eventName) {
8
9
  throw new Error("Event name is required for signal.");
9
10
  }
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
11
  const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
16
12
  const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
17
13
  const token = (0, tracing_js_1.getTokenStorage)();
18
14
  if (!externalCustomerId || !externalAgentId || !token) {
19
15
  throw new Error(`Missing some of: external_customer_id: ${externalCustomerId}, external_agent_id: ${externalAgentId}, or token. Make sure to call signal() within trace()`);
20
16
  }
21
- const tracer = api_1.trace.getTracer("paid.node");
17
+ const tracer = tracing_js_2.paidTracer;
22
18
  tracer.startActiveSpan("trace.signal", (span) => {
23
19
  try {
24
20
  const attributes = {
@@ -1,9 +1,8 @@
1
- import { SpanProcessor } from "@opentelemetry/sdk-trace-base";
2
1
  import winston from "winston";
3
2
  export declare const logger: winston.Logger;
3
+ export declare let paidTracer: import("@opentelemetry/api").Tracer;
4
4
  export declare const getCustomerIdStorage: () => string | null | undefined;
5
5
  export declare const getAgentIdStorage: () => string | null | undefined;
6
6
  export declare const getTokenStorage: () => string | null | undefined;
7
- export declare function _initializeTracing(apiKey: string, collectorEndpoint: string): void;
8
- export declare function _getSpanProcessorAndInitialize(apiKey: string, collectorEndpoint: string): SpanProcessor;
7
+ export declare function _initializeTracing(apiKey: string, collectorEndpoint?: string): void;
9
8
  export declare function _trace<T extends (...args: any[]) => any>(externalCustomerId: string, fn: T, externalAgentId: string | undefined, ...args: Parameters<T>): Promise<ReturnType<T>>;
@@ -12,11 +12,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.getTokenStorage = exports.getAgentIdStorage = exports.getCustomerIdStorage = exports.logger = void 0;
15
+ exports.getTokenStorage = exports.getAgentIdStorage = exports.getCustomerIdStorage = exports.paidTracer = exports.logger = void 0;
16
16
  exports._initializeTracing = _initializeTracing;
17
- exports._getSpanProcessorAndInitialize = _getSpanProcessorAndInitialize;
18
17
  exports._trace = _trace;
19
- const sdk_node_1 = require("@opentelemetry/sdk-node");
18
+ const sdk_trace_node_1 = require("@opentelemetry/sdk-trace-node");
20
19
  const exporter_trace_otlp_http_1 = require("@opentelemetry/exporter-trace-otlp-http");
21
20
  const sdk_trace_base_1 = require("@opentelemetry/sdk-trace-base");
22
21
  const api_1 = require("@opentelemetry/api");
@@ -31,6 +30,12 @@ const logLevel = process.env.PAID_LOG_LEVEL;
31
30
  if (logLevel) {
32
31
  exports.logger.level = logLevel;
33
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
+ exports.paidTracer = paidTracerProvider.getTracer("paid.node");
34
39
  // storage for passing info to child spans
35
40
  const customerIdStorage = new async_hooks_1.AsyncLocalStorage();
36
41
  const agentIdStorage = new async_hooks_1.AsyncLocalStorage();
@@ -63,19 +68,6 @@ function setupGracefulShutdown(shuttable) {
63
68
  });
64
69
  });
65
70
  }
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
71
  function _initializeTracing(apiKey, collectorEndpoint) {
80
72
  if (getToken()) {
81
73
  throw new Error("Tracing SDK is already initialized.");
@@ -83,40 +75,23 @@ function _initializeTracing(apiKey, collectorEndpoint) {
83
75
  if (!apiKey) {
84
76
  throw new Error("Cannot initialize tracing SDK - first initialize the PaidClient with an API key");
85
77
  }
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");
78
+ if (collectorEndpoint) {
79
+ paidExporter = new exporter_trace_otlp_http_1.OTLPTraceExporter({ url: collectorEndpoint });
80
+ spanProcessor = new sdk_trace_base_1.BatchSpanProcessor(paidExporter);
81
+ paidTracerProvider = new sdk_trace_node_1.NodeTracerProvider({ spanProcessors: [spanProcessor] });
82
+ exports.paidTracer = paidTracerProvider.getTracer("paid.node");
97
83
  }
98
- const sdk = new sdk_node_1.NodeSDK({
99
- traceExporter: new exporter_trace_otlp_http_1.OTLPTraceExporter({
100
- url: collectorEndpoint,
101
- }),
102
- });
103
- sdk.start();
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
84
  setupGracefulShutdown(spanProcessor);
112
- return spanProcessor;
85
+ setToken(apiKey);
86
+ const collectorAddress = collectorEndpoint || COLLECTOR_ENDPOINT;
87
+ exports.logger.info(`Paid tracing SDK initialized with collector endpoint: ${collectorAddress}`);
113
88
  }
114
89
  function _trace(externalCustomerId, fn, externalAgentId, ...args) {
115
90
  return __awaiter(this, void 0, void 0, function* () {
116
- const tracer = api_1.trace.getTracer("paid.node");
91
+ const tracer = exports.paidTracer;
117
92
  const token = getToken();
118
93
  if (!token || !externalCustomerId) {
119
- throw new Error(`Token [${token}] or external customer ID [${externalCustomerId}] is missing`);
94
+ throw new Error(`Paid tracing is not initialized. Make sure to call initializeTracing() first.`);
120
95
  }
121
96
  return tracer.startActiveSpan("paid.node", (span) => __awaiter(this, void 0, void 0, function* () {
122
97
  span.setAttribute("external_customer_id", externalCustomerId);
@@ -15,7 +15,7 @@ const tracing_js_1 = require("../tracing.js");
15
15
  class PaidAnthropic {
16
16
  constructor(anthropicClient) {
17
17
  this.anthropic = anthropicClient;
18
- this.tracer = api_1.trace.getTracer("paid.node");
18
+ this.tracer = tracing_js_1.paidTracer;
19
19
  }
20
20
  get messages() {
21
21
  return new MessagesWrapper(this.anthropic, this.tracer);
@@ -29,10 +29,6 @@ class MessagesWrapper {
29
29
  }
30
30
  create(params) {
31
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
32
  const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
37
33
  const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
38
34
  const token = (0, tracing_js_1.getTokenStorage)();
@@ -18,7 +18,7 @@ class PaidLangChainCallback extends base_1.BaseCallbackHandler {
18
18
  super();
19
19
  this.name = "PaidLangChainCallback";
20
20
  this.spans = new Map();
21
- this.tracer = api_1.trace.getTracer("paid.node");
21
+ this.tracer = tracing_js_1.paidTracer;
22
22
  }
23
23
  extractProvider(serialized) {
24
24
  if (!(serialized === null || serialized === void 0 ? void 0 : serialized.id))
@@ -40,10 +40,6 @@ class PaidLangChainCallback extends base_1.BaseCallbackHandler {
40
40
  }
41
41
  handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata) {
42
42
  return __awaiter(this, void 0, void 0, function* () {
43
- const currentSpan = api_1.trace.getSpan(api_1.context.active());
44
- if (!currentSpan) {
45
- throw new Error("No active span found, make sure to call this inside of a callback to paid.trace().");
46
- }
47
43
  const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
48
44
  const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
49
45
  const token = (0, tracing_js_1.getTokenStorage)();
@@ -15,7 +15,7 @@ const tracing_js_1 = require("../tracing.js");
15
15
  class PaidMistral {
16
16
  constructor(mistralClient) {
17
17
  this.mistral = mistralClient;
18
- this.tracer = api_1.trace.getTracer("paid.node");
18
+ this.tracer = tracing_js_1.paidTracer;
19
19
  }
20
20
  get ocr() {
21
21
  return new OCRWrapper(this.mistral, this.tracer);
@@ -29,10 +29,6 @@ class OCRWrapper {
29
29
  }
30
30
  process(request, options) {
31
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
32
  const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
37
33
  const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
38
34
  const token = (0, tracing_js_1.getTokenStorage)();
@@ -15,7 +15,7 @@ const tracing_js_1 = require("../tracing.js");
15
15
  class PaidOpenAI {
16
16
  constructor(openaiClient) {
17
17
  this.openai = openaiClient;
18
- this.tracer = api_1.trace.getTracer("paid.node");
18
+ this.tracer = tracing_js_1.paidTracer;
19
19
  }
20
20
  get chat() {
21
21
  return new ChatWrapper(this.openai, this.tracer);
@@ -47,10 +47,6 @@ class ChatCompletionsWrapper {
47
47
  }
48
48
  create(params) {
49
49
  return __awaiter(this, void 0, void 0, function* () {
50
- const currentSpan = api_1.trace.getSpan(api_1.context.active());
51
- if (!currentSpan) {
52
- throw new Error("No active span found, make sure to call this inside of a callback to paid.trace().");
53
- }
54
50
  const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
55
51
  const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
56
52
  const token = (0, tracing_js_1.getTokenStorage)();
@@ -99,10 +95,6 @@ class ResponsesWrapper {
99
95
  }
100
96
  create(params) {
101
97
  return __awaiter(this, void 0, void 0, function* () {
102
- const currentSpan = api_1.trace.getSpan(api_1.context.active());
103
- if (!currentSpan) {
104
- throw new Error("No active span found, make sure to call this inside of a callback to paid.trace().");
105
- }
106
98
  const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
107
99
  const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
108
100
  const token = (0, tracing_js_1.getTokenStorage)();
@@ -158,10 +150,6 @@ class EmbeddingsWrapper {
158
150
  }
159
151
  create(params) {
160
152
  return __awaiter(this, void 0, void 0, function* () {
161
- const currentSpan = api_1.trace.getSpan(api_1.context.active());
162
- if (!currentSpan) {
163
- throw new Error("No active span found, make sure to call this inside of a callback to paid.trace().");
164
- }
165
153
  const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
166
154
  const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
167
155
  const token = (0, tracing_js_1.getTokenStorage)();
@@ -210,10 +198,6 @@ class ImagesWrapper {
210
198
  generate(params) {
211
199
  return __awaiter(this, void 0, void 0, function* () {
212
200
  var _a;
213
- const currentSpan = api_1.trace.getSpan(api_1.context.active());
214
- if (!currentSpan) {
215
- throw new Error("No active span found, make sure to call this inside of a callback to paid.trace().");
216
- }
217
201
  const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
218
202
  const externalAgentId = (0, tracing_js_1.getAgentIdStorage)();
219
203
  const token = (0, tracing_js_1.getTokenStorage)();
@@ -0,0 +1,22 @@
1
+ import { generateText as originalGenerateText, streamText as originalStreamText, generateObject as originalGenerateObject, streamObject as originalStreamObject, embed as originalEmbed, embedMany as originalEmbedMany } from "ai";
2
+ type GenerateTextParams = Parameters<typeof originalGenerateText>[0];
3
+ type StreamTextParams = Parameters<typeof originalStreamText>[0];
4
+ type GenerateObjectParams = Parameters<typeof originalGenerateObject>[0];
5
+ type StreamObjectParams = Parameters<typeof originalStreamObject>[0];
6
+ type EmbedParams = Parameters<typeof originalEmbed>[0];
7
+ type EmbedManyParams = Parameters<typeof originalEmbedMany>[0];
8
+ export declare function generateText(params: GenerateTextParams): Promise<ReturnType<typeof originalGenerateText>>;
9
+ export declare function streamText(params: StreamTextParams): Promise<ReturnType<typeof originalStreamText>>;
10
+ export declare function generateObject(params: GenerateObjectParams): Promise<ReturnType<typeof originalGenerateObject>>;
11
+ export declare function streamObject(params: StreamObjectParams): Promise<ReturnType<typeof originalStreamObject>>;
12
+ export declare function embed(params: EmbedParams): Promise<ReturnType<typeof originalEmbed>>;
13
+ export declare function embedMany(params: EmbedManyParams): Promise<ReturnType<typeof originalEmbedMany>>;
14
+ declare const _default: {
15
+ generateText: typeof generateText;
16
+ streamText: typeof streamText;
17
+ generateObject: typeof generateObject;
18
+ streamObject: typeof streamObject;
19
+ embed: typeof embed;
20
+ embedMany: typeof embedMany;
21
+ };
22
+ export default _default;
@@ -0,0 +1,327 @@
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.generateText = generateText;
13
+ exports.streamText = streamText;
14
+ exports.generateObject = generateObject;
15
+ exports.streamObject = streamObject;
16
+ exports.embed = embed;
17
+ exports.embedMany = embedMany;
18
+ const api_1 = require("@opentelemetry/api");
19
+ const tracing_js_1 = require("../tracing.js");
20
+ const ai_1 = require("ai");
21
+ function getModelInfo(model) {
22
+ if (model === null || model === void 0 ? void 0 : model.modelId) {
23
+ const modelId = model.modelId;
24
+ if (modelId.startsWith('gpt-') || modelId.startsWith('text-embedding-') || modelId.startsWith('dall-e-')) {
25
+ return { system: 'openai', modelName: modelId };
26
+ }
27
+ if (modelId.startsWith('claude-')) {
28
+ return { system: 'anthropic', modelName: modelId };
29
+ }
30
+ if (modelId.startsWith('mistral-') || modelId.startsWith('codestral-')) {
31
+ return { system: 'mistral', modelName: modelId };
32
+ }
33
+ if (modelId.includes('gemini')) {
34
+ return { system: 'google', modelName: modelId };
35
+ }
36
+ }
37
+ if (model === null || model === void 0 ? void 0 : model.provider) {
38
+ return { system: model.provider, modelName: model.modelId };
39
+ }
40
+ return { system: 'unknown' };
41
+ }
42
+ function extractUsageMetrics(usage) {
43
+ const usageAttrs = {};
44
+ const inputTokens = usage.promptTokens || usage.prompt_tokens || usage.inputTokens;
45
+ const outputTokens = usage.completionTokens || usage.completion_tokens || usage.outputTokens;
46
+ const cachedTokens = usage.cachedPromptTokens || usage.cached_prompt_tokens || usage.cachedInputTokens;
47
+ if (inputTokens !== undefined) {
48
+ usageAttrs["gen_ai.usage.input_tokens"] = inputTokens;
49
+ }
50
+ if (outputTokens !== undefined) {
51
+ usageAttrs["gen_ai.usage.output_tokens"] = outputTokens;
52
+ }
53
+ if (cachedTokens !== undefined) {
54
+ usageAttrs["gen_ai.usage.cached_input_tokens"] = cachedTokens;
55
+ }
56
+ if (usage.tokens !== undefined && inputTokens === undefined) {
57
+ usageAttrs["gen_ai.usage.input_tokens"] = usage.tokens;
58
+ }
59
+ return usageAttrs;
60
+ }
61
+ function validateContext() {
62
+ const externalCustomerId = (0, tracing_js_1.getCustomerIdStorage)();
63
+ const token = (0, tracing_js_1.getTokenStorage)();
64
+ if (!token || !externalCustomerId) {
65
+ throw new Error("No token or externalCustomerId: This wrapper should be used inside a callback to paid.trace().");
66
+ }
67
+ return {
68
+ externalCustomerId,
69
+ externalAgentId: (0, tracing_js_1.getAgentIdStorage)(),
70
+ token,
71
+ };
72
+ }
73
+ function generateText(params) {
74
+ return __awaiter(this, void 0, void 0, function* () {
75
+ const context = validateContext();
76
+ const { system: aiSystem, modelName } = getModelInfo(params.model);
77
+ return tracing_js_1.paidTracer.startActiveSpan("trace.ai-sdk.generateText", (span) => __awaiter(this, void 0, void 0, function* () {
78
+ var _a;
79
+ const attributes = {
80
+ "gen_ai.system": aiSystem,
81
+ "gen_ai.operation.name": "chat",
82
+ "external_customer_id": context.externalCustomerId,
83
+ "token": context.token,
84
+ };
85
+ if (context.externalAgentId) {
86
+ attributes["external_agent_id"] = context.externalAgentId;
87
+ }
88
+ if (modelName) {
89
+ attributes["gen_ai.request.model"] = modelName;
90
+ }
91
+ span.setAttributes(attributes);
92
+ try {
93
+ const result = yield (0, ai_1.generateText)(params);
94
+ if (result.usage) {
95
+ const usageAttrs = extractUsageMetrics(result.usage);
96
+ span.setAttributes(usageAttrs);
97
+ }
98
+ if ((_a = result.response) === null || _a === void 0 ? void 0 : _a.modelId) {
99
+ span.setAttribute("gen_ai.response.model", result.response.modelId);
100
+ }
101
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
102
+ return result;
103
+ }
104
+ catch (error) {
105
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
106
+ span.recordException(error);
107
+ throw error;
108
+ }
109
+ finally {
110
+ span.end();
111
+ }
112
+ }));
113
+ });
114
+ }
115
+ function streamText(params) {
116
+ return __awaiter(this, void 0, void 0, function* () {
117
+ const context = validateContext();
118
+ const { system: aiSystem, modelName } = getModelInfo(params.model);
119
+ return tracing_js_1.paidTracer.startActiveSpan("trace.ai-sdk.streamText", (span) => __awaiter(this, void 0, void 0, function* () {
120
+ const attributes = {
121
+ "gen_ai.system": aiSystem,
122
+ "gen_ai.operation.name": "chat",
123
+ "external_customer_id": context.externalCustomerId,
124
+ "token": context.token,
125
+ };
126
+ if (context.externalAgentId) {
127
+ attributes["external_agent_id"] = context.externalAgentId;
128
+ }
129
+ if (modelName) {
130
+ attributes["gen_ai.request.model"] = modelName;
131
+ }
132
+ span.setAttributes(attributes);
133
+ try {
134
+ const originalOnFinish = params.onFinish;
135
+ const wrappedParams = Object.assign(Object.assign({}, params), { onFinish: (result) => {
136
+ if (result.usage) {
137
+ const usageAttrs = extractUsageMetrics(result.usage);
138
+ span.setAttributes(usageAttrs);
139
+ }
140
+ if (originalOnFinish) {
141
+ originalOnFinish(result);
142
+ }
143
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
144
+ span.end();
145
+ } });
146
+ const result = (0, ai_1.streamText)(wrappedParams);
147
+ return result;
148
+ }
149
+ catch (error) {
150
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
151
+ span.recordException(error);
152
+ throw error;
153
+ }
154
+ finally {
155
+ span.end();
156
+ }
157
+ }));
158
+ });
159
+ }
160
+ function generateObject(params) {
161
+ return __awaiter(this, void 0, void 0, function* () {
162
+ const context = validateContext();
163
+ const { system: aiSystem, modelName } = getModelInfo(params.model);
164
+ return tracing_js_1.paidTracer.startActiveSpan("trace.ai-sdk.generateObject", (span) => __awaiter(this, void 0, void 0, function* () {
165
+ var _a;
166
+ const attributes = {
167
+ "gen_ai.system": aiSystem,
168
+ "gen_ai.operation.name": "chat",
169
+ "external_customer_id": context.externalCustomerId,
170
+ "token": context.token,
171
+ };
172
+ if (context.externalAgentId) {
173
+ attributes["external_agent_id"] = context.externalAgentId;
174
+ }
175
+ if (modelName) {
176
+ attributes["gen_ai.request.model"] = modelName;
177
+ }
178
+ span.setAttributes(attributes);
179
+ try {
180
+ const result = yield (0, ai_1.generateObject)(params);
181
+ if (result.usage) {
182
+ const usageAttrs = extractUsageMetrics(result.usage);
183
+ span.setAttributes(usageAttrs);
184
+ }
185
+ if ((_a = result.response) === null || _a === void 0 ? void 0 : _a.modelId) {
186
+ span.setAttribute("gen_ai.response.model", result.response.modelId);
187
+ }
188
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
189
+ return result;
190
+ }
191
+ catch (error) {
192
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
193
+ span.recordException(error);
194
+ throw error;
195
+ }
196
+ finally {
197
+ span.end();
198
+ }
199
+ }));
200
+ });
201
+ }
202
+ function streamObject(params) {
203
+ return __awaiter(this, void 0, void 0, function* () {
204
+ const context = validateContext();
205
+ const { system: aiSystem, modelName } = getModelInfo(params.model);
206
+ return tracing_js_1.paidTracer.startActiveSpan("trace.ai-sdk.streamObject", (span) => __awaiter(this, void 0, void 0, function* () {
207
+ const attributes = {
208
+ "gen_ai.system": aiSystem,
209
+ "gen_ai.operation.name": "chat",
210
+ "external_customer_id": context.externalCustomerId,
211
+ "token": context.token,
212
+ };
213
+ if (context.externalAgentId) {
214
+ attributes["external_agent_id"] = context.externalAgentId;
215
+ }
216
+ if (modelName) {
217
+ attributes["gen_ai.request.model"] = modelName;
218
+ }
219
+ span.setAttributes(attributes);
220
+ try {
221
+ const originalOnFinish = params.onFinish;
222
+ const wrappedParams = Object.assign(Object.assign({}, params), { onFinish: (result) => {
223
+ if (result.usage) {
224
+ const usageAttrs = extractUsageMetrics(result.usage);
225
+ span.setAttributes(usageAttrs);
226
+ }
227
+ if (originalOnFinish) {
228
+ originalOnFinish(result);
229
+ }
230
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
231
+ span.end();
232
+ } });
233
+ const result = (0, ai_1.streamObject)(wrappedParams);
234
+ return result;
235
+ }
236
+ catch (error) {
237
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
238
+ span.recordException(error);
239
+ throw error;
240
+ }
241
+ }));
242
+ });
243
+ }
244
+ function embed(params) {
245
+ return __awaiter(this, void 0, void 0, function* () {
246
+ const context = validateContext();
247
+ const { system: aiSystem, modelName } = getModelInfo(params.model);
248
+ return tracing_js_1.paidTracer.startActiveSpan("trace.ai-sdk.embed", (span) => __awaiter(this, void 0, void 0, function* () {
249
+ const attributes = {
250
+ "gen_ai.system": aiSystem,
251
+ "gen_ai.operation.name": "embeddings",
252
+ "external_customer_id": context.externalCustomerId,
253
+ "token": context.token,
254
+ };
255
+ if (context.externalAgentId) {
256
+ attributes["external_agent_id"] = context.externalAgentId;
257
+ }
258
+ if (modelName) {
259
+ attributes["gen_ai.request.model"] = modelName;
260
+ }
261
+ span.setAttributes(attributes);
262
+ try {
263
+ const result = yield (0, ai_1.embed)(params);
264
+ if (result.usage) {
265
+ const usageAttrs = extractUsageMetrics(result.usage);
266
+ span.setAttributes(usageAttrs);
267
+ }
268
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
269
+ return result;
270
+ }
271
+ catch (error) {
272
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
273
+ span.recordException(error);
274
+ throw error;
275
+ }
276
+ finally {
277
+ span.end();
278
+ }
279
+ }));
280
+ });
281
+ }
282
+ function embedMany(params) {
283
+ return __awaiter(this, void 0, void 0, function* () {
284
+ const context = validateContext();
285
+ const { system: aiSystem, modelName } = getModelInfo(params.model);
286
+ return tracing_js_1.paidTracer.startActiveSpan("trace.ai-sdk.embedMany", (span) => __awaiter(this, void 0, void 0, function* () {
287
+ const attributes = {
288
+ "gen_ai.system": aiSystem,
289
+ "gen_ai.operation.name": "embeddings",
290
+ "external_customer_id": context.externalCustomerId,
291
+ "token": context.token,
292
+ };
293
+ if (context.externalAgentId) {
294
+ attributes["external_agent_id"] = context.externalAgentId;
295
+ }
296
+ if (modelName) {
297
+ attributes["gen_ai.request.model"] = modelName;
298
+ }
299
+ span.setAttributes(attributes);
300
+ try {
301
+ const result = yield (0, ai_1.embedMany)(params);
302
+ if (result.usage) {
303
+ const usageAttrs = extractUsageMetrics(result.usage);
304
+ span.setAttributes(usageAttrs);
305
+ }
306
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
307
+ return result;
308
+ }
309
+ catch (error) {
310
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error.message });
311
+ span.recordException(error);
312
+ throw error;
313
+ }
314
+ finally {
315
+ span.end();
316
+ }
317
+ }));
318
+ });
319
+ }
320
+ exports.default = {
321
+ generateText,
322
+ streamText,
323
+ generateObject,
324
+ streamObject,
325
+ embed,
326
+ embedMany,
327
+ };
@@ -0,0 +1 @@
1
+ export { generateText as paidGenerateText, streamText as paidStreamText, generateObject as paidGenerateObject, streamObject as paidStreamObject, embed as paidEmbed, embedMany as paidEmbedMany, } from "../tracing/wrappers/vercelAIWrapper.js";
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.paidEmbedMany = exports.paidEmbed = exports.paidStreamObject = exports.paidGenerateObject = exports.paidStreamText = exports.paidGenerateText = void 0;
4
+ var vercelAIWrapper_js_1 = require("../tracing/wrappers/vercelAIWrapper.js");
5
+ Object.defineProperty(exports, "paidGenerateText", { enumerable: true, get: function () { return vercelAIWrapper_js_1.generateText; } });
6
+ Object.defineProperty(exports, "paidStreamText", { enumerable: true, get: function () { return vercelAIWrapper_js_1.streamText; } });
7
+ Object.defineProperty(exports, "paidGenerateObject", { enumerable: true, get: function () { return vercelAIWrapper_js_1.generateObject; } });
8
+ Object.defineProperty(exports, "paidStreamObject", { enumerable: true, get: function () { return vercelAIWrapper_js_1.streamObject; } });
9
+ Object.defineProperty(exports, "paidEmbed", { enumerable: true, get: function () { return vercelAIWrapper_js_1.embed; } });
10
+ Object.defineProperty(exports, "paidEmbedMany", { enumerable: true, get: function () { return vercelAIWrapper_js_1.embedMany; } });
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.0.8-alpha2";
1
+ export declare const SDK_VERSION = "0.0.8-alpha4";
@@ -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.8-alpha2";
4
+ exports.SDK_VERSION = "0.0.8-alpha4";