@latitude-data/telemetry 2.0.4 → 3.0.0-alpha.1

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,157 @@
1
+ # GNU LESSER GENERAL PUBLIC LICENSE
2
+
3
+ Version 3, 29 June 2007
4
+
5
+ Copyright (C) 2007 Free Software Foundation, Inc.
6
+ <https://fsf.org/>
7
+
8
+ Everyone is permitted to copy and distribute verbatim copies of this
9
+ license document, but changing it is not allowed.
10
+
11
+ This version of the GNU Lesser General Public License incorporates the
12
+ terms and conditions of version 3 of the GNU General Public License,
13
+ supplemented by the additional permissions listed below.
14
+
15
+ ## 0. Additional Definitions.
16
+
17
+ As used herein, "this License" refers to version 3 of the GNU Lesser
18
+ General Public License, and the "GNU GPL" refers to version 3 of the
19
+ GNU General Public License.
20
+
21
+ "The Library" refers to a covered work governed by this License, other
22
+ than an Application or a Combined Work as defined below.
23
+
24
+ An "Application" is any work that makes use of an interface provided
25
+ by the Library, but which is not otherwise based on the Library.
26
+ Defining a subclass of a class defined by the Library is deemed a mode
27
+ of using an interface provided by the Library.
28
+
29
+ A "Combined Work" is a work produced by combining or linking an
30
+ Application with the Library. The particular version of the Library
31
+ with which the Combined Work was made is also called the "Linked
32
+ Version".
33
+
34
+ The "Minimal Corresponding Source" for a Combined Work means the
35
+ Corresponding Source for the Combined Work, excluding any source code
36
+ for portions of the Combined Work that, considered in isolation, are
37
+ based on the Application, and not on the Linked Version.
38
+
39
+ The "Corresponding Application Code" for a Combined Work means the
40
+ object code and/or source code for the Application, including any data
41
+ and utility programs needed for reproducing the Combined Work from the
42
+ Application, but excluding the System Libraries of the Combined Work.
43
+
44
+ ## 1. Exception to Section 3 of the GNU GPL.
45
+
46
+ You may convey a covered work under sections 3 and 4 of this License
47
+ without being bound by section 3 of the GNU GPL.
48
+
49
+ ## 2. Conveying Modified Versions.
50
+
51
+ If you modify a copy of the Library, and, in your modifications, a
52
+ facility refers to a function or data to be supplied by an Application
53
+ that uses the facility (other than as an argument passed when the
54
+ facility is invoked), then you may convey a copy of the modified
55
+ version:
56
+
57
+ - a) under this License, provided that you make a good faith effort
58
+ to ensure that, in the event an Application does not supply the
59
+ function or data, the facility still operates, and performs
60
+ whatever part of its purpose remains meaningful, or
61
+ - b) under the GNU GPL, with none of the additional permissions of
62
+ this License applicable to that copy.
63
+
64
+ ## 3. Object Code Incorporating Material from Library Header Files.
65
+
66
+ The object code form of an Application may incorporate material from a
67
+ header file that is part of the Library. You may convey such object
68
+ code under terms of your choice, provided that, if the incorporated
69
+ material is not limited to numerical parameters, data structure
70
+ layouts and accessors, or small macros, inline functions and templates
71
+ (ten or fewer lines in length), you do both of the following:
72
+
73
+ - a) Give prominent notice with each copy of the object code that
74
+ the Library is used in it and that the Library and its use are
75
+ covered by this License.
76
+ - b) Accompany the object code with a copy of the GNU GPL and this
77
+ license document.
78
+
79
+ ## 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that, taken
82
+ together, effectively do not restrict modification of the portions of
83
+ the Library contained in the Combined Work and reverse engineering for
84
+ debugging such modifications, if you also do each of the following:
85
+
86
+ - a) Give prominent notice with each copy of the Combined Work that
87
+ the Library is used in it and that the Library and its use are
88
+ covered by this License.
89
+ - b) Accompany the Combined Work with a copy of the GNU GPL and this
90
+ license document.
91
+ - c) For a Combined Work that displays copyright notices during
92
+ execution, include the copyright notice for the Library among
93
+ these notices, as well as a reference directing the user to the
94
+ copies of the GNU GPL and this license document.
95
+ - d) Do one of the following:
96
+ - 0) Convey the Minimal Corresponding Source under the terms of
97
+ this License, and the Corresponding Application Code in a form
98
+ suitable for, and under terms that permit, the user to
99
+ recombine or relink the Application with a modified version of
100
+ the Linked Version to produce a modified Combined Work, in the
101
+ manner specified by section 6 of the GNU GPL for conveying
102
+ Corresponding Source.
103
+ - 1) Use a suitable shared library mechanism for linking with
104
+ the Library. A suitable mechanism is one that (a) uses at run
105
+ time a copy of the Library already present on the user's
106
+ computer system, and (b) will operate properly with a modified
107
+ version of the Library that is interface-compatible with the
108
+ Linked Version.
109
+ - e) Provide Installation Information, but only if you would
110
+ otherwise be required to provide such information under section 6
111
+ of the GNU GPL, and only to the extent that such information is
112
+ necessary to install and execute a modified version of the
113
+ Combined Work produced by recombining or relinking the Application
114
+ with a modified version of the Linked Version. (If you use option
115
+ 4d0, the Installation Information must accompany the Minimal
116
+ Corresponding Source and Corresponding Application Code. If you
117
+ use option 4d1, you must provide the Installation Information in
118
+ the manner specified by section 6 of the GNU GPL for conveying
119
+ Corresponding Source.)
120
+
121
+ ## 5. Combined Libraries.
122
+
123
+ You may place library facilities that are a work based on the Library
124
+ side by side in a single library together with other library
125
+ facilities that are not Applications and are not covered by this
126
+ License, and convey such a combined library under terms of your
127
+ choice, if you do both of the following:
128
+
129
+ - a) Accompany the combined library with a copy of the same work
130
+ based on the Library, uncombined with any other library
131
+ facilities, conveyed under the terms of this License.
132
+ - b) Give prominent notice with the combined library that part of it
133
+ is a work based on the Library, and explaining where to find the
134
+ accompanying uncombined form of the same work.
135
+
136
+ ## 6. Revised Versions of the GNU Lesser General Public License.
137
+
138
+ The Free Software Foundation may publish revised and/or new versions
139
+ of the GNU Lesser General Public License from time to time. Such new
140
+ versions will be similar in spirit to the present version, but may
141
+ differ in detail to address new problems or concerns.
142
+
143
+ Each version is given a distinguishing version number. If the Library
144
+ as you received it specifies that a certain numbered version of the
145
+ GNU Lesser General Public License "or any later version" applies to
146
+ it, you have the option of following the terms and conditions either
147
+ of that published version or of any later version published by the
148
+ Free Software Foundation. If the Library as you received it does not
149
+ specify a version number of the GNU Lesser General Public License, you
150
+ may choose any version of the GNU Lesser General Public License ever
151
+ published by the Free Software Foundation.
152
+
153
+ If the Library as you received it specifies that a proxy can decide
154
+ whether future versions of the GNU Lesser General Public License shall
155
+ apply, that proxy's public statement of acceptance of any version is
156
+ permanent authorization for you to choose that version for the
157
+ Library.
package/README.md CHANGED
@@ -1,52 +1,476 @@
1
- # Latitude Telemetry for Typescript & Javascript
1
+ # Latitude Telemetry for TypeScript
2
+
3
+ Instrument your AI application and send traces to [Latitude](https://latitude.so). Built on [OpenTelemetry](https://opentelemetry.io/).
4
+
5
+ ## Installation
2
6
 
3
7
  ```sh
4
8
  npm install @latitude-data/telemetry
5
9
  ```
6
10
 
7
- Requires Node.js `20` or higher.
11
+ ## Quick Start
12
+
13
+ ### Bootstrap (Recommended)
14
+
15
+ The fastest way to start tracing your LLM calls. One function sets up everything:
16
+
17
+ ```typescript
18
+ import { initLatitude } from "@latitude-data/telemetry";
19
+
20
+ const latitude = initLatitude({
21
+ apiKey: process.env.LATITUDE_API_KEY!,
22
+ projectSlug: process.env.LATITUDE_PROJECT_SLUG!,
23
+ instrumentations: ["openai"], // Auto-instrument OpenAI, Anthropic, etc.
24
+ });
25
+
26
+ // Optionally wait for instrumentations to be ready
27
+ await latitude.ready;
28
+
29
+ // Your LLM calls will now be traced and sent to Latitude
30
+ const response = await openai.chat.completions.create({
31
+ model: "gpt-4",
32
+ messages: [{ role: "user", content: "Hello" }],
33
+ });
34
+
35
+ await latitude.shutdown();
36
+ ```
37
+
38
+ **What this does:**
39
+
40
+ - Creates a complete OpenTelemetry setup
41
+ - Registers LLM auto-instrumentation (OpenAI, Anthropic, etc.) **asynchronously in the background**
42
+ - Configures the Latitude span processor and exporter
43
+ - Sets up async context propagation (for passing context through async operations)
44
+
45
+ **Key point about async instrumentations:**
46
+
47
+ `initLatitude` returns **immediately** — no top-level await needed. Instrumentation registration happens in the background. This avoids top-level await issues in CommonJS environments while still supporting ESM.
48
+
49
+ - **Fire-and-forget**: Start using your LLM clients right away. Early spans will be captured once instrumentations finish registering.
50
+ - **Optional `await latitude.ready`**: If you want to ensure instrumentations are fully registered before making LLM calls, await the `ready` promise.
51
+
52
+ **When to use this:** Most applications should start here. It's the simplest path to get LLM observability into Latitude.
53
+
54
+ **When you might need the advanced setup:**
55
+
56
+ - You already have OpenTelemetry configured for other backends (Datadog, Sentry, Jaeger)
57
+ - You need custom span processing, sampling, or filtering
58
+ - You want multiple observability backends receiving the same spans
59
+
60
+ ### Existing OpenTelemetry Setup (Advanced)
61
+
62
+ If your app already uses OpenTelemetry, add Latitude alongside your existing setup:
63
+
64
+ ```typescript
65
+ import { NodeSDK } from "@opentelemetry/sdk-node";
66
+ import {
67
+ LatitudeSpanProcessor,
68
+ registerLatitudeInstrumentations,
69
+ } from "@latitude-data/telemetry";
70
+
71
+ const sdk = new NodeSDK({
72
+ spanProcessors: [
73
+ existingProcessor, // Your existing processor
74
+ new LatitudeSpanProcessor(
75
+ process.env.LATITUDE_API_KEY!,
76
+ process.env.LATITUDE_PROJECT_SLUG!,
77
+ ),
78
+ ],
79
+ });
80
+
81
+ sdk.start();
82
+
83
+ // Enable LLM auto-instrumentation
84
+ await registerLatitudeInstrumentations({
85
+ instrumentations: ["openai"],
86
+ tracerProvider: sdk.getTracerProvider(),
87
+ });
88
+
89
+ // Your LLM calls will now be traced and sent to Latitude
90
+ const response = await openai.chat.completions.create({
91
+ model: "gpt-4",
92
+ messages: [{ role: "user", content: "Hello" }],
93
+ });
94
+ ```
95
+
96
+ ### Why OpenTelemetry?
97
+
98
+ Latitude Telemetry is built entirely on OpenTelemetry standards. When you're ready to add other observability tools (Datadog, Sentry, Jaeger, etc.), you can use them alongside Latitude without conflicts:
99
+
100
+ - **Standard span processors** — `LatitudeSpanProcessor` works with any `NodeSDK` or `NodeTracerProvider`
101
+ - **Smart filtering** — Only LLM-relevant spans are exported to Latitude (spans with `gen_ai.*`, `llm.*`, `openinference.*`, or `ai.*` attributes, plus known LLM instrumentation scopes)
102
+ - **Compatible with existing instrumentations** — Works alongside HTTP, DB, and other OTel instrumentations
103
+ - **No vendor lock-in** — Standard OTLP export, no proprietary wire format
104
+
105
+ ## Using `capture()` for Context and Boundaries
106
+
107
+ The SDK automatically traces LLM calls when you use auto-instrumentation. However, you may want to add additional context (user ID, session ID, tags, or metadata) to group related spans together.
108
+
109
+ ### What `capture()` Does
110
+
111
+ `capture()` wraps your code to attach Latitude context to all LLM spans created inside the callback:
112
+
113
+ - Adds attributes like `user.id`, `session.id`, `latitude.tags`, and `latitude.metadata` to every span
114
+ - Creates a named boundary for grouping related traces
115
+ - Uses OpenTelemetry's native `context.with()` for reliable async propagation
116
+
117
+ ### When to Use It
118
+
119
+ You don't need `capture()` to get started—auto-instrumentation handles LLM calls automatically. Use `capture()` when you want to:
120
+
121
+ - **Group traces by user or session** — Track all LLM calls from a specific user or session
122
+ - **Add business context** — Tag traces with deployment environment, feature flags, or request IDs
123
+ - **Mark agent boundaries** — Wrap an entire agent run or conversation turn with a name and metadata
124
+ - **Filter and analyze** — Use tags and metadata to filter traces in the Latitude
125
+
126
+ ### Example
127
+
128
+ ```typescript
129
+ import { initLatitude, capture } from "@latitude-data/telemetry";
130
+
131
+ const latitude = initLatitude({
132
+ apiKey: process.env.LATITUDE_API_KEY!,
133
+ projectSlug: process.env.LATITUDE_PROJECT_SLUG!,
134
+ instrumentations: ["openai"],
135
+ });
136
+
137
+ // Optional: wait for instrumentations before starting
138
+ await latitude.ready;
139
+
140
+ // Wrap a request or agent run to add context
141
+ await capture(
142
+ "handle-user-request",
143
+ async () => {
144
+ const result = await agent.process(userMessage);
145
+ return result;
146
+ },
147
+ {
148
+ userId: "user_123",
149
+ sessionId: "session_abc",
150
+ tags: ["production", "v2-agent"],
151
+ metadata: { requestId: "req-xyz", featureFlag: "new-prompt" },
152
+ },
153
+ );
154
+
155
+ await latitude.shutdown();
156
+ ```
157
+
158
+ **Important:** `capture()` does not create spans—it only attaches context to spans created by auto-instrumentation. Use one `capture()` call at the request or agent boundary. You can nest calls for granular context; child spans inherit from parent context with local overrides.
159
+
160
+ ## Key Concepts
161
+
162
+ - **`initLatitude()`** — The primary way to use Latitude. Bootstraps a complete OpenTelemetry setup with LLM auto-instrumentation and the Latitude exporter. Best for most applications.
163
+ - **`LatitudeSpanProcessor`** — For advanced use cases where you already have an OpenTelemetry setup. Exports spans to Latitude alongside your existing observability stack.
164
+ - **`registerLatitudeInstrumentations()`** — Registers LLM auto-instrumentations (OpenAI, Anthropic, etc.) when using the advanced setup with your own provider.
165
+ - **`capture()`** — Optional. Wraps your code to attach Latitude context (tags, userId, sessionId, metadata) to all spans created inside the callback. Use this when you want to group traces by user, session, or add business context.
166
+
167
+ **Important:** Auto-instrumentation traces LLM calls without `capture()`. Use `capture()` only when you need to add context or mark boundaries. Wrap the request, job, or agent entrypoint once—you don't need to wrap every internal step.
168
+
169
+ ## Public API
170
+
171
+ ```typescript
172
+ import {
173
+ initLatitude,
174
+ LatitudeSpanProcessor,
175
+ capture,
176
+ registerLatitudeInstrumentations,
177
+ } from "@latitude-data/telemetry";
178
+ ```
179
+
180
+ ### `initLatitude(options)`
181
+
182
+ The primary entry point. Bootstraps a complete OpenTelemetry setup with LLM instrumentations and Latitude export.
183
+
184
+ ```typescript
185
+ type InitLatitudeOptions = {
186
+ apiKey: string;
187
+ projectSlug: string;
188
+ instrumentations?: InstrumentationType[]; // ["openai", "anthropic", etc.]
189
+ serviceName?: string;
190
+ disableBatch?: boolean;
191
+ disableSmartFilter?: boolean;
192
+ shouldExportSpan?: (span: ReadableSpan) => boolean;
193
+ blockedInstrumentationScopes?: string[];
194
+ disableRedact?: boolean;
195
+ redact?: RedactSpanProcessorOptions;
196
+ exporter?: SpanExporter;
197
+ };
198
+
199
+ function initLatitude(options: InitLatitudeOptions): {
200
+ provider: NodeTracerProvider; // Access to underlying provider for advanced use
201
+ ready: Promise<void>; // Resolves when instrumentations are registered
202
+ flush(): Promise<void>;
203
+ shutdown(): Promise<void>;
204
+ };
205
+ ```
206
+
207
+ ### `LatitudeSpanProcessor`
208
+
209
+ Span processor for shared-provider setups. Reads Latitude context from OTel context and stamps attributes onto spans.
210
+
211
+ ```typescript
212
+ class LatitudeSpanProcessor implements SpanProcessor {
213
+ constructor(
214
+ apiKey: string,
215
+ projectSlug: string,
216
+ options?: LatitudeSpanProcessorOptions,
217
+ );
218
+ }
219
+
220
+ type LatitudeSpanProcessorOptions = {
221
+ disableBatch?: boolean;
222
+ disableSmartFilter?: boolean;
223
+ shouldExportSpan?: (span: ReadableSpan) => boolean;
224
+ blockedInstrumentationScopes?: string[];
225
+ disableRedact?: boolean;
226
+ redact?: RedactSpanProcessorOptions;
227
+ exporter?: SpanExporter;
228
+ };
229
+ ```
230
+
231
+ ### `capture(name, fn, options?)`
232
+
233
+ Wraps a function to attach Latitude context to all spans created inside. Uses OpenTelemetry's native `context.with()` for scoping.
234
+
235
+ ```typescript
236
+ type ContextOptions = {
237
+ name?: string;
238
+ userId?: string;
239
+ sessionId?: string;
240
+ tags?: string[];
241
+ metadata?: Record<string, unknown>;
242
+ };
243
+
244
+ function capture<T>(
245
+ name: string,
246
+ fn: () => T | Promise<T>,
247
+ options?: ContextOptions,
248
+ ): T | Promise<T>;
249
+ ```
250
+
251
+ **Nested `capture()` behavior:**
252
+
253
+ - `userId`: last-write-wins
254
+ - `sessionId`: last-write-wins
255
+ - `metadata`: shallow merge
256
+ - `tags`: append and dedupe while preserving order
257
+
258
+ ### `registerLatitudeInstrumentations(options)`
259
+
260
+ Registers patch-based AI SDK instrumentations against a specific tracer provider.
261
+
262
+ ```typescript
263
+ type InstrumentationType =
264
+ | "openai"
265
+ | "anthropic"
266
+ | "bedrock"
267
+ | "cohere"
268
+ | "langchain"
269
+ | "llamaindex"
270
+ | "togetherai"
271
+ | "vertexai"
272
+ | "aiplatform";
273
+
274
+ function registerLatitudeInstrumentations(options: {
275
+ instrumentations: InstrumentationType[];
276
+ tracerProvider: TracerProvider;
277
+ instrumentationModules?: Partial<Record<InstrumentationType, unknown>>;
278
+ }): Promise<void>;
279
+ ```
280
+
281
+ ## Vendor-Specific Integration Guides
8
282
 
9
- Go to the [documentation](https://docs.latitude.so/guides/sdk/typescript) to learn more.
283
+ For users with existing observability infrastructure.
10
284
 
11
- ## Usage
285
+ ### With Datadog
286
+
287
+ Use Datadog's OTel `TracerProvider` with `LatitudeSpanProcessor`:
12
288
 
13
289
  ```typescript
14
- import { LatitudeTelemetry } from '@latitude-data/telemetry'
15
- import { Latitude } from '@latitude-data/sdk'
16
- import { OpenAI } from 'openai'
290
+ import tracer from "dd-trace";
291
+ import { LatitudeSpanProcessor } from "@latitude-data/telemetry";
292
+
293
+ const ddTracer = tracer.init({ service: "my-app", env: "production" });
294
+ const provider = new ddTracer.TracerProvider();
295
+
296
+ provider.addSpanProcessor(
297
+ new LatitudeSpanProcessor(
298
+ process.env.LATITUDE_API_KEY!,
299
+ process.env.LATITUDE_PROJECT_SLUG!,
300
+ ),
301
+ );
302
+
303
+ provider.register();
304
+
305
+ // LLM calls are now traced and sent to both Datadog and Latitude
306
+ ```
307
+
308
+ **Adding context:** Use `capture()` if you want to add user IDs, session IDs, or tags to your traces (see [Using `capture()` for Context and Boundaries](#using-capture-for-context-and-boundaries)).
309
+
310
+ ### With Sentry
311
+
312
+ Use Sentry's custom OpenTelemetry setup with `skipOpenTelemetrySetup: true`:
17
313
 
18
- const telemetry = new LatitudeTelemetry('my-api-key', {
19
- instrumentations: {
20
- latitude: Latitude,
21
- openai: OpenAI,
314
+ ```typescript
315
+ import * as Sentry from "@sentry/node";
316
+ import {
317
+ SentrySpanProcessor,
318
+ SentrySampler,
319
+ SentryPropagator,
320
+ } from "@sentry/opentelemetry";
321
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
322
+ import {
323
+ LatitudeSpanProcessor,
324
+ registerLatitudeInstrumentations,
325
+ } from "@latitude-data/telemetry";
326
+
327
+ // Initialize Sentry with custom OTel setup flag
328
+ const sentryClient = Sentry.init({
329
+ dsn: process.env.SENTRY_DSN,
330
+ skipOpenTelemetrySetup: true,
331
+ tracesSampleRate: 1.0,
332
+ });
333
+
334
+ // Create a shared provider with both Sentry and Latitude processors
335
+ const provider = new NodeTracerProvider({
336
+ sampler: sentryClient ? new SentrySampler(sentryClient) : undefined,
337
+ spanProcessors: [
338
+ new SentrySpanProcessor(), // Send spans to Sentry
339
+ new LatitudeSpanProcessor(
340
+ process.env.LATITUDE_API_KEY!,
341
+ process.env.LATITUDE_PROJECT_SLUG!,
342
+ ), // Send spans to Latitude
343
+ ],
344
+ });
345
+
346
+ // Register with Sentry's propagator and context manager
347
+ provider.register({
348
+ propagator: new SentryPropagator(),
349
+ contextManager: new Sentry.SentryContextManager(),
350
+ });
351
+
352
+ // Add LLM instrumentations
353
+ await registerLatitudeInstrumentations({
354
+ instrumentations: ["openai"],
355
+ tracerProvider: provider,
356
+ });
357
+
358
+ // Validate the setup
359
+ Sentry.validateOpenTelemetrySetup();
360
+
361
+ // LLM calls are now traced and sent to both Sentry and Latitude
362
+ ```
363
+
364
+ **Adding context:** Use `capture()` if you want to add user IDs, session IDs, or tags to your traces (see [Using `capture()` for Context and Boundaries](#using-capture-for-context-and-boundaries)).
365
+
366
+ **Required Sentry packages:** `@sentry/node`, `@sentry/opentelemetry`
367
+
368
+ **Note:** See [Sentry's custom OTel setup documentation](https://docs.sentry.io/platforms/javascript/guides/node/opentelemetry/custom-setup/) for version-specific details.
369
+
370
+ ## Supported AI Providers
371
+
372
+ | Identifier | Package |
373
+ | -------------- | --------------------------------- |
374
+ | `"openai"` | `openai` |
375
+ | `"anthropic"` | `@anthropic-ai/sdk` |
376
+ | `"bedrock"` | `@aws-sdk/client-bedrock-runtime` |
377
+ | `"cohere"` | `cohere-ai` |
378
+ | `"langchain"` | `langchain` |
379
+ | `"llamaindex"` | `llamaindex` |
380
+ | `"togetherai"` | `together-ai` |
381
+ | `"vertexai"` | `@google-cloud/vertexai` |
382
+ | `"aiplatform"` | `@google-cloud/aiplatform` |
383
+
384
+ ## Context Options
385
+
386
+ `capture()` accepts these context options:
387
+
388
+ | Option | Type | OTel Attribute | Description |
389
+ | ----------- | ------------------------- | ----------------------- | ---------------------------- |
390
+ | `name` | `string` | `latitude.capture.name` | Name for the capture context |
391
+ | `tags` | `string[]` | `latitude.tags` | Tags for filtering traces |
392
+ | `metadata` | `Record<string, unknown>` | `latitude.metadata` | Arbitrary key-value metadata |
393
+ | `sessionId` | `string` | `session.id` | Group traces by session |
394
+ | `userId` | `string` | `user.id` | Associate traces with a user |
395
+
396
+ ## Configuration Options
397
+
398
+ ### Smart Filtering
399
+
400
+ By default, only LLM-relevant spans are exported:
401
+
402
+ ```typescript
403
+ new LatitudeSpanProcessor(apiKey, projectSlug, {
404
+ disableSmartFilter: true, // Export all spans
405
+ });
406
+ ```
407
+
408
+ ### Redaction
409
+
410
+ PII redaction is enabled by default for security-sensitive attributes only:
411
+
412
+ **Redacted by default:**
413
+
414
+ - HTTP authorization headers
415
+ - HTTP cookies
416
+ - HTTP API key headers (`x-api-key`)
417
+ - Database statements
418
+
419
+ ```typescript
420
+ new LatitudeSpanProcessor(apiKey, projectSlug, {
421
+ disableRedact: true, // Disable all redaction
422
+ redact: {
423
+ attributes: [/^password$/i, /secret/i], // Add custom patterns
424
+ mask: (attr, value) => "[REDACTED]",
22
425
  },
23
- })
426
+ });
427
+ ```
24
428
 
25
- // Automatically instrumented
26
- const sdk = new Latitude('my-api-key', {
27
- projectId: 'my-project-id',
28
- versionUuid: 'my-version-uuid',
29
- })
429
+ ### Custom Filtering
30
430
 
31
- // Automatically instrumented
32
- const openai = new OpenAI({
33
- apiKey: 'my-api-key',
34
- })
431
+ ```typescript
432
+ new LatitudeSpanProcessor(apiKey, projectSlug, {
433
+ shouldExportSpan: (span) => span.attributes["custom"] === true,
434
+ blockedInstrumentationScopes: ["opentelemetry.instrumentation.fs"],
435
+ });
35
436
  ```
36
437
 
37
- Find more [examples](https://docs.latitude.so/examples/sdk).
438
+ ## Environment Variables
439
+
440
+ | Variable | Default | Description |
441
+ | ------------------------ | ------------------------------------------------------------------- | ---------------------- |
442
+ | `LATITUDE_TELEMETRY_URL` | `http://localhost:3002` (dev) / `https://ingest.latitude.so` (prod) | OTLP exporter endpoint |
443
+
444
+ ## Troubleshooting
445
+
446
+ ### Spans not appearing in Latitude
38
447
 
39
- ## Development
448
+ 1. **Check API key and project slug** — Must be non-empty strings
449
+ 2. **Verify instrumentations are registered** — Use `await registerLatitudeInstrumentations()`
450
+ 3. **Flush before exit** — Call `await latitude.flush()` or `await provider.forceFlush()`
451
+ 4. **Check smart filter** — Only LLM spans are exported by default. Use `disableSmartFilter: true` to export all spans
452
+ 5. **Ensure `capture()` wraps the code that creates spans** — `capture()` itself doesn't create spans; it only attaches context to spans created by instrumentations
40
453
 
41
- Requires npm `0.5.10` or higher.
454
+ ### No spans created inside `capture()`
455
+
456
+ `capture()` only attaches context. You need:
457
+
458
+ 1. An active instrumentation (e.g., `@traceloop/instrumentation-openai`)
459
+ 2. That instrumentation to create spans for the operations inside your callback
460
+
461
+ ### Context not propagating
462
+
463
+ Ensure you have a functioning OpenTelemetry context manager registered:
464
+
465
+ ```typescript
466
+ import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
467
+ import { context } from "@opentelemetry/api";
468
+
469
+ context.setGlobalContextManager(new AsyncLocalStorageContextManager());
470
+ ```
42
471
 
43
- - Install dependencies: `npm install`
44
- - Add [dev] dependencies: `npm install <package> [--save-dev]`
45
- - Run linter: `npm run lint`
46
- - Run formatter: `npm run format`
47
- - Run tests: `npm run test`
48
- - Build package: `npm run build`
472
+ `initLatitude()` does this automatically. For shared-provider setups, your app's existing OTel setup should already have this.
49
473
 
50
474
  ## License
51
475
 
52
- The SDK is licensed under the [MIT License](https://opensource.org/licenses/MIT) - read the [LICENSE](/LICENSE) file for details.
476
+ MIT