@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,43 @@
1
+ import { ReveniumConfig, Logger } from './types';
2
+ /**
3
+ * Default console logger implementation
4
+ */
5
+ export declare const defaultLogger: Logger;
6
+ /**
7
+ * Validate Revenium configuration with enhanced error reporting
8
+ */
9
+ export declare function validateConfig(config: ReveniumConfig): void;
10
+ /**
11
+ * Get the current global configuration
12
+ */
13
+ export declare function getConfig(): ReveniumConfig | null;
14
+ /**
15
+ * Set the global configuration
16
+ */
17
+ export declare function setConfig(config: ReveniumConfig): void;
18
+ /**
19
+ * Get the current logger
20
+ */
21
+ export declare function getLogger(): Logger;
22
+ /**
23
+ * Set a custom logger
24
+ */
25
+ export declare function setLogger(logger: Logger): void;
26
+ /**
27
+ * Initialize configuration from environment variables
28
+ */
29
+ export declare function initializeConfig(): boolean;
30
+ /**
31
+ * Get configuration status
32
+ */
33
+ export declare function getConfigStatus(): {
34
+ hasConfig: boolean;
35
+ hasApiKey: boolean;
36
+ hasAnthropicKey: boolean;
37
+ baseUrl: string;
38
+ };
39
+ /**
40
+ * Validate current configuration
41
+ */
42
+ export declare function validateCurrentConfig(): boolean;
43
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Configuration constants for Revenium Anthropic middleware
3
+ * Centralizes all magic numbers and default values
4
+ */
5
+ /**
6
+ * Default configuration values
7
+ */
8
+ export declare const DEFAULT_CONFIG: {
9
+ /** Default Revenium API base URL */
10
+ readonly REVENIUM_BASE_URL: "https://api.revenium.io/meter";
11
+ /** Default API timeout in milliseconds */
12
+ readonly API_TIMEOUT: 5000;
13
+ /** Default maximum retries for failed API calls */
14
+ readonly MAX_RETRIES: 3;
15
+ /** Default fail silent behavior */
16
+ readonly FAIL_SILENT: true;
17
+ /** Minimum allowed API timeout */
18
+ readonly MIN_API_TIMEOUT: 1000;
19
+ /** Maximum allowed API timeout */
20
+ readonly MAX_API_TIMEOUT: 60000;
21
+ /** Maximum allowed retry attempts */
22
+ readonly MAX_RETRY_ATTEMPTS: 10;
23
+ /** Warning threshold for low API timeout */
24
+ readonly LOW_TIMEOUT_WARNING_THRESHOLD: 3000;
25
+ };
26
+ /**
27
+ * Circuit breaker configuration constants
28
+ */
29
+ export declare const CIRCUIT_BREAKER_CONFIG: {
30
+ /** Default number of failures before opening circuit */
31
+ readonly FAILURE_THRESHOLD: 5;
32
+ /** Default recovery timeout in milliseconds (30 seconds) */
33
+ readonly RECOVERY_TIMEOUT: 30000;
34
+ /** Default number of successful calls needed to close circuit */
35
+ readonly SUCCESS_THRESHOLD: 3;
36
+ /** Default time window for counting failures (1 minute) */
37
+ readonly TIME_WINDOW: 60000;
38
+ /** Maximum failure history size to prevent memory leaks */
39
+ readonly MAX_FAILURE_HISTORY_SIZE: 1000;
40
+ /** Periodic cleanup interval (5 minutes) */
41
+ readonly CLEANUP_INTERVAL: 300000;
42
+ /** Cleanup trigger threshold for failures array size */
43
+ readonly CLEANUP_SIZE_THRESHOLD: 100;
44
+ };
45
+ /**
46
+ * Retry configuration constants
47
+ */
48
+ export declare const RETRY_CONFIG: {
49
+ /** Base delay for exponential backoff in milliseconds */
50
+ readonly BASE_DELAY: 1000;
51
+ /** Maximum delay for exponential backoff */
52
+ readonly MAX_DELAY: 5000;
53
+ /** Jitter factor for randomizing delays */
54
+ readonly JITTER_FACTOR: 0.1;
55
+ };
56
+ /**
57
+ * Validation constants
58
+ */
59
+ export declare const VALIDATION_CONFIG: {
60
+ /** Minimum API key length */
61
+ readonly MIN_API_KEY_LENGTH: 20;
62
+ /** Required API key prefix for Revenium */
63
+ readonly REVENIUM_API_KEY_PREFIX: "hak_";
64
+ /** Required API key prefix for Anthropic */
65
+ readonly ANTHROPIC_API_KEY_PREFIX: "sk-ant-";
66
+ /** Maximum tokens warning threshold */
67
+ readonly HIGH_MAX_TOKENS_THRESHOLD: 4096;
68
+ /** Temperature range */
69
+ readonly MIN_TEMPERATURE: 0;
70
+ readonly MAX_TEMPERATURE: 1;
71
+ /** Response quality score range */
72
+ readonly MIN_QUALITY_SCORE: 0;
73
+ readonly MAX_QUALITY_SCORE: 1;
74
+ /** API timeout constraints */
75
+ readonly MIN_API_TIMEOUT: 1000;
76
+ readonly MAX_API_TIMEOUT: 60000;
77
+ readonly LOW_TIMEOUT_WARNING_THRESHOLD: 3000;
78
+ /** Retry constraints */
79
+ readonly MAX_RETRY_ATTEMPTS: 10;
80
+ };
81
+ /**
82
+ * Logging constants
83
+ */
84
+ export declare const LOGGING_CONFIG: {
85
+ /** Middleware name for log prefixes */
86
+ readonly MIDDLEWARE_NAME: "Revenium";
87
+ /** User agent string for API requests */
88
+ readonly USER_AGENT: "revenium-middleware-anthropic-node/1.0.0";
89
+ /** Debug environment variable name */
90
+ readonly DEBUG_ENV_VAR: "REVENIUM_DEBUG";
91
+ };
92
+ /**
93
+ * Environment variable names
94
+ */
95
+ export declare const ENV_VARS: {
96
+ /** Revenium API key */
97
+ readonly REVENIUM_API_KEY: "REVENIUM_METERING_API_KEY";
98
+ /** Revenium base URL */
99
+ readonly REVENIUM_BASE_URL: "REVENIUM_METERING_BASE_URL";
100
+ /** Anthropic API key */
101
+ readonly ANTHROPIC_API_KEY: "ANTHROPIC_API_KEY";
102
+ /** Debug mode */
103
+ readonly DEBUG: "REVENIUM_DEBUG";
104
+ /** Log level */
105
+ readonly LOG_LEVEL: "REVENIUM_LOG_LEVEL";
106
+ /** API timeout */
107
+ readonly API_TIMEOUT: "REVENIUM_API_TIMEOUT";
108
+ /** Fail silent mode */
109
+ readonly FAIL_SILENT: "REVENIUM_FAIL_SILENT";
110
+ /** Maximum retries */
111
+ readonly MAX_RETRIES: "REVENIUM_MAX_RETRIES";
112
+ };
113
+ /**
114
+ * API endpoints
115
+ */
116
+ export declare const API_ENDPOINTS: {
117
+ /** Revenium AI completions endpoint */
118
+ readonly AI_COMPLETIONS: "/v2/ai/completions";
119
+ };
120
+ /**
121
+ * Anthropic model patterns
122
+ */
123
+ export declare const ANTHROPIC_PATTERNS: {
124
+ /** Pattern to identify Claude models */
125
+ readonly CLAUDE_MODEL_PATTERN: RegExp;
126
+ /** Known Anthropic stop reasons */
127
+ readonly STOP_REASONS: {
128
+ readonly END_TURN: "end_turn";
129
+ readonly MAX_TOKENS: "max_tokens";
130
+ readonly STOP_SEQUENCE: "stop_sequence";
131
+ readonly TOOL_USE: "tool_use";
132
+ };
133
+ /** Revenium stop reason mappings */
134
+ readonly REVENIUM_STOP_REASON_MAP: {
135
+ readonly end_turn: "END";
136
+ readonly max_tokens: "TOKEN_LIMIT";
137
+ readonly stop_sequence: "END_SEQUENCE";
138
+ readonly tool_use: "END";
139
+ };
140
+ };
141
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Modern Revenium Anthropic Middleware
3
+ * Clean architecture without backward compatibility constraints
4
+ */
5
+ import "./types/anthropic-augmentation";
6
+ import { setConfig } from "./config";
7
+ import { trackUsageAsync } from "./tracking";
8
+ /**
9
+ * Core types for TypeScript developers using Revenium middleware
10
+ * @public
11
+ */
12
+ export type {
13
+ /** Configuration interface for Revenium middleware */
14
+ ReveniumConfig,
15
+ /** Usage metadata structure for tracking AI API calls */
16
+ UsageMetadata,
17
+ /** Logger interface for custom logging implementations */
18
+ Logger,
19
+ /** Middleware status and health information */
20
+ MiddlewareStatus,
21
+ /** Tracking data structure for manual usage reporting */
22
+ TrackingData,
23
+ /** Configuration validation result with detailed feedback */
24
+ ConfigValidationResult,
25
+ /** Request validation result for API call validation */
26
+ RequestValidationResult, } from "./types";
27
+ import type { MiddlewareStatus } from "./types";
28
+ export { setConfig, setLogger, getLogger, getConfig, getConfigStatus, validateCurrentConfig, } from "./config";
29
+ export { patchAnthropic, unpatchAnthropic, isAnthropicPatched, } from "./wrapper";
30
+ export { sendReveniumMetrics, trackUsageAsync, extractUsageFromStream, } from "./tracking";
31
+ export { getCircuitBreakerStats, resetCircuitBreaker, canExecuteRequest, } from "./utils/circuit-breaker";
32
+ export { validateReveniumConfig, validateAnthropicMessageParams, validateUsageMetadata, } from "./utils/validation";
33
+ export declare function initialize(): void;
34
+ /**
35
+ * Manual initialization with custom configuration
36
+ */
37
+ export declare function configure(config: Parameters<typeof setConfig>[0]): void;
38
+ /**
39
+ * Check if the middleware is properly initialized
40
+ */
41
+ export declare function isInitialized(): boolean;
42
+ /**
43
+ * Get comprehensive middleware status
44
+ */
45
+ export declare function getStatus(): MiddlewareStatus;
46
+ /**
47
+ * Manually track an Anthropic API call (for cases where auto-patching isn't used)
48
+ */
49
+ export declare function trackAnthropicCall(trackingData: Parameters<typeof trackUsageAsync>[0]): void;
50
+ /**
51
+ * Reset middleware to initial state (useful for testing)
52
+ */
53
+ export declare function reset(): void;
54
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Tracking implementation for Anthropic middleware with resilience patterns
3
+ */
4
+ import { TrackingData } from "./types";
5
+ /**
6
+ * Send tracking data to Revenium API with resilience patterns
7
+ */
8
+ export declare function sendReveniumMetrics(data: TrackingData): Promise<void>;
9
+ /**
10
+ * Fire-and-forget async tracking wrapper
11
+ * Ensures tracking never blocks the main application flow
12
+ */
13
+ export declare function trackUsageAsync(trackingData: TrackingData): void;
14
+ /**
15
+ * Extract usage data from Anthropic response
16
+ */
17
+ export declare function extractUsageFromResponse(response: {
18
+ usage?: {
19
+ input_tokens?: number;
20
+ output_tokens?: number;
21
+ cache_creation_input_tokens?: number;
22
+ cache_read_input_tokens?: number;
23
+ };
24
+ stop_reason?: string;
25
+ }): {
26
+ inputTokens: number;
27
+ outputTokens: number;
28
+ cacheCreationTokens?: number;
29
+ cacheReadTokens?: number;
30
+ stopReason?: string;
31
+ };
32
+ /**
33
+ * Extract usage data from streaming chunks
34
+ */
35
+ export declare function extractUsageFromStream(chunks: Array<any>): {
36
+ inputTokens: number;
37
+ outputTokens: number;
38
+ cacheCreationTokens?: number;
39
+ cacheReadTokens?: number;
40
+ stopReason?: string;
41
+ };
42
+ //# sourceMappingURL=tracking.d.ts.map
@@ -0,0 +1,182 @@
1
+ /**
2
+ * TypeScript module augmentation for Anthropic SDK
3
+ *
4
+ * This file extends Anthropic's existing types to include the usageMetadata field
5
+ * through TypeScript's declaration merging feature. This allows developers to
6
+ * use usageMetadata directly in Anthropic API calls without type casting or
7
+ * TypeScript errors.
8
+ *
9
+ * ## What is Module Augmentation?
10
+ *
11
+ * Module augmentation is a TypeScript feature that allows you to extend existing
12
+ * interfaces from external libraries. When you import this middleware, TypeScript
13
+ * automatically recognizes the usageMetadata field as a valid parameter.
14
+ *
15
+ * ## Benefits:
16
+ * - **Type Safety**: Full IntelliSense support for usageMetadata
17
+ * - **No Type Casting**: Use usageMetadata directly without `as any`
18
+ * - **Automatic Validation**: TypeScript validates the structure at compile time
19
+ * - **Better Developer Experience**: Auto-completion and error detection
20
+ *
21
+ * ## Usage Examples:
22
+ *
23
+ * ### Basic Usage:
24
+ * ```typescript
25
+ * import 'revenium-middleware-anthropic-node';
26
+ * import Anthropic from '@anthropic-ai/sdk';
27
+ *
28
+ * const anthropic = new Anthropic();
29
+ *
30
+ * const response = await anthropic.messages.create({
31
+ * model: 'claude-3-5-sonnet-latest',
32
+ * max_tokens: 1024,
33
+ * messages: [{ role: 'user', content: 'Hello!' }],
34
+ * usageMetadata: { // TypeScript recognizes this natively
35
+ * subscriber: { id: 'user-123', email: 'user@example.com' },
36
+ * organizationId: 'my-company',
37
+ * taskType: 'customer-support',
38
+ * traceId: 'session-abc-123'
39
+ * }
40
+ * });
41
+ * ```
42
+ *
43
+ * ### Streaming Usage:
44
+ * ```typescript
45
+ * const stream = await anthropic.messages.stream({
46
+ * model: 'claude-3-5-sonnet-latest',
47
+ * max_tokens: 1024,
48
+ * messages: [{ role: 'user', content: 'Generate a report' }],
49
+ * usageMetadata: {
50
+ * taskType: 'content-generation',
51
+ * productId: 'report-generator',
52
+ * responseQualityScore: 0.95
53
+ * }
54
+ * });
55
+ * ```
56
+ *
57
+ * ### Advanced Usage with All Fields:
58
+ * ```typescript
59
+ * const response = await anthropic.messages.create({
60
+ * model: 'claude-3-5-sonnet-latest',
61
+ * max_tokens: 2048,
62
+ * messages: [{ role: 'user', content: 'Complex analysis task' }],
63
+ * usageMetadata: {
64
+ * subscriber: {
65
+ * id: 'user-456',
66
+ * email: 'analyst@company.com',
67
+ * credential: { name: 'api-key', value: 'sk-...' }
68
+ * },
69
+ * traceId: 'analysis-session-789',
70
+ * taskId: 'task-001',
71
+ * taskType: 'data-analysis',
72
+ * organizationId: 'enterprise-client',
73
+ * subscriptionId: 'premium-plan',
74
+ * productId: 'analytics-suite',
75
+ * agent: 'data-analyst-bot',
76
+ * responseQualityScore: 0.98,
77
+ * customField: 'custom-value' // Extensible with custom fields
78
+ * }
79
+ * });
80
+ * ```
81
+ *
82
+ * @public
83
+ * @since 1.1.0
84
+ */
85
+ import { UsageMetadata } from "../types";
86
+ export {};
87
+ /**
88
+ * Module augmentation for Anthropic SDK message creation interfaces
89
+ *
90
+ * This declaration extends the official Anthropic SDK interfaces to include
91
+ * the usageMetadata field across all message creation methods.
92
+ */
93
+ declare module "@anthropic-ai/sdk/resources/messages" {
94
+ /**
95
+ * Base interface for message creation parameters
96
+ * Extended to include usageMetadata for all message creation operations
97
+ */
98
+ interface MessageCreateParamsBase {
99
+ /**
100
+ * Optional metadata for enhanced tracking and analytics
101
+ *
102
+ * This field enables rich context collection for business analytics,
103
+ * user tracking, billing, and operational insights. All nested fields
104
+ * are optional, allowing flexible usage patterns.
105
+ *
106
+ * ## Key Use Cases:
107
+ * - **User Tracking**: Identify and track individual users or subscribers
108
+ * - **Session Management**: Group related requests with traceId
109
+ * - **Business Analytics**: Categorize requests by taskType and productId
110
+ * - **Multi-tenancy**: Organize usage by organizationId
111
+ * - **Quality Monitoring**: Track response quality scores
112
+ * - **Custom Analytics**: Add custom fields for specific business needs
113
+ *
114
+ * @example Basic user tracking
115
+ * ```typescript
116
+ * usageMetadata: {
117
+ * subscriber: { id: 'user-123', email: 'user@example.com' },
118
+ * organizationId: 'my-company'
119
+ * }
120
+ * ```
121
+ *
122
+ * @example Session and task tracking
123
+ * ```typescript
124
+ * usageMetadata: {
125
+ * traceId: 'session-abc-123',
126
+ * taskType: 'customer-support',
127
+ * productId: 'help-desk'
128
+ * }
129
+ * ```
130
+ *
131
+ * @example Advanced analytics
132
+ * ```typescript
133
+ * usageMetadata: {
134
+ * subscriber: { id: 'user-456' },
135
+ * taskType: 'content-generation',
136
+ * responseQualityScore: 0.95,
137
+ * customMetric: 'high-priority'
138
+ * }
139
+ * ```
140
+ *
141
+ * @public
142
+ * @since 1.1.0
143
+ */
144
+ usageMetadata?: UsageMetadata;
145
+ }
146
+ /**
147
+ * Non-streaming message creation parameters
148
+ * Extended to include usageMetadata for standard (non-streaming) requests
149
+ */
150
+ interface MessageCreateParamsNonStreaming {
151
+ /**
152
+ * Optional metadata for enhanced tracking and analytics
153
+ *
154
+ * Provides the same rich tracking capabilities as the base interface,
155
+ * specifically for non-streaming message creation requests.
156
+ *
157
+ * @see MessageCreateParamsBase.usageMetadata for detailed documentation
158
+ * @public
159
+ * @since 1.1.0
160
+ */
161
+ usageMetadata?: UsageMetadata;
162
+ }
163
+ /**
164
+ * Streaming message creation parameters
165
+ * Extended to include usageMetadata for streaming requests
166
+ */
167
+ interface MessageCreateParamsStreaming {
168
+ /**
169
+ * Optional metadata for enhanced tracking and analytics
170
+ *
171
+ * Provides the same rich tracking capabilities as the base interface,
172
+ * specifically for streaming message creation requests. Particularly
173
+ * useful for tracking long-running or real-time interactions.
174
+ *
175
+ * @see MessageCreateParamsBase.usageMetadata for detailed documentation
176
+ * @public
177
+ * @since 1.1.0
178
+ */
179
+ usageMetadata?: UsageMetadata;
180
+ }
181
+ }
182
+ //# sourceMappingURL=anthropic-augmentation.d.ts.map