cencori 1.16.4 → 1.18.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.
@@ -0,0 +1,164 @@
1
+ import * as _opentelemetry_api from '@opentelemetry/api';
2
+ import { Span } from '@opentelemetry/api';
3
+ import { ExportResult } from '@opentelemetry/core';
4
+ import { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';
5
+
6
+ /**
7
+ * Sends spans to Cencori (POST /api/v1/traces) as OTLP/JSON, authenticated with the project's
8
+ * Cencori key. Written here rather than taken from OpenTelemetry's exporters, which bring a
9
+ * protobuf runtime and add tens of megabytes to every install.
10
+ *
11
+ * The key is read when a batch is sent, not when the exporter is made: `cencori/observe` is
12
+ * imported first thing, often before a .env file has been loaded.
13
+ */
14
+ interface CencoriExporterOptions {
15
+ /** Defaults to CENCORI_API_KEY. */
16
+ apiKey?: string;
17
+ /** Defaults to CENCORI_BASE_URL, then https://cencori.com. */
18
+ baseUrl?: string;
19
+ /** Print what happens to each batch. Also CENCORI_OBSERVE_DEBUG=1. */
20
+ debug?: boolean;
21
+ /** Replaces the resource's service.name on everything sent. */
22
+ serviceName?: string;
23
+ /** false: drop prompts, replies and tool arguments before they leave the app. Also CENCORI_OBSERVE_CONTENT=false. */
24
+ captureContent?: boolean;
25
+ }
26
+ type AnyValue = {
27
+ stringValue: string;
28
+ } | {
29
+ boolValue: boolean;
30
+ } | {
31
+ intValue: string;
32
+ } | {
33
+ doubleValue: number;
34
+ } | {
35
+ arrayValue: {
36
+ values: AnyValue[];
37
+ };
38
+ } | Record<string, never>;
39
+ /** ReadableSpans as an OTLP/JSON ExportTraceServiceRequest, grouped by resource and scope. */
40
+ declare function toOtlpJson(spans: ReadableSpan[], options?: {
41
+ serviceName?: string;
42
+ captureContent?: boolean;
43
+ }): {
44
+ resourceSpans: {
45
+ resource: {
46
+ attributes: {
47
+ key: string;
48
+ value: AnyValue;
49
+ }[];
50
+ };
51
+ scopeSpans: {
52
+ scope: {
53
+ name: string;
54
+ version: string | undefined;
55
+ };
56
+ spans: {
57
+ traceId: string;
58
+ spanId: string;
59
+ parentSpanId: string | undefined;
60
+ name: string;
61
+ kind: number;
62
+ startTimeUnixNano: string;
63
+ endTimeUnixNano: string;
64
+ attributes: {
65
+ key: string;
66
+ value: AnyValue;
67
+ }[];
68
+ events: {
69
+ name: string;
70
+ timeUnixNano: string;
71
+ attributes: {
72
+ key: string;
73
+ value: AnyValue;
74
+ }[];
75
+ }[];
76
+ status: {
77
+ message?: string | undefined;
78
+ code: _opentelemetry_api.SpanStatusCode;
79
+ };
80
+ }[];
81
+ }[];
82
+ }[];
83
+ };
84
+ declare class CencoriSpanExporter implements SpanExporter {
85
+ private warnedNoKey;
86
+ private stopped;
87
+ private readonly pending;
88
+ private options;
89
+ constructor(options?: CencoriExporterOptions);
90
+ /** Change options for batches sent from now on (observe() called after the import started it). */
91
+ configure(options: CencoriExporterOptions): void;
92
+ private get captureContent();
93
+ private get debug();
94
+ export(spans: ReadableSpan[], done: (result: ExportResult) => void): void;
95
+ private send;
96
+ forceFlush(): Promise<void>;
97
+ shutdown(): Promise<void>;
98
+ }
99
+
100
+ /**
101
+ * Cencori Observe: traces of your AI app in Cencori → Observability, from one import.
102
+ *
103
+ * @example Node (CommonJS, or `node --import cencori/observe app.js`):
104
+ * import 'cencori/observe'; // first line; reads CENCORI_API_KEY
105
+ *
106
+ * @example Next.js and other bundled or ESM apps: hand it the clients you use
107
+ * import OpenAI from 'openai';
108
+ * import { observe } from 'cencori/observe';
109
+ * observe({ openai: OpenAI });
110
+ *
111
+ * Model calls through the OpenAI and Anthropic SDKs are recorded with their prompts, responses,
112
+ * tokens and timing; LangChain's chains and tools too when
113
+ * @arizeai/openinference-instrumentation-langchain is installed. Everything is sent as
114
+ * OpenTelemetry to Cencori's /v1/traces with your Cencori key, and nothing else is needed.
115
+ */
116
+
117
+ interface ObserveOptions extends CencoriExporterOptions {
118
+ /** Shown on every trace. Defaults to CENCORI_SERVICE_NAME, OTEL_SERVICE_NAME or your package name. */
119
+ serviceName?: string;
120
+ /**
121
+ * Record prompts and responses (default true; CENCORI_OBSERVE_CONTENT=false turns it off).
122
+ * Off, Cencori still gets the model, tokens, timing and errors of each call.
123
+ */
124
+ captureContent?: boolean;
125
+ /** The OpenAI client class (or a client): needed in bundled and ESM apps, harmless elsewhere. */
126
+ openai?: unknown;
127
+ /** The Anthropic client class (or a client): needed in bundled and ESM apps. */
128
+ anthropic?: unknown;
129
+ /** `import * as CallbackManagerModule from '@langchain/core/callbacks/manager'`, for LangChain in bundled and ESM apps. */
130
+ langchain?: unknown;
131
+ }
132
+ /** Who and what a stretch of work is for, put on every span started inside it. */
133
+ interface ObserveContext {
134
+ userId?: string;
135
+ sessionId?: string;
136
+ tags?: string[];
137
+ metadata?: Record<string, string | number | boolean>;
138
+ }
139
+ /**
140
+ * Start sending traces to Cencori (already done by importing this module), and instrument the
141
+ * client classes you pass. Safe to call more than once. Returns false where it cannot run
142
+ * (a browser, or CENCORI_OBSERVE=false).
143
+ */
144
+ declare function observe(options?: ObserveOptions): boolean;
145
+ /** Run `fn` with a user, session, tags or metadata on every span inside it (model calls included). */
146
+ declare function withContext<T>(values: ObserveContext, fn: () => T): T;
147
+ type StepType = 'agent' | 'chain' | 'tool' | 'retriever' | 'llm' | 'embedding';
148
+ /**
149
+ * Record a step of your own (an agent run, a tool, a pipeline stage) as a span, with the model
150
+ * calls made inside it as its children. Errors are recorded and rethrown.
151
+ *
152
+ * @example
153
+ * const answer = await trace('answer-ticket', () => agent.run(ticket), { type: 'agent', input: ticket.text });
154
+ */
155
+ declare function trace<T>(name: string, fn: (span: Span) => T, options?: {
156
+ type?: StepType;
157
+ input?: unknown;
158
+ }): T;
159
+ /** Send every span recorded so far. Await it before a serverless function returns. */
160
+ declare function flush(): Promise<void>;
161
+ /** Flush and stop sending traces. */
162
+ declare function shutdown(): Promise<void>;
163
+
164
+ export { type CencoriExporterOptions, CencoriSpanExporter, type ObserveContext, type ObserveOptions, type StepType, flush, observe, shutdown, toOtlpJson, trace, withContext };
@@ -0,0 +1,164 @@
1
+ import * as _opentelemetry_api from '@opentelemetry/api';
2
+ import { Span } from '@opentelemetry/api';
3
+ import { ExportResult } from '@opentelemetry/core';
4
+ import { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';
5
+
6
+ /**
7
+ * Sends spans to Cencori (POST /api/v1/traces) as OTLP/JSON, authenticated with the project's
8
+ * Cencori key. Written here rather than taken from OpenTelemetry's exporters, which bring a
9
+ * protobuf runtime and add tens of megabytes to every install.
10
+ *
11
+ * The key is read when a batch is sent, not when the exporter is made: `cencori/observe` is
12
+ * imported first thing, often before a .env file has been loaded.
13
+ */
14
+ interface CencoriExporterOptions {
15
+ /** Defaults to CENCORI_API_KEY. */
16
+ apiKey?: string;
17
+ /** Defaults to CENCORI_BASE_URL, then https://cencori.com. */
18
+ baseUrl?: string;
19
+ /** Print what happens to each batch. Also CENCORI_OBSERVE_DEBUG=1. */
20
+ debug?: boolean;
21
+ /** Replaces the resource's service.name on everything sent. */
22
+ serviceName?: string;
23
+ /** false: drop prompts, replies and tool arguments before they leave the app. Also CENCORI_OBSERVE_CONTENT=false. */
24
+ captureContent?: boolean;
25
+ }
26
+ type AnyValue = {
27
+ stringValue: string;
28
+ } | {
29
+ boolValue: boolean;
30
+ } | {
31
+ intValue: string;
32
+ } | {
33
+ doubleValue: number;
34
+ } | {
35
+ arrayValue: {
36
+ values: AnyValue[];
37
+ };
38
+ } | Record<string, never>;
39
+ /** ReadableSpans as an OTLP/JSON ExportTraceServiceRequest, grouped by resource and scope. */
40
+ declare function toOtlpJson(spans: ReadableSpan[], options?: {
41
+ serviceName?: string;
42
+ captureContent?: boolean;
43
+ }): {
44
+ resourceSpans: {
45
+ resource: {
46
+ attributes: {
47
+ key: string;
48
+ value: AnyValue;
49
+ }[];
50
+ };
51
+ scopeSpans: {
52
+ scope: {
53
+ name: string;
54
+ version: string | undefined;
55
+ };
56
+ spans: {
57
+ traceId: string;
58
+ spanId: string;
59
+ parentSpanId: string | undefined;
60
+ name: string;
61
+ kind: number;
62
+ startTimeUnixNano: string;
63
+ endTimeUnixNano: string;
64
+ attributes: {
65
+ key: string;
66
+ value: AnyValue;
67
+ }[];
68
+ events: {
69
+ name: string;
70
+ timeUnixNano: string;
71
+ attributes: {
72
+ key: string;
73
+ value: AnyValue;
74
+ }[];
75
+ }[];
76
+ status: {
77
+ message?: string | undefined;
78
+ code: _opentelemetry_api.SpanStatusCode;
79
+ };
80
+ }[];
81
+ }[];
82
+ }[];
83
+ };
84
+ declare class CencoriSpanExporter implements SpanExporter {
85
+ private warnedNoKey;
86
+ private stopped;
87
+ private readonly pending;
88
+ private options;
89
+ constructor(options?: CencoriExporterOptions);
90
+ /** Change options for batches sent from now on (observe() called after the import started it). */
91
+ configure(options: CencoriExporterOptions): void;
92
+ private get captureContent();
93
+ private get debug();
94
+ export(spans: ReadableSpan[], done: (result: ExportResult) => void): void;
95
+ private send;
96
+ forceFlush(): Promise<void>;
97
+ shutdown(): Promise<void>;
98
+ }
99
+
100
+ /**
101
+ * Cencori Observe: traces of your AI app in Cencori → Observability, from one import.
102
+ *
103
+ * @example Node (CommonJS, or `node --import cencori/observe app.js`):
104
+ * import 'cencori/observe'; // first line; reads CENCORI_API_KEY
105
+ *
106
+ * @example Next.js and other bundled or ESM apps: hand it the clients you use
107
+ * import OpenAI from 'openai';
108
+ * import { observe } from 'cencori/observe';
109
+ * observe({ openai: OpenAI });
110
+ *
111
+ * Model calls through the OpenAI and Anthropic SDKs are recorded with their prompts, responses,
112
+ * tokens and timing; LangChain's chains and tools too when
113
+ * @arizeai/openinference-instrumentation-langchain is installed. Everything is sent as
114
+ * OpenTelemetry to Cencori's /v1/traces with your Cencori key, and nothing else is needed.
115
+ */
116
+
117
+ interface ObserveOptions extends CencoriExporterOptions {
118
+ /** Shown on every trace. Defaults to CENCORI_SERVICE_NAME, OTEL_SERVICE_NAME or your package name. */
119
+ serviceName?: string;
120
+ /**
121
+ * Record prompts and responses (default true; CENCORI_OBSERVE_CONTENT=false turns it off).
122
+ * Off, Cencori still gets the model, tokens, timing and errors of each call.
123
+ */
124
+ captureContent?: boolean;
125
+ /** The OpenAI client class (or a client): needed in bundled and ESM apps, harmless elsewhere. */
126
+ openai?: unknown;
127
+ /** The Anthropic client class (or a client): needed in bundled and ESM apps. */
128
+ anthropic?: unknown;
129
+ /** `import * as CallbackManagerModule from '@langchain/core/callbacks/manager'`, for LangChain in bundled and ESM apps. */
130
+ langchain?: unknown;
131
+ }
132
+ /** Who and what a stretch of work is for, put on every span started inside it. */
133
+ interface ObserveContext {
134
+ userId?: string;
135
+ sessionId?: string;
136
+ tags?: string[];
137
+ metadata?: Record<string, string | number | boolean>;
138
+ }
139
+ /**
140
+ * Start sending traces to Cencori (already done by importing this module), and instrument the
141
+ * client classes you pass. Safe to call more than once. Returns false where it cannot run
142
+ * (a browser, or CENCORI_OBSERVE=false).
143
+ */
144
+ declare function observe(options?: ObserveOptions): boolean;
145
+ /** Run `fn` with a user, session, tags or metadata on every span inside it (model calls included). */
146
+ declare function withContext<T>(values: ObserveContext, fn: () => T): T;
147
+ type StepType = 'agent' | 'chain' | 'tool' | 'retriever' | 'llm' | 'embedding';
148
+ /**
149
+ * Record a step of your own (an agent run, a tool, a pipeline stage) as a span, with the model
150
+ * calls made inside it as its children. Errors are recorded and rethrown.
151
+ *
152
+ * @example
153
+ * const answer = await trace('answer-ticket', () => agent.run(ticket), { type: 'agent', input: ticket.text });
154
+ */
155
+ declare function trace<T>(name: string, fn: (span: Span) => T, options?: {
156
+ type?: StepType;
157
+ input?: unknown;
158
+ }): T;
159
+ /** Send every span recorded so far. Await it before a serverless function returns. */
160
+ declare function flush(): Promise<void>;
161
+ /** Flush and stop sending traces. */
162
+ declare function shutdown(): Promise<void>;
163
+
164
+ export { type CencoriExporterOptions, CencoriSpanExporter, type ObserveContext, type ObserveOptions, type StepType, flush, observe, shutdown, toOtlpJson, trace, withContext };
@@ -0,0 +1,339 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/observe/index.ts
31
+ var observe_exports = {};
32
+ __export(observe_exports, {
33
+ CencoriSpanExporter: () => CencoriSpanExporter,
34
+ flush: () => flush,
35
+ observe: () => observe,
36
+ shutdown: () => shutdown,
37
+ toOtlpJson: () => toOtlpJson,
38
+ trace: () => trace,
39
+ withContext: () => withContext
40
+ });
41
+ module.exports = __toCommonJS(observe_exports);
42
+ var import_api2 = require("@opentelemetry/api");
43
+ var import_context_async_hooks = require("@opentelemetry/context-async-hooks");
44
+ var import_resources = require("@opentelemetry/resources");
45
+ var import_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
46
+ var import_node_module = require("module");
47
+ var import_node_path = __toESM(require("path"));
48
+
49
+ // src/observe/exporter.ts
50
+ var import_api = require("@opentelemetry/api");
51
+ var import_core = require("@opentelemetry/core");
52
+ var import_node_zlib = require("zlib");
53
+ var CONTENT_ATTRIBUTE = /^(gen_ai\.(prompt|completion)\.\d+\.|gen_ai\.(input|output)\.messages$|gen_ai\.tool\.call\.(arguments|result)$|gen_ai\.system_instructions$|llm\.(input|output)_messages\.|llm\.prompts?\b|llm\.prompt_template\.|input\.value$|output\.value$|ai\.prompt|ai\.response\.(text|object|toolCalls|reasoning)|ai\.toolCall\.(args|input|result|output)$|traceloop\.entity\.(input|output)$)/;
54
+ var CONTENT_EVENT = /^gen_ai\.(system|user|assistant|tool)\.message$|^gen_ai\.choice$/;
55
+ var DEFAULT_BASE_URL = "https://cencori.com";
56
+ var TIMEOUT_MS = 1e4;
57
+ var MAX_RETRY_WAIT_MS = 1e4;
58
+ function anyValue(value) {
59
+ if (value === null || value === void 0) return {};
60
+ if (typeof value === "string") return { stringValue: value };
61
+ if (typeof value === "boolean") return { boolValue: value };
62
+ if (typeof value === "number") return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };
63
+ if (Array.isArray(value)) return { arrayValue: { values: value.map(anyValue) } };
64
+ return {};
65
+ }
66
+ var keyValues = (attributes, dropContent = false) => Object.entries(attributes ?? {}).filter(([key]) => !dropContent || !CONTENT_ATTRIBUTE.test(key)).map(([key, value]) => ({ key, value: anyValue(value) }));
67
+ var nanos = (time) => (BigInt(time[0]) * BigInt(1e9) + BigInt(time[1])).toString();
68
+ function toOtlpJson(spans, options = {}) {
69
+ const dropContent = options.captureContent === false;
70
+ const resourceAttributes = (attributes) => keyValues(options.serviceName ? { ...attributes, "service.name": options.serviceName } : attributes);
71
+ const byResource = /* @__PURE__ */ new Map();
72
+ for (const span of spans) {
73
+ const scopes = byResource.get(span.resource) ?? /* @__PURE__ */ new Map();
74
+ const scope = `${span.instrumentationScope.name}\0${span.instrumentationScope.version ?? ""}`;
75
+ scopes.set(scope, [...scopes.get(scope) ?? [], span]);
76
+ byResource.set(span.resource, scopes);
77
+ }
78
+ return {
79
+ resourceSpans: [...byResource.entries()].map(([resource, scopes]) => ({
80
+ resource: { attributes: resourceAttributes(resource.attributes) },
81
+ scopeSpans: [...scopes.values()].map((list) => ({
82
+ scope: { name: list[0].instrumentationScope.name, version: list[0].instrumentationScope.version },
83
+ spans: list.map((span) => ({
84
+ traceId: span.spanContext().traceId,
85
+ spanId: span.spanContext().spanId,
86
+ parentSpanId: span.parentSpanContext?.spanId,
87
+ name: span.name,
88
+ kind: span.kind + 1,
89
+ // the API's SpanKind starts at INTERNAL = 0; OTLP's at UNSPECIFIED = 0
90
+ startTimeUnixNano: nanos(span.startTime),
91
+ endTimeUnixNano: nanos(span.endTime),
92
+ attributes: keyValues(span.attributes, dropContent),
93
+ events: span.events.filter((event) => !dropContent || !CONTENT_EVENT.test(event.name)).map((event) => ({ name: event.name, timeUnixNano: nanos(event.time), attributes: keyValues(event.attributes, dropContent) })),
94
+ status: { code: span.status.code, ...span.status.message ? { message: span.status.message } : {} }
95
+ }))
96
+ }))
97
+ }))
98
+ };
99
+ }
100
+ var CencoriSpanExporter = class {
101
+ constructor(options = {}) {
102
+ this.warnedNoKey = false;
103
+ this.stopped = false;
104
+ this.pending = /* @__PURE__ */ new Set();
105
+ this.options = { ...options };
106
+ }
107
+ /** Change options for batches sent from now on (observe() called after the import started it). */
108
+ configure(options) {
109
+ for (const [key, value] of Object.entries(options)) {
110
+ if (value !== void 0) this.options[key] = value;
111
+ }
112
+ }
113
+ get captureContent() {
114
+ return this.options.captureContent ?? !/^(0|false|off)$/i.test(process.env.CENCORI_OBSERVE_CONTENT ?? "");
115
+ }
116
+ get debug() {
117
+ return this.options.debug || process.env.CENCORI_OBSERVE_DEBUG === "1";
118
+ }
119
+ export(spans, done) {
120
+ if (this.stopped) return done({ code: import_core.ExportResultCode.FAILED, error: new Error("Exporter is shut down") });
121
+ const sending = this.send(spans).then(done, (error) => done({ code: import_core.ExportResultCode.FAILED, error }));
122
+ this.pending.add(sending);
123
+ void sending.finally(() => this.pending.delete(sending));
124
+ }
125
+ async send(spans) {
126
+ const apiKey = this.options.apiKey || process.env.CENCORI_API_KEY;
127
+ if (!apiKey) {
128
+ if (!this.warnedNoKey) {
129
+ this.warnedNoKey = true;
130
+ console.warn("[cencori] observe: CENCORI_API_KEY is not set, so traces are not being sent to Cencori.");
131
+ }
132
+ return { code: import_core.ExportResultCode.FAILED, error: new Error("CENCORI_API_KEY is not set") };
133
+ }
134
+ const base = (this.options.baseUrl || process.env.CENCORI_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
135
+ const json = JSON.stringify(toOtlpJson(spans, {
136
+ serviceName: this.options.serviceName,
137
+ captureContent: this.captureContent
138
+ }));
139
+ const compressed = json.length > 1024;
140
+ const body = compressed ? (0, import_node_zlib.gzipSync)(json) : json;
141
+ for (let attempt = 0; attempt < 2; attempt++) {
142
+ let wait = 1e3;
143
+ try {
144
+ const res = await import_api.context.with((0, import_core.suppressTracing)(import_api.context.active()), () => fetch(`${base}/api/v1/traces`, {
145
+ method: "POST",
146
+ headers: {
147
+ Authorization: `Bearer ${apiKey}`,
148
+ "Content-Type": "application/json",
149
+ ...compressed ? { "Content-Encoding": "gzip" } : {}
150
+ },
151
+ body,
152
+ signal: AbortSignal.timeout(TIMEOUT_MS)
153
+ }));
154
+ if (res.ok) {
155
+ const reply = await res.json().catch(() => ({}));
156
+ if (this.debug) console.info(`[cencori] observe: sent ${spans.length} span(s)${reply.partialSuccess?.rejectedSpans ? `, ${reply.partialSuccess.rejectedSpans} rejected: ${reply.partialSuccess.errorMessage}` : ""}`);
157
+ return { code: import_core.ExportResultCode.SUCCESS };
158
+ }
159
+ const text = await res.text().catch(() => "");
160
+ if (res.status !== 429 && res.status < 500) {
161
+ console.warn(`[cencori] observe: Cencori refused ${spans.length} span(s) (${res.status}): ${text.slice(0, 200)}`);
162
+ return { code: import_core.ExportResultCode.FAILED, error: new Error(`HTTP ${res.status}`) };
163
+ }
164
+ const retryAfter = Number(res.headers.get("retry-after"));
165
+ if (Number.isFinite(retryAfter) && retryAfter > 0) wait = Math.min(retryAfter * 1e3, MAX_RETRY_WAIT_MS);
166
+ if (this.debug) console.info(`[cencori] observe: Cencori answered ${res.status}; ${attempt === 0 ? "retrying" : "dropping the batch"}`);
167
+ } catch (error) {
168
+ if (this.debug) console.info(`[cencori] observe: sending failed (${error.message}); ${attempt === 0 ? "retrying" : "dropping the batch"}`);
169
+ }
170
+ if (attempt === 0) await new Promise((resolve) => setTimeout(resolve, wait));
171
+ }
172
+ return { code: import_core.ExportResultCode.FAILED, error: new Error("Cencori could not be reached") };
173
+ }
174
+ async forceFlush() {
175
+ await Promise.all([...this.pending]);
176
+ }
177
+ async shutdown() {
178
+ this.stopped = true;
179
+ await this.forceFlush();
180
+ }
181
+ };
182
+
183
+ // src/observe/index.ts
184
+ var import_meta = {};
185
+ var STATE_KEY = /* @__PURE__ */ Symbol.for("cencori.observe.state");
186
+ var CONTEXT_KEY = /* @__PURE__ */ Symbol.for("cencori.observe.context");
187
+ var globals = globalThis;
188
+ function serviceName(options) {
189
+ return options.serviceName ?? process.env.CENCORI_SERVICE_NAME ?? process.env.OTEL_SERVICE_NAME ?? process.env.npm_package_name ?? "app";
190
+ }
191
+ var ContextSpanProcessor = class {
192
+ onStart(span, parent) {
193
+ const values = parent.getValue(CONTEXT_KEY);
194
+ if (!values) return;
195
+ if (values.userId) span.setAttribute("user.id", values.userId);
196
+ if (values.sessionId) span.setAttribute("session.id", values.sessionId);
197
+ if (values.tags?.length) span.setAttribute("tag.tags", values.tags);
198
+ if (values.metadata && Object.keys(values.metadata).length) span.setAttribute("metadata", JSON.stringify(values.metadata));
199
+ }
200
+ onEnd(_span) {
201
+ }
202
+ async forceFlush() {
203
+ }
204
+ async shutdown() {
205
+ }
206
+ };
207
+ var localRequire = (0, import_node_module.createRequire)(typeof __filename === "string" ? __filename : import_meta.url);
208
+ var appRequire = () => (0, import_node_module.createRequire)(import_node_path.default.join(process.cwd(), "noop.js"));
209
+ function loadInstrumentation(pkg, exportName, captureContent) {
210
+ for (const load of [() => localRequire(pkg), () => appRequire()(pkg)]) {
211
+ try {
212
+ const Instrumentation = load()[exportName];
213
+ if (Instrumentation) return new Instrumentation({ traceConfig: contentConfig(captureContent) });
214
+ } catch {
215
+ }
216
+ }
217
+ return null;
218
+ }
219
+ var exporterOptions = ({ apiKey, baseUrl, debug, serviceName: serviceName2, captureContent }) => ({ apiKey, baseUrl, debug, serviceName: serviceName2, captureContent });
220
+ var contentConfig = (captureContent) => captureContent ? void 0 : { hideInputs: true, hideOutputs: true, hideInputMessages: true, hideOutputMessages: true };
221
+ var clientClass = (value) => typeof value === "function" ? value : value && typeof value === "object" ? value.constructor : void 0;
222
+ function start(options) {
223
+ if (typeof window !== "undefined") return null;
224
+ const existing = globals[STATE_KEY];
225
+ if (existing) return existing;
226
+ const exporter = new CencoriSpanExporter(exporterOptions(options));
227
+ const provider = new import_sdk_trace_base.BasicTracerProvider({
228
+ resource: (0, import_resources.resourceFromAttributes)({ "service.name": serviceName(options), "telemetry.sdk.name": "cencori-observe" }),
229
+ spanProcessors: [new ContextSpanProcessor(), new import_sdk_trace_base.BatchSpanProcessor(exporter)]
230
+ });
231
+ import_api2.context.setGlobalContextManager(new import_context_async_hooks.AsyncLocalStorageContextManager().enable());
232
+ const ownsGlobal = import_api2.trace.setGlobalTracerProvider(provider);
233
+ if (!ownsGlobal) {
234
+ console.warn(
235
+ "[cencori] observe: another OpenTelemetry setup is already running. AI calls are still sent to Cencori; to send your other spans too, add `new BatchSpanProcessor(new CencoriSpanExporter())` to that setup."
236
+ );
237
+ }
238
+ const captureContent = options.captureContent ?? !/^(0|false|off)$/i.test(process.env.CENCORI_OBSERVE_CONTENT ?? "");
239
+ const instrumentations = {
240
+ openai: loadInstrumentation("@arizeai/openinference-instrumentation-openai", "OpenAIInstrumentation", captureContent),
241
+ anthropic: loadInstrumentation("@arizeai/openinference-instrumentation-anthropic", "AnthropicInstrumentation", captureContent),
242
+ langchain: loadInstrumentation("@arizeai/openinference-instrumentation-langchain", "LangChainInstrumentation", captureContent)
243
+ };
244
+ for (const instrumentation of Object.values(instrumentations)) instrumentation?.setTracerProvider(provider);
245
+ process.once("beforeExit", () => {
246
+ void provider.forceFlush();
247
+ });
248
+ const state = { provider, exporter, instrumentations, ownsGlobal };
249
+ globals[STATE_KEY] = state;
250
+ return state;
251
+ }
252
+ function observe(options = {}) {
253
+ if (/^(0|false|off)$/i.test(process.env.CENCORI_OBSERVE ?? "")) return false;
254
+ const state = start(options);
255
+ if (!state) return false;
256
+ state.exporter.configure(exporterOptions(options));
257
+ const openai = clientClass(options.openai);
258
+ if (openai) state.instrumentations.openai?.manuallyInstrument({ OpenAI: openai });
259
+ const anthropic = clientClass(options.anthropic);
260
+ if (anthropic) state.instrumentations.anthropic?.manuallyInstrument(anthropic);
261
+ if (options.langchain) {
262
+ if (!state.instrumentations.langchain) {
263
+ console.warn("[cencori] observe: install @arizeai/openinference-instrumentation-langchain to record LangChain chains and tools.");
264
+ } else {
265
+ state.instrumentations.langchain.manuallyInstrument(options.langchain);
266
+ }
267
+ }
268
+ return true;
269
+ }
270
+ function withContext(values, fn) {
271
+ const current = import_api2.context.active().getValue(CONTEXT_KEY);
272
+ const merged = {
273
+ ...current,
274
+ ...values,
275
+ tags: [.../* @__PURE__ */ new Set([...current?.tags ?? [], ...values.tags ?? []])],
276
+ metadata: { ...current?.metadata, ...values.metadata }
277
+ };
278
+ return import_api2.context.with(import_api2.context.active().setValue(CONTEXT_KEY, merged), fn);
279
+ }
280
+ function trace(name, fn, options = {}) {
281
+ const tracer = (globals[STATE_KEY]?.provider ?? import_api2.trace.getTracerProvider()).getTracer("cencori");
282
+ const text = (value) => typeof value === "string" ? value : JSON.stringify(value);
283
+ return tracer.startActiveSpan(name, {
284
+ attributes: {
285
+ "openinference.span.kind": (options.type ?? "chain").toUpperCase(),
286
+ ...options.input !== void 0 ? { "input.value": text(options.input) } : {}
287
+ }
288
+ }, (span) => {
289
+ const fail = (error) => {
290
+ span.recordException(error);
291
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR, message: error?.message });
292
+ span.end();
293
+ throw error;
294
+ };
295
+ const succeed = (result) => {
296
+ if (result !== void 0) {
297
+ try {
298
+ span.setAttribute("output.value", text(result));
299
+ } catch {
300
+ }
301
+ }
302
+ span.end();
303
+ };
304
+ try {
305
+ const result = fn(span);
306
+ if (result && typeof result.then === "function") {
307
+ return result.then((value) => {
308
+ succeed(value);
309
+ return value;
310
+ }, fail);
311
+ }
312
+ succeed(result);
313
+ return result;
314
+ } catch (error) {
315
+ return fail(error);
316
+ }
317
+ });
318
+ }
319
+ async function flush() {
320
+ await globals[STATE_KEY]?.provider.forceFlush();
321
+ }
322
+ async function shutdown() {
323
+ const state = globals[STATE_KEY];
324
+ if (!state) return;
325
+ await state.provider.shutdown();
326
+ globals[STATE_KEY] = void 0;
327
+ }
328
+ observe();
329
+ // Annotate the CommonJS export names for ESM import in node:
330
+ 0 && (module.exports = {
331
+ CencoriSpanExporter,
332
+ flush,
333
+ observe,
334
+ shutdown,
335
+ toOtlpJson,
336
+ trace,
337
+ withContext
338
+ });
339
+ //# sourceMappingURL=index.js.map