@revenium/anthropic 1.0.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,647 @@
1
+ /**
2
+ * Type definitions for Anthropic middleware
3
+ */
4
+ /**
5
+ * Credential information for subscriber authentication
6
+ *
7
+ * @public
8
+ * @example
9
+ * ```typescript
10
+ * const credential: Credential = {
11
+ * name: 'api-key',
12
+ * value: 'sk-1234567890abcdef'
13
+ * };
14
+ * ```
15
+ */
16
+ export interface Credential {
17
+ /** The name/type of the credential (e.g., 'api-key', 'token', 'bearer') */
18
+ name: string;
19
+ /** The actual credential value */
20
+ value: string;
21
+ }
22
+ /**
23
+ * Subscriber information for Revenium API
24
+ * All fields are optional to allow flexible usage
25
+ *
26
+ * @public
27
+ * @example
28
+ * ```typescript
29
+ * const subscriber: Subscriber = {
30
+ * id: 'user-123',
31
+ * email: 'user@example.com',
32
+ * credential: {
33
+ * name: 'api-key',
34
+ * value: 'sk-1234567890abcdef'
35
+ * }
36
+ * };
37
+ * ```
38
+ */
39
+ export interface Subscriber {
40
+ /** Unique identifier for the subscriber */
41
+ id?: string;
42
+ /** Email address of the subscriber */
43
+ email?: string;
44
+ /** Authentication credential for the subscriber */
45
+ credential?: Credential;
46
+ }
47
+ /**
48
+ * Revenium configuration interface
49
+ *
50
+ * @public
51
+ * @example
52
+ * ```typescript
53
+ * const config: ReveniumConfig = {
54
+ * reveniumApiKey: 'hak_1234567890abcdef',
55
+ * reveniumBaseUrl: 'https://api.revenium.io/meter/v2',
56
+ * anthropicApiKey: 'sk-ant-1234567890abcdef',
57
+ * apiTimeout: 8000,
58
+ * failSilent: true,
59
+ * maxRetries: 3
60
+ * };
61
+ * ```
62
+ */
63
+ export interface ReveniumConfig {
64
+ /** Revenium API key (starts with hak_) - required for tracking */
65
+ reveniumApiKey: string;
66
+ /** Revenium base URL - endpoint for usage tracking */
67
+ reveniumBaseUrl: string;
68
+ /** Anthropic API key (optional if already configured in environment) */
69
+ anthropicApiKey?: string;
70
+ /** API timeout in milliseconds (default: 5000) */
71
+ apiTimeout?: number;
72
+ /** Whether to fail silently if Revenium tracking fails (default: true) */
73
+ failSilent?: boolean;
74
+ /** Maximum retries for failed Revenium API calls (default: 3) */
75
+ maxRetries?: number;
76
+ }
77
+ /**
78
+ * Usage metadata for enhanced tracking and analytics
79
+ *
80
+ * @public
81
+ * @example
82
+ * ```typescript
83
+ * const metadata: UsageMetadata = {
84
+ * subscriber: {
85
+ * id: 'user-123',
86
+ * email: 'user@example.com'
87
+ * },
88
+ * traceId: 'trace-abc-123',
89
+ * taskType: 'customer-support',
90
+ * organizationId: 'org-456',
91
+ * productId: 'chat-assistant',
92
+ * responseQualityScore: 0.95
93
+ * };
94
+ * ```
95
+ */
96
+ export interface UsageMetadata {
97
+ /** User identification information with nested structure for detailed tracking */
98
+ subscriber?: Subscriber;
99
+ /** Unique identifier for conversation/session tracking across multiple requests */
100
+ traceId?: string;
101
+ /** Identifier for specific AI task grouping within a trace */
102
+ taskId?: string;
103
+ /** Classification of AI operation (e.g., 'customer-support', 'content-generation', 'code-review') */
104
+ taskType?: string;
105
+ /** Customer organization identifier for multi-tenant applications */
106
+ organizationId?: string;
107
+ /** Reference to billing plan or subscription tier */
108
+ subscriptionId?: string;
109
+ /** Product or feature identifier that is using AI services */
110
+ productId?: string;
111
+ /** Agent or bot identifier for automated systems */
112
+ agent?: string;
113
+ /** Quality score of AI response (0.0-1.0) for performance tracking */
114
+ responseQualityScore?: number;
115
+ /** Allow additional custom fields for extensibility */
116
+ [key: string]: unknown;
117
+ }
118
+ /**
119
+ * Logger interface for consistent logging across the middleware
120
+ *
121
+ * @public
122
+ * @example
123
+ * ```typescript
124
+ * const customLogger: Logger = {
125
+ * debug: (msg, ctx) => console.debug(`[DEBUG] ${msg}`, ctx),
126
+ * info: (msg, ctx) => console.info(`[INFO] ${msg}`, ctx),
127
+ * warn: (msg, ctx) => console.warn(`[WARN] ${msg}`, ctx),
128
+ * error: (msg, ctx) => console.error(`[ERROR] ${msg}`, ctx)
129
+ * };
130
+ * ```
131
+ */
132
+ export interface Logger {
133
+ /** Log debug messages (only shown when debug mode is enabled) */
134
+ debug(message: string, context?: Record<string, unknown>): void;
135
+ /** Log informational messages */
136
+ info(message: string, context?: Record<string, unknown>): void;
137
+ /** Log warning messages */
138
+ warn(message: string, context?: Record<string, unknown>): void;
139
+ /** Log error messages */
140
+ error(message: string, context?: Record<string, unknown>): void;
141
+ }
142
+ /**
143
+ * Middleware status and health information
144
+ *
145
+ * @public
146
+ * @example
147
+ * ```typescript
148
+ * const status: MiddlewareStatus = {
149
+ * initialized: true,
150
+ * patched: true,
151
+ * hasConfig: true,
152
+ * anthropicVersion: '0.55.1',
153
+ * circuitBreakerState: 'CLOSED'
154
+ * };
155
+ * ```
156
+ */
157
+ export interface MiddlewareStatus {
158
+ /** Whether the middleware has been successfully initialized */
159
+ initialized: boolean;
160
+ /** Whether the Anthropic SDK has been patched for tracking */
161
+ patched: boolean;
162
+ /** Whether a valid configuration is available */
163
+ hasConfig: boolean;
164
+ /** Version of the Anthropic SDK if available */
165
+ anthropicVersion?: string;
166
+ /** Current state of the circuit breaker (CLOSED, OPEN, HALF_OPEN) */
167
+ circuitBreakerState?: string;
168
+ }
169
+ /**
170
+ * Tracking data structure for manual usage reporting to Revenium API
171
+ *
172
+ * @public
173
+ * @example
174
+ * ```typescript
175
+ * const trackingData: TrackingData = {
176
+ * requestId: 'req-123',
177
+ * model: 'claude-3-5-sonnet-latest',
178
+ * inputTokens: 150,
179
+ * outputTokens: 75,
180
+ * duration: 1250,
181
+ * isStreamed: false,
182
+ * stopReason: 'end_turn',
183
+ * requestTime: new Date('2024-01-01T10:00:00Z'),
184
+ * responseTime: new Date('2024-01-01T10:00:01Z')
185
+ * };
186
+ * ```
187
+ */
188
+ export interface TrackingData {
189
+ /** Unique identifier for the API request */
190
+ requestId: string;
191
+ /** AI model used for the request (e.g., 'claude-3-5-sonnet-latest') */
192
+ model: string;
193
+ /** Number of tokens in the input/prompt */
194
+ inputTokens: number;
195
+ /** Number of tokens in the output/response */
196
+ outputTokens: number;
197
+ /** Number of tokens used for cache creation (if applicable) */
198
+ cacheCreationTokens?: number;
199
+ /** Number of tokens read from cache (if applicable) */
200
+ cacheReadTokens?: number;
201
+ /** Total request duration in milliseconds */
202
+ duration: number;
203
+ /** Whether the response was streamed or returned all at once */
204
+ isStreamed: boolean;
205
+ /** Reason why the completion stopped (e.g., 'end_turn', 'max_tokens', 'stop_sequence') */
206
+ stopReason?: string;
207
+ /** Additional usage metadata for enhanced tracking */
208
+ metadata?: UsageMetadata;
209
+ /** Timestamp when the request was initiated */
210
+ requestTime: Date;
211
+ /** Timestamp when the response was completed */
212
+ responseTime: Date;
213
+ /** Time to first token in milliseconds (for streaming responses) */
214
+ timeToFirstToken?: number;
215
+ }
216
+ /**
217
+ * Internal payload structure for Revenium API
218
+ * This interface represents the exact format expected by Revenium's tracking endpoint
219
+ *
220
+ * @internal
221
+ * @example
222
+ * ```typescript
223
+ * const payload: ReveniumPayload = {
224
+ * stopReason: 'end_turn',
225
+ * costType: 'AI',
226
+ * isStreamed: false,
227
+ * operationType: 'CHAT',
228
+ * inputTokenCount: 150,
229
+ * outputTokenCount: 75,
230
+ * reasoningTokenCount: 0,
231
+ * cacheCreationTokenCount: 0,
232
+ * cacheReadTokenCount: 0,
233
+ * totalTokenCount: 225,
234
+ * model: 'claude-3-5-sonnet-latest',
235
+ * transactionId: 'txn-123',
236
+ * responseTime: '2024-01-01T10:00:01.000Z',
237
+ * requestDuration: 1250,
238
+ * provider: 'anthropic'
239
+ * };
240
+ * ```
241
+ */
242
+ export interface ReveniumPayload {
243
+ /** Reason why the AI completion stopped */
244
+ stopReason: string;
245
+ /** Type of cost being tracked (always 'AI' for this middleware) */
246
+ costType: "AI";
247
+ /** Whether the response was streamed */
248
+ isStreamed: boolean;
249
+ /** Type of AI task being performed */
250
+ taskType?: string;
251
+ /** Agent or bot identifier */
252
+ agent?: string;
253
+ /** Type of AI operation (always 'CHAT' for Anthropic) */
254
+ operationType: "CHAT";
255
+ /** Number of input tokens consumed */
256
+ inputTokenCount: number;
257
+ /** Number of output tokens generated */
258
+ outputTokenCount: number;
259
+ /** Number of reasoning tokens used (for models that support reasoning) */
260
+ reasoningTokenCount: number;
261
+ /** Number of tokens used for cache creation */
262
+ cacheCreationTokenCount: number;
263
+ /** Number of tokens read from cache */
264
+ cacheReadTokenCount: number;
265
+ /** Total token count (sum of all token types) */
266
+ totalTokenCount: number;
267
+ /** Organization identifier for multi-tenant tracking */
268
+ organizationId?: string;
269
+ /** Product identifier */
270
+ productId?: string;
271
+ /** Subscriber information */
272
+ subscriber?: Subscriber;
273
+ /** Subscription identifier */
274
+ subscriptionId?: string;
275
+ /** AI model identifier */
276
+ model: string;
277
+ /** Unique transaction identifier */
278
+ transactionId: string;
279
+ /** ISO timestamp of response completion */
280
+ responseTime: string;
281
+ /** Request duration in milliseconds */
282
+ requestDuration: number;
283
+ /** AI provider name (always 'anthropic' for this middleware) */
284
+ provider: string;
285
+ /** ISO timestamp when the request was initiated */
286
+ requestTime: string;
287
+ /** ISO timestamp when completion generation started */
288
+ completionStartTime: string;
289
+ /** Time to first token in milliseconds */
290
+ timeToFirstToken: number;
291
+ /** Optional trace identifier for request correlation */
292
+ traceId?: string;
293
+ /** Source identifier for the middleware */
294
+ middlewareSource: string;
295
+ }
296
+ /**
297
+ * Anthropic content block types for message validation
298
+ * These interfaces match Anthropic's API specification for different content types
299
+ *
300
+ * @public
301
+ */
302
+ /**
303
+ * Text content block for Anthropic messages
304
+ *
305
+ * @public
306
+ */
307
+ export interface AnthropicTextContent {
308
+ /** Content type identifier */
309
+ type: "text";
310
+ /** The actual text content */
311
+ text: string;
312
+ }
313
+ /**
314
+ * Image content block for Anthropic messages
315
+ *
316
+ * @public
317
+ */
318
+ export interface AnthropicImageContent {
319
+ /** Content type identifier */
320
+ type: "image";
321
+ /** Image source configuration */
322
+ source: {
323
+ /** Source type (always 'base64' for direct image data) */
324
+ type: "base64";
325
+ /** MIME type of the image */
326
+ media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp";
327
+ /** Base64-encoded image data */
328
+ data: string;
329
+ };
330
+ }
331
+ /**
332
+ * Tool use content block for Anthropic messages
333
+ *
334
+ * @public
335
+ */
336
+ export interface AnthropicToolUseContent {
337
+ /** Content type identifier */
338
+ type: "tool_use";
339
+ /** Unique identifier for this tool use */
340
+ id: string;
341
+ /** Name of the tool being used */
342
+ name: string;
343
+ /** Input parameters for the tool */
344
+ input: Record<string, unknown>;
345
+ }
346
+ /**
347
+ * Tool result content block for Anthropic messages
348
+ *
349
+ * @public
350
+ */
351
+ export interface AnthropicToolResultContent {
352
+ /** Content type identifier */
353
+ type: "tool_result";
354
+ /** ID of the tool use this result corresponds to */
355
+ tool_use_id: string;
356
+ /** Result content (can be string or structured text blocks) */
357
+ content?: string | AnthropicTextContent[];
358
+ /** Whether this result represents an error */
359
+ is_error?: boolean;
360
+ }
361
+ /**
362
+ * Union type for all possible Anthropic content blocks
363
+ *
364
+ * @public
365
+ */
366
+ export type AnthropicContentBlock = AnthropicTextContent | AnthropicImageContent | AnthropicToolUseContent | AnthropicToolResultContent;
367
+ /**
368
+ * Anthropic message structure for validation
369
+ *
370
+ * @public
371
+ * @example
372
+ * ```typescript
373
+ * const message: AnthropicMessage = {
374
+ * role: 'user',
375
+ * content: 'Hello, how can you help me today?'
376
+ * };
377
+ * ```
378
+ */
379
+ export interface AnthropicMessage {
380
+ /** Role of the message sender */
381
+ role: "user" | "assistant" | "system";
382
+ /** Message content (can be simple string or structured content blocks) */
383
+ content: string | AnthropicContentBlock[];
384
+ }
385
+ /**
386
+ * Anthropic tool definition for function calling
387
+ *
388
+ * @public
389
+ * @example
390
+ * ```typescript
391
+ * const tool: AnthropicTool = {
392
+ * name: 'get_weather',
393
+ * description: 'Get current weather for a location',
394
+ * input_schema: {
395
+ * type: 'object',
396
+ * properties: {
397
+ * location: {
398
+ * type: 'string',
399
+ * description: 'City name'
400
+ * }
401
+ * },
402
+ * required: ['location']
403
+ * }
404
+ * };
405
+ * ```
406
+ */
407
+ export interface AnthropicTool {
408
+ /** Name of the tool function */
409
+ name: string;
410
+ /** Human-readable description of what the tool does */
411
+ description: string;
412
+ /** JSON Schema defining the tool's input parameters */
413
+ input_schema: {
414
+ /** Schema type (always 'object' for tool inputs) */
415
+ type: "object";
416
+ /** Property definitions for the tool parameters */
417
+ properties: Record<string, {
418
+ /** Parameter data type */
419
+ type: "string" | "number" | "boolean" | "array" | "object";
420
+ /** Human-readable description of the parameter */
421
+ description?: string;
422
+ /** Allowed values for string parameters */
423
+ enum?: string[];
424
+ /** Item type definition for array parameters */
425
+ items?: {
426
+ type: string;
427
+ };
428
+ }>;
429
+ /** List of required parameter names */
430
+ required?: string[];
431
+ };
432
+ }
433
+ /**
434
+ * Anthropic tool choice configuration for controlling tool usage
435
+ *
436
+ * @public
437
+ * @example
438
+ * ```typescript
439
+ * const toolChoice: AnthropicToolChoice = {
440
+ * type: 'tool',
441
+ * name: 'get_weather'
442
+ * };
443
+ * ```
444
+ */
445
+ export interface AnthropicToolChoice {
446
+ /** How the model should choose tools ('auto', 'any', or 'tool') */
447
+ type: "auto" | "any" | "tool";
448
+ /** Specific tool name (required when type is 'tool') */
449
+ name?: string;
450
+ }
451
+ /**
452
+ * Anthropic message creation parameters
453
+ * Complete interface for all parameters supported by Anthropic's messages API
454
+ *
455
+ * @public
456
+ * @example
457
+ * ```typescript
458
+ * const params: AnthropicMessageParams = {
459
+ * model: 'claude-3-5-sonnet-latest',
460
+ * messages: [{ role: 'user', content: 'Hello!' }],
461
+ * max_tokens: 1024,
462
+ * temperature: 0.7,
463
+ * usageMetadata: {
464
+ * subscriber: { id: 'user-123' }
465
+ * }
466
+ * };
467
+ * ```
468
+ */
469
+ export interface AnthropicMessageParams {
470
+ /** AI model to use (e.g., 'claude-3-5-sonnet-latest') */
471
+ model: string;
472
+ /** Array of conversation messages */
473
+ messages: AnthropicMessage[];
474
+ /** Maximum number of tokens to generate */
475
+ max_tokens?: number;
476
+ /** Sampling temperature (0.0 to 1.0) */
477
+ temperature?: number;
478
+ /** Nucleus sampling parameter (0.0 to 1.0) */
479
+ top_p?: number;
480
+ /** Top-k sampling parameter */
481
+ top_k?: number;
482
+ /** Whether to stream the response */
483
+ stream?: boolean;
484
+ /** Sequences that will stop generation */
485
+ stop_sequences?: string[];
486
+ /** System message to set context */
487
+ system?: string;
488
+ /** Available tools for function calling */
489
+ tools?: AnthropicTool[];
490
+ /** Tool usage configuration */
491
+ tool_choice?: AnthropicToolChoice;
492
+ /** Usage metadata for tracking (added by this middleware) */
493
+ usageMetadata?: UsageMetadata;
494
+ }
495
+ /**
496
+ * Anthropic response content blocks
497
+ */
498
+ export interface AnthropicResponseTextContent {
499
+ type: "text";
500
+ text: string;
501
+ }
502
+ export interface AnthropicResponseToolUseContent {
503
+ type: "tool_use";
504
+ id: string;
505
+ name: string;
506
+ input: Record<string, unknown>;
507
+ }
508
+ export type AnthropicResponseContent = AnthropicResponseTextContent | AnthropicResponseToolUseContent;
509
+ /**
510
+ * Anthropic usage statistics
511
+ */
512
+ export interface AnthropicUsage {
513
+ input_tokens: number;
514
+ output_tokens: number;
515
+ cache_creation_input_tokens?: number;
516
+ cache_read_input_tokens?: number;
517
+ }
518
+ /**
519
+ * Anthropic response structure
520
+ */
521
+ export interface AnthropicResponse {
522
+ id: string;
523
+ type: "message";
524
+ role: "assistant";
525
+ content: AnthropicResponseContent[];
526
+ model: string;
527
+ stop_reason: "end_turn" | "max_tokens" | "stop_sequence" | "tool_use";
528
+ stop_sequence?: string;
529
+ usage: AnthropicUsage;
530
+ }
531
+ /**
532
+ * Stream chunk delta types
533
+ */
534
+ export interface AnthropicStreamTextDelta {
535
+ type: "text_delta";
536
+ text: string;
537
+ }
538
+ export interface AnthropicStreamInputJsonDelta {
539
+ type: "input_json_delta";
540
+ partial_json: string;
541
+ }
542
+ export type AnthropicStreamDelta = AnthropicStreamTextDelta | AnthropicStreamInputJsonDelta | {
543
+ type: string;
544
+ text?: string;
545
+ stop_reason?: "end_turn" | "max_tokens" | "stop_sequence" | "tool_use";
546
+ };
547
+ /**
548
+ * Stream chunk structure for Anthropic streaming
549
+ */
550
+ export interface AnthropicStreamChunk {
551
+ type: "message_start" | "content_block_start" | "content_block_delta" | "content_block_stop" | "message_delta" | "message_stop";
552
+ message?: Partial<AnthropicResponse>;
553
+ content_block?: AnthropicResponseContent;
554
+ delta?: AnthropicStreamDelta;
555
+ usage?: Partial<AnthropicUsage>;
556
+ }
557
+ /**
558
+ * Configuration validation result with detailed feedback
559
+ *
560
+ * @public
561
+ * @example
562
+ * ```typescript
563
+ * const result: ConfigValidationResult = {
564
+ * isValid: false,
565
+ * errors: ['Missing reveniumApiKey'],
566
+ * warnings: ['apiTimeout is very high'],
567
+ * suggestions: ['Set REVENIUM_METERING_API_KEY environment variable']
568
+ * };
569
+ * ```
570
+ */
571
+ export interface ConfigValidationResult {
572
+ /** Whether the configuration is valid and ready to use */
573
+ isValid: boolean;
574
+ /** Array of validation errors that prevent usage */
575
+ errors: string[];
576
+ /** Array of validation warnings (non-blocking issues) */
577
+ warnings: string[];
578
+ /** The validated configuration object (if valid) */
579
+ config?: ReveniumConfig;
580
+ /** Helpful suggestions for fixing validation issues */
581
+ suggestions?: string[];
582
+ }
583
+ /**
584
+ * Request validation result for API call validation
585
+ *
586
+ * @public
587
+ * @example
588
+ * ```typescript
589
+ * const result: RequestValidationResult = {
590
+ * isValid: true,
591
+ * errors: [],
592
+ * warnings: ['Large message count may impact performance']
593
+ * };
594
+ * ```
595
+ */
596
+ export interface RequestValidationResult {
597
+ /** Whether the request parameters are valid */
598
+ isValid: boolean;
599
+ /** Array of validation errors that prevent the request */
600
+ errors: string[];
601
+ /** Array of validation warnings (non-blocking issues) */
602
+ warnings: string[];
603
+ }
604
+ /**
605
+ * Anthropic SDK method signatures for patching
606
+ */
607
+ export interface AnthropicMethodSignatures {
608
+ create: (params: AnthropicMessageParams, options?: Record<string, unknown>) => Promise<AnthropicResponse>;
609
+ stream: (params: AnthropicMessageParams, options?: Record<string, unknown>) => AsyncIterable<AnthropicStreamChunk>;
610
+ }
611
+ /**
612
+ * Patching context for tracking
613
+ */
614
+ export interface PatchingContext {
615
+ originalMethods: Partial<AnthropicMethodSignatures>;
616
+ isPatched: boolean;
617
+ patchedInstances: WeakSet<object>;
618
+ }
619
+ /**
620
+ * HTTP request options for Revenium API
621
+ */
622
+ export interface ReveniumRequestOptions {
623
+ method: "POST";
624
+ headers: {
625
+ "Content-Type": "application/json";
626
+ "x-api-key": string;
627
+ "User-Agent": string;
628
+ [key: string]: string;
629
+ };
630
+ body: string;
631
+ timeout?: number;
632
+ signal?: AbortSignal;
633
+ }
634
+ /**
635
+ * Environment configuration
636
+ */
637
+ export interface EnvironmentConfig {
638
+ reveniumApiKey?: string;
639
+ reveniumBaseUrl?: string;
640
+ anthropicApiKey?: string;
641
+ debug?: boolean;
642
+ logLevel?: string;
643
+ apiTimeout?: string;
644
+ failSilent?: string;
645
+ maxRetries?: string;
646
+ }
647
+ //# sourceMappingURL=types.d.ts.map