raindrop-ai 0.0.69 → 0.0.70

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/dist/index.d.mts CHANGED
@@ -1,5 +1,514 @@
1
- export { A as AiTrackEvent, a as Attachment, b as AttachmentType, B as BeginInteractionOptions, F as FinishInteractionOptions, c as IdentifyEvent, I as Interaction, M as MAX_INGEST_SIZE_BYTES, P as PartialAiTrackEvent, R as Raindrop, d as SignalEvent, e as SpanParams, f as ToolParams, g as TraceContext, T as Tracer, W as WorkflowParams, R as default } from './index-BnPIaY-L.mjs';
2
- import '@traceloop/node-server-sdk';
3
- import '@opentelemetry/api';
4
- import 'zod';
5
- import '@opentelemetry/resources';
1
+ import { Span } from '@opentelemetry/api';
2
+ import { z } from 'zod';
3
+ import { SpanProcessorOptions } from '@traceloop/node-server-sdk';
4
+
5
+ /**
6
+ * Version-agnostic SpanProcessor interface.
7
+ *
8
+ * This interface avoids direct dependency on OTEL's Span and ReadableSpan types
9
+ * which can cause compatibility issues across minor OTEL versions. Using `any`
10
+ * allows the processor to work with any version of OTEL without type conflicts.
11
+ */
12
+ interface RaindropSpanProcessor {
13
+ forceFlush(): Promise<void>;
14
+ onStart(span: any, parentContext: any): void;
15
+ onEnd(span: any): void;
16
+ shutdown(): Promise<void>;
17
+ }
18
+ type BaseAttachment = {
19
+ attachment_id?: string;
20
+ name?: string;
21
+ value: string;
22
+ role: "input" | "output";
23
+ };
24
+ type CodeAttachment = BaseAttachment & {
25
+ type: "code";
26
+ language?: string;
27
+ };
28
+ type OtherAttachment = BaseAttachment & {
29
+ type: "text" | "image" | "iframe";
30
+ };
31
+ type Attachment = CodeAttachment | OtherAttachment;
32
+ /**
33
+ * Interface for tracking events.
34
+ *
35
+ * @param eventId - An optional event ID for the event.
36
+ * @param event - The name of the event.
37
+ * @param properties - An optional record of properties for the event.
38
+ * @param timestamp - An optional timestamp for the event.
39
+ * @param userId - The ID of the user. This is a required field.
40
+ * @param anonymousId - An optional anonymous ID for the user.
41
+ */
42
+ interface TrackEvent {
43
+ eventId?: string;
44
+ event: string;
45
+ properties?: Record<string, any>;
46
+ timestamp?: string;
47
+ userId: string;
48
+ }
49
+ type BasicSignal = {
50
+ eventId: string;
51
+ name: "thumbs_up" | "thumbs_down" | string;
52
+ sentiment?: "POSITIVE" | "NEGATIVE";
53
+ timestamp?: string;
54
+ properties?: {
55
+ [key: string]: any;
56
+ };
57
+ attachmentId?: string;
58
+ };
59
+ type DefaultSignal = BasicSignal & {
60
+ type?: "default";
61
+ };
62
+ type FeedbackSignal = BasicSignal & {
63
+ type: "feedback";
64
+ comment?: string;
65
+ };
66
+ type EditSignal = BasicSignal & {
67
+ type: "edit";
68
+ after?: string;
69
+ };
70
+ type SignalEvent = DefaultSignal | FeedbackSignal | EditSignal;
71
+ /**
72
+ * Interface for identifying events.
73
+ *
74
+ * @param userId - The ID of the user. This is a required field.
75
+ * @param traits - An optional object of traits for the user.
76
+ * @param anonymousId - An optional anonymous ID for the user.
77
+ * TODO: ensure at least one out of userId or anonymousId is present
78
+ */
79
+ interface IdentifyEvent {
80
+ userId: string;
81
+ traits?: object;
82
+ }
83
+ /**
84
+ * Type definition for AI tracking events.
85
+ * In addition to the properties of a TrackEvent, an AiTrackEvent may have a 'model' property.
86
+ * It must have at least one of 'input' or 'output' property.
87
+ *
88
+ * @property model - An optional model property for the even
89
+ * @property input - An optional input property for the event, required if output is not provided.
90
+ * @property output - An optional output property for the event, required if input is not provided.
91
+ */
92
+ type AiTrackEvent = Omit<TrackEvent, "type"> & {
93
+ model?: string;
94
+ convoId?: string;
95
+ attachments?: Attachment[];
96
+ } & ({
97
+ input: string;
98
+ output?: string;
99
+ } | {
100
+ input?: string;
101
+ output: string;
102
+ });
103
+ /**
104
+ * Type definition for partial AI tracking events used with trackAiPartial.
105
+ * Requires an eventId to correlate partial updates. All other fields are optional.
106
+ */
107
+ type PartialAiTrackEvent = Partial<AiTrackEvent> & {
108
+ eventId: string;
109
+ isPending?: boolean;
110
+ };
111
+ declare const AttachmentTypeSchema: z.ZodEnum<["code", "text", "image", "iframe"]>;
112
+ type AttachmentType = z.infer<typeof AttachmentTypeSchema>;
113
+ /**
114
+ * Configuration for initializing a trace interaction.
115
+ *
116
+ * This interface defines the context required to create and track an AI
117
+ * interaction through its lifecycle. It includes identifiers for the user
118
+ * and conversation, as well as input/output content and attachments.
119
+ *
120
+ * @property userId - Optional unique identifier for the user
121
+ * @property convoId - Optional unique identifier for the conversation
122
+ * @property eventId - Optional unique identifier for this specific interaction event
123
+ * @property input - Optional input text from the user
124
+ * @property attachments - Optional array of attachments associated with this interaction
125
+ * @property properties - Optional key-value pairs for additional custom metadata
126
+ */
127
+ interface TraceContext {
128
+ userId?: string;
129
+ convoId?: string;
130
+ eventId?: string;
131
+ input?: string;
132
+ event?: string;
133
+ attachments?: Attachment[];
134
+ properties?: Record<string, string>;
135
+ }
136
+ type BeginInteractionOptions = PartialAiTrackEvent & {
137
+ eventId: string;
138
+ };
139
+ type FinishInteractionOptions = Omit<PartialAiTrackEvent, "eventId"> & {
140
+ output: string;
141
+ eventId?: string;
142
+ };
143
+ /**
144
+ * Configuration for a traced workflow.
145
+ *
146
+ * Workflows represent higher-level operations that might contain multiple
147
+ * tasks. They help organize traces into logical units of work.
148
+ *
149
+ * @property name - Name of the workflow for identification in traces
150
+ * @property inputParameters - Optional array of input parameters for the workflow
151
+ * @property properties - Optional key-value pairs for additional metadata
152
+ */
153
+ interface WorkflowParams {
154
+ name: string;
155
+ inputParameters?: unknown[];
156
+ properties?: Record<string, string>;
157
+ }
158
+ /**
159
+ * Configuration for a traced task.
160
+ *
161
+ * Tasks represent individual operations within a workflow, such as an LLM call,
162
+ * a tool invocation, a retrieval operation, or internal processing.
163
+ *
164
+ * @property name - Name of the task for identification in traces
165
+ * @property kind - Category of the task (llm, tool, retrival, or internal)
166
+ * @property properties - Optional key-value pairs for additional metadata
167
+ * @property inputParameters - Optional array of input parameters for the task
168
+ * @property traceContent - Optional flag to control whether content is traced
169
+ * @property suppressTracing - Optional flag to suppress tracing for this task
170
+ */
171
+ interface SpanParams {
172
+ name: string;
173
+ properties?: Record<string, string>;
174
+ inputParameters?: unknown[];
175
+ traceContent?: boolean;
176
+ suppressTracing?: boolean;
177
+ }
178
+ /**
179
+ * Configuration for a traced tool.
180
+ *
181
+ * Tools represent external utilities or services that are invoked during an AI interaction,
182
+ * such as search engines, calculators, or other specialized functions.
183
+ *
184
+ * @property name - Name of the tool for identification in traces
185
+ * @property version - Optional version number of the tool
186
+ * @property properties - Optional key-value pairs for additional metadata
187
+ * @property inputParameters - Optional record of input parameters for the tool
188
+ * @property traceContent - Optional flag to control whether content is traced
189
+ * @property suppressTracing - Optional flag to suppress tracing for this tool invocation
190
+ */
191
+ interface ToolParams {
192
+ name: string;
193
+ version?: number;
194
+ properties?: Record<string, string>;
195
+ inputParameters?: Record<string, any>;
196
+ traceContent?: boolean;
197
+ suppressTracing?: boolean;
198
+ }
199
+ /**
200
+ * Represents an active tracing interaction for tracking and analyzing AI interactions.
201
+ *
202
+ * An Interaction is the core entity for tracing and instrumenting AI operations,
203
+ * allowing you to organize your code into workflows and tasks while capturing
204
+ * important metadata and contextual information. Use the methods on this interface
205
+ * to record your AI interaction's lifecycle from input to output, and to add
206
+ * structured context about the operation.
207
+ *
208
+ * Interactions are typically created using the `tracing.begin()` method and ended
209
+ * with the `end()` method. Between these calls, you can add properties, attachments,
210
+ * and nested traced operations.
211
+ *
212
+ * @example
213
+ * // Basic usage pattern
214
+ * const interaction = tracing.begin({
215
+ * userId: "user-123",
216
+ * convoId: "conversation-456"
217
+ * });
218
+ *
219
+ * // Set the user's input
220
+ * interaction.setInput("Tell me a joke about AI");
221
+ *
222
+ * // Add context properties
223
+ * interaction.setProperty("intent", "entertainment");
224
+ *
225
+ * // Run a traced workflow
226
+ * const result = await interaction.withWorkflow("joke_generation", async () => {
227
+ * // Run a traced task for the LLM call
228
+ * return await interaction.withTask({
229
+ * name: "llm_completion",
230
+ * kind: "llm"
231
+ * }, async () => {
232
+ * const completion = await openai.chat.completions.create({
233
+ * model: "gpt-4",
234
+ * messages: [{ role: "user", content: "Tell me a joke about AI" }]
235
+ * });
236
+ * return completion.choices[0].message.content;
237
+ * });
238
+ * });
239
+ *
240
+ * // End the interaction with the result
241
+ * interaction.end(result);
242
+ */
243
+ type Interaction = {
244
+ /**
245
+ * Creates a traced task that executes the provided function.
246
+ *
247
+ * @param params TaskParams object with task configuration
248
+ * @returns A span that can be used to record a task
249
+ */
250
+ withSpan<T>(params: SpanParams, fn: (...args: any[]) => Promise<T> | T, thisArg?: any, ...args: any[]): Promise<T>;
251
+ /**
252
+ * Creates a traced tool that executes the provided function.
253
+ *
254
+ * Tools represent external utilities or services that are invoked during an AI interaction.
255
+ * This method wraps a function call with tracing to capture the tool's inputs and outputs.
256
+ *
257
+ * @param params ToolParams object with tool configuration
258
+ * @param fn Function to execute within the tool trace
259
+ * @param thisArg Optional 'this' context for the function
260
+ * @param args Optional arguments to pass to the function
261
+ * @returns A promise that resolves with the tool execution result
262
+ *
263
+ * @example
264
+ * // Basic tool usage
265
+ * const result = await interaction.withTool(
266
+ * { name: "search_tool" },
267
+ * async () => {
268
+ * // Call to external API or service
269
+ * return "Search results";
270
+ * }
271
+ * );
272
+ *
273
+ * @example
274
+ * // Basic tool usage
275
+ * const result = await interaction.withTool(
276
+ * {
277
+ * name: "calculator",
278
+ * properties: { operation: "multiply" },
279
+ * inputParameters: { a: 5, b: 10 }
280
+ * },
281
+ * async () => {
282
+ * // Tool implementation
283
+ * return "Result: 50";
284
+ * }
285
+ * );
286
+ */
287
+ withTool<T>(params: ToolParams, fn: (...args: any[]) => Promise<T> | T, thisArg?: any, ...args: any[]): Promise<T>;
288
+ /**
289
+ * Creates a task span that can be used to manually record a task.
290
+ *
291
+ * @param params TaskParams object with task configuration
292
+ * @returns A span that can be used to record a task
293
+ */
294
+ startSpan(params: SpanParams): Span;
295
+ /**
296
+ * Sets multiple properties on the interaction context.
297
+ *
298
+ * @param properties Object containing properties to set
299
+ */
300
+ setProperties(properties: Record<string, string>): void;
301
+ /**
302
+ * Sets a single property on the interaction context.
303
+ *
304
+ * @param key The property key
305
+ * @param value The property value
306
+ */
307
+ setProperty(key: string, value: string): void;
308
+ /**
309
+ * Adds an attachment to the interaction.
310
+ *
311
+ * @param attachment The attachment to add
312
+ *
313
+ * @example
314
+ * // Adding various attachment types to an interaction
315
+ *
316
+ * // 1. Text attachment for context
317
+ * interaction.addAttachment([{
318
+ * type: "text",
319
+ * name: "Additional Info",
320
+ * value: "A very long document",
321
+ * role: "input",
322
+ * }]);
323
+ *
324
+ * // 2. Image attachment (output)
325
+ * interaction.addAttachment([{
326
+ * type: "image",
327
+ * value: "https://example.com/image.png",
328
+ * role: "output"
329
+ * }]);
330
+ *
331
+ * // 3. Iframe for embedded content
332
+ * interaction.addAttachment([{
333
+ * type: "iframe",
334
+ * name: "Generated UI",
335
+ * value: "https://newui.generated.com",
336
+ * role: "output",
337
+ * }]);
338
+ *
339
+ * // 4. Code snippet
340
+ * interaction.addAttachment([{
341
+ * type: "code",
342
+ * name: "Generated SQL Query",
343
+ * value: "SELECT * FROM users WHERE os_build = '17.1'",
344
+ * role: "output",
345
+ * language: "sql"
346
+ * }]);
347
+ *
348
+ * // All attachments are included when the interaction ends
349
+ * interaction.end("The weather is sunny and warm.");
350
+ */
351
+ addAttachments(attachments: Attachment[]): void;
352
+ /**
353
+ * Sets the input for the interaction.
354
+ *
355
+ * @param input The input string
356
+ */
357
+ setInput(input: string): void;
358
+ /**
359
+ * Ends the interaction and sends analytics data.
360
+ *
361
+ * This method completes the interaction lifecycle by:
362
+ * 1. Setting the trace_id as a property (if available)
363
+ * 2. Sending analytics data including the event ID, conversation ID,
364
+ * user ID, input, output, attachments, and any custom properties
365
+ *
366
+ * @param output The final output string for this interaction
367
+ *
368
+ * @example
369
+ * // Start and end an interaction
370
+ * const interaction = tracing.begin({
371
+ * userId: "user-123",
372
+ * convoId: "convo-456"
373
+ * });
374
+ *
375
+ * interaction.setInput("What can you help me with today?");
376
+ * // ... process the request ...
377
+ *
378
+ * // End the interaction with the response
379
+ * interaction.end("I can help you with various tasks. Here are some examples...");
380
+ */
381
+ finish(resultEvent: FinishInteractionOptions): void;
382
+ };
383
+ type Tracer = {
384
+ /**
385
+ * Creates a traced task that executes the provided function.
386
+ *
387
+ * @param params TaskParams object with task configuration
388
+ * @returns A span that can be used to record a task
389
+ */
390
+ withSpan<T>(params: SpanParams, fn: (...args: any[]) => Promise<T> | T, thisArg?: any, ...args: any[]): Promise<T>;
391
+ };
392
+
393
+ interface AnalyticsConfig {
394
+ writeKey: string;
395
+ bufferSize?: number;
396
+ bufferTimeout?: number;
397
+ debugLogs?: boolean;
398
+ endpoint?: string;
399
+ redactPii?: boolean;
400
+ /**
401
+ * false by default. If true, raindrop doesn't initialize OTEL tracing.
402
+ * you can then use the span processor using raindrop.createSpanProcessor()
403
+ */
404
+ disableTracing?: boolean;
405
+ /**
406
+ * false by default. If true, the SDK will not send any events or initialize tracing.
407
+ * Useful for development/test environments.
408
+ */
409
+ disabled?: boolean;
410
+ }
411
+ declare const MAX_INGEST_SIZE_BYTES: number;
412
+ declare class Raindrop {
413
+ private writeKey;
414
+ private apiUrl;
415
+ private buffer;
416
+ private bufferSize;
417
+ private bufferTimeout;
418
+ private flushTimer;
419
+ private redactPii;
420
+ private disabled;
421
+ private context;
422
+ private _tracing;
423
+ private partialEventBuffer;
424
+ private partialEventTimeouts;
425
+ private inFlightRequests;
426
+ debugLogs: boolean;
427
+ constructor(config: AnalyticsConfig);
428
+ private formatEndpoint;
429
+ /**
430
+ * Begins a new interaction.
431
+ *
432
+ * @param traceContext - The trace context for the interaction.
433
+ * @returns The interaction object.
434
+ */
435
+ begin(traceContext: PartialAiTrackEvent & {
436
+ event: string;
437
+ userId: string;
438
+ }): Interaction;
439
+ /**
440
+ * Returns a tracer object that can be used to create spans and tools that aren't tied to any interaction.
441
+ * For chat interaction use-case `begin` should be used.
442
+ * This is meant for batch jobs or other non-interactive use-cases where you only care about tracing and token usage.
443
+ *
444
+ * @param globalProperties - Optional global properties to be associated with all spans and tools.
445
+ * @returns The tracer object.
446
+ */
447
+ tracer(globalProperties?: Record<string, string>): Tracer;
448
+ createSpanProcessor(processorOptions?: SpanProcessorOptions): RaindropSpanProcessor;
449
+ /**
450
+ * Resumes an existing interaction.
451
+ *
452
+ * @param eventId - The ID of the interaction to resume.
453
+ * @returns The interaction object.
454
+ */
455
+ resumeInteraction(eventId: string): Interaction;
456
+ /**
457
+ * Track AI events. In addiiton to normal event properties, you can provide an "input", "output", or "model" parameter.
458
+ * It takes an AiTrackEvent as input and sends it to the /track-ai endpoint of the raindrop api.
459
+ *
460
+ * @param event - The AiTrackEvent (you must specify at least one of input/output properties)
461
+ * @returns A Promise that resolves when the event has been successfully sent.
462
+ *
463
+ * Example usage:
464
+ * ```typescript
465
+ * raindrop.track_ai({
466
+ * event: "chat", //name of the event
467
+ * model: "claude", //optional
468
+ * input: "what's up?", // input or output is required
469
+ * output: "not much human, how are you?", //input or output is required
470
+ * userId: "cn123456789",
471
+ * });
472
+ * ```
473
+ */
474
+ trackAi(event: AiTrackEvent | AiTrackEvent[]): string | Array<string | undefined> | undefined;
475
+ private isEnvWithLocalStorage;
476
+ setUserDetails(event: IdentifyEvent): void;
477
+ trackSignal(signal: SignalEvent | SignalEvent[]): void | void[];
478
+ private getSize;
479
+ private saveToBuffer;
480
+ private flush;
481
+ private sendBatchToApi;
482
+ private getContext;
483
+ private formatZodError;
484
+ /**
485
+ * Deeply merges properties of the source object into the target object.
486
+ * Modifies the target object in place. Handles nested plain objects.
487
+ */
488
+ private deepMergeObjects;
489
+ /**
490
+ * Internal method for tracking partial AI events. use .begin() to start an interaction instead.
491
+ *
492
+ * @param event - The PartialAiTrackEvent, requires eventId.
493
+ */
494
+ _trackAiPartial(event: PartialAiTrackEvent): void;
495
+ /**
496
+ * Flushes a single accumulated partial event by its ID.
497
+ * This is called internally by the timeout or by the close method.
498
+ * @param eventId - The ID of the partial event to flush.
499
+ */
500
+ private flushPartialEvent;
501
+ /**
502
+ * Internal implementation of flushPartialEvent without request tracking.
503
+ * @param eventId - The ID of the partial event to flush.
504
+ */
505
+ private _flushPartialEventInternal;
506
+ /**
507
+ * Sends a single prepared event object to the 'events/track_partial' endpoint.
508
+ * @param event - The event data conforming to ClientAiTrack schema.
509
+ */
510
+ private sendPartialEvent;
511
+ close(): Promise<void>;
512
+ }
513
+
514
+ export { type AiTrackEvent, type Attachment, type AttachmentType, type BeginInteractionOptions, type FinishInteractionOptions, type IdentifyEvent, type Interaction, MAX_INGEST_SIZE_BYTES, type PartialAiTrackEvent, Raindrop, type RaindropSpanProcessor, type SignalEvent, type SpanParams, type ToolParams, type TraceContext, type Tracer, type WorkflowParams, Raindrop as default };