@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.
package/README.md ADDED
@@ -0,0 +1,807 @@
1
+ # Revenium Middleware for Anthropic (Node.js)
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@revenium/anthropic.svg)](https://www.npmjs.com/package/@revenium/anthropic)
4
+ [![Node Versions](https://img.shields.io/node/v/@revenium/anthropic.svg)](https://www.npmjs.com/package/@revenium/anthropic)
5
+ [![Documentation](https://img.shields.io/badge/docs-revenium.io-blue)](https://docs.revenium.io)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ Automatically track and meter your Anthropic Claude API usage with Revenium. This middleware provides seamless integration with **Anthropic Claude SDK**, requiring minimal code changes and featuring native TypeScript support.
9
+
10
+ > **📦 Package Renamed**: This package has been renamed from `revenium-middleware-anthropic-node` to `@revenium/anthropic` for better organization and simpler naming. Please update your dependencies accordingly.
11
+
12
+ ## ✨ Features
13
+
14
+ - 🔄 **Seamless Integration**: Drop-in replacement with zero code changes required
15
+ - 📊 **Complete Metering**: Track tokens, costs, and performance metrics automatically
16
+ - 🎯 **Custom Metadata**: Add business context with native TypeScript support
17
+ - 🌊 **Streaming Support**: Real-time streaming with comprehensive analytics
18
+ - 🛠️ **Tool Use Support**: Full support for Anthropic's function calling and tools
19
+ - 🖼️ **Multi-modal Support**: Works with text, images, and all Claude capabilities
20
+ - 🛡️ **Type Safe**: Complete TypeScript support with no type casting required
21
+ - 🚀 **Fire-and-forget**: Never blocks your application flow
22
+ - 📈 **Analytics**: Detailed usage analytics and reporting
23
+
24
+ ## � Package Migration
25
+
26
+ This package has been renamed from `revenium-middleware-anthropic-node` to `@revenium/anthropic` for better organization and simpler naming.
27
+
28
+ ### Migration Steps
29
+
30
+ If you're upgrading from the old package:
31
+
32
+ ```bash
33
+ # Uninstall the old package
34
+ npm uninstall revenium-middleware-anthropic-node
35
+
36
+ # Install the new package
37
+ npm install @revenium/anthropic
38
+ ```
39
+
40
+ **Update your imports:**
41
+
42
+ ```typescript
43
+ // Old import
44
+ import "revenium-middleware-anthropic-node";
45
+
46
+ // New import
47
+ import "@revenium/anthropic";
48
+ ```
49
+
50
+ All functionality remains exactly the same - only the package name has changed.
51
+
52
+ ## �🚀 Getting Started
53
+
54
+ You have **3 options** to start using Revenium middleware:
55
+
56
+ ### Option 1: Create Project from Scratch
57
+
58
+ Perfect for new projects. We'll guide you step-by-step from `mkdir` to running tests.
59
+ [👉 Go to Step-by-Step Guide](#option-1-create-project-from-scratch)
60
+
61
+ ### Option 2: Clone Our Repository
62
+
63
+ Clone and run the repository with working examples.
64
+ [👉 Go to Repository Guide](#option-2-clone-our-repository)
65
+
66
+ ### Option 3: Add to Existing Project
67
+
68
+ Already have a project? Just install and replace imports.
69
+ [👉 Go to Quick Integration](#option-3-add-to-existing-project)
70
+
71
+ ---
72
+
73
+ ## Option 1: Create Project from Scratch
74
+
75
+ ### Step 1: Create Your Project
76
+
77
+ ```bash
78
+ # Create project directory
79
+ mkdir my-anthropic-project
80
+ cd my-anthropic-project
81
+
82
+ # Initialize Node.js project
83
+ npm init -y
84
+ ```
85
+
86
+ ### Step 2: Install Dependencies
87
+
88
+ ```bash
89
+ # Install Revenium middleware and Anthropic SDK
90
+ npm install @revenium/anthropic @anthropic-ai/sdk@^0.55.1 dotenv
91
+
92
+ # For TypeScript projects (optional)
93
+ npm install -D typescript tsx @types/node
94
+ ```
95
+
96
+ ### Step 3: Setup Environment Variables
97
+
98
+ Create a `.env` file in your project root:
99
+
100
+ ```bash
101
+ # Create .env file
102
+ echo. > .env # On Windows (CMD)
103
+ touch .env # On Mac/Linux
104
+ # OR PowerShell
105
+ New-Item -Path .env -ItemType File
106
+ ```
107
+
108
+ Copy and paste the following into `.env`:
109
+
110
+ ```env
111
+ # Anthropic Configuration
112
+ ANTHROPIC_API_KEY=sk-ant-your_anthropic_api_key_here
113
+
114
+ # Revenium Configuration
115
+ REVENIUM_METERING_API_KEY=hak_your_revenium_api_key_here
116
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
117
+
118
+ # Optional: Enable debug logging
119
+ REVENIUM_DEBUG=true
120
+ ```
121
+
122
+ **💡 NOTE**: Replace each `your_..._here` with your actual values.
123
+
124
+ **⚠️ IMPORTANT - Environment Matching**:
125
+
126
+ - If using QA environment URL `"https://api.qa.hcapp.io/meter"`, ensure your `REVENIUM_METERING_API_KEY` is from the **QA environment**
127
+ - If using Production environment URL `"https://api.revenium.io/meter"`, ensure your `REVENIUM_METERING_API_KEY` is from the **Production environment**
128
+ - **Mismatched environments will cause authentication failures**
129
+
130
+ ### Step 4: Create Your First Test
131
+
132
+ #### TypeScript Test
133
+
134
+ Create `test-anthropic.ts`:
135
+
136
+ ```typescript
137
+ // test-anthropic.ts
138
+ import "dotenv/config";
139
+ import "@revenium/anthropic";
140
+ import Anthropic from "@anthropic-ai/sdk";
141
+
142
+ async function testAnthropic() {
143
+ try {
144
+ const anthropic = new Anthropic();
145
+
146
+ const response = await anthropic.messages.create({
147
+ model: "claude-sonnet-4-20250514",
148
+ max_tokens: 100,
149
+ messages: [{ role: "user", content: "What is artificial intelligence?" }],
150
+ usageMetadata: {
151
+ subscriber: {
152
+ id: "test-user",
153
+ email: "test@example.com",
154
+ },
155
+ organizationId: "test-org",
156
+ taskType: "test-query",
157
+ },
158
+ });
159
+
160
+ const text =
161
+ response.content[0].type === "text"
162
+ ? response.content[0].text
163
+ : "Non-text response";
164
+
165
+ console.log("Response:", text);
166
+ // Success! Response and metering data sent to Revenium
167
+ } catch (error) {
168
+ console.error("Error:", error);
169
+ }
170
+ }
171
+
172
+ testAnthropic();
173
+ ```
174
+
175
+ #### JavaScript Test
176
+
177
+ Create `test-anthropic.js`:
178
+
179
+ ```javascript
180
+ // test-anthropic.js
181
+ require("dotenv").config();
182
+ require("@revenium/anthropic");
183
+ const Anthropic = require("@anthropic-ai/sdk");
184
+
185
+ async function testAnthropic() {
186
+ try {
187
+ const anthropic = new Anthropic();
188
+
189
+ const response = await anthropic.messages.create({
190
+ model: "claude-3-5-sonnet-latest",
191
+ max_tokens: 100,
192
+ messages: [{ role: "user", content: "What is artificial intelligence?" }],
193
+ });
194
+
195
+ const text =
196
+ response.content[0].type === "text"
197
+ ? response.content[0].text
198
+ : "Non-text response";
199
+
200
+ // Success! Response and metering data sent to Revenium
201
+ } catch (error) {
202
+ // Handle error appropriately
203
+ }
204
+ }
205
+
206
+ testAnthropic();
207
+ ```
208
+
209
+ ### Step 5: Update package.json
210
+
211
+ Add test scripts to your `package.json`:
212
+
213
+ ```json
214
+ {
215
+ "type": "commonjs",
216
+ "scripts": {
217
+ "test-ts": "npx tsx test-anthropic.ts",
218
+ "test-js": "node test-anthropic.js"
219
+ }
220
+ }
221
+ ```
222
+
223
+ ### Step 6: Run Your Tests
224
+
225
+ ```bash
226
+ # Test TypeScript
227
+ npm run test-ts
228
+
229
+ # Test JavaScript
230
+ npm run test-js
231
+ ```
232
+
233
+ ### Step 7: Create Advanced Examples
234
+
235
+ #### Streaming Example
236
+
237
+ Create `examples/streaming.ts`:
238
+
239
+ ```typescript
240
+ // examples/streaming.ts
241
+ import "dotenv/config";
242
+ import "@revenium/anthropic";
243
+ import Anthropic from "@anthropic-ai/sdk";
244
+
245
+ async function streamingExample() {
246
+ try {
247
+ const anthropic = new Anthropic();
248
+
249
+ const stream = await anthropic.messages.create({
250
+ model: "claude-3-5-sonnet-latest",
251
+ max_tokens: 200,
252
+ messages: [{ role: "user", content: "Write a short poem about AI" }],
253
+ stream: true,
254
+ usageMetadata: {
255
+ subscriber: {
256
+ id: "streaming-user",
257
+ email: "user@example.com",
258
+ },
259
+ organizationId: "creative-org",
260
+ taskType: "creative-writing",
261
+ agent: "poetry-bot",
262
+ },
263
+ });
264
+
265
+ for await (const event of stream) {
266
+ if (
267
+ event.type === "content_block_delta" &&
268
+ event.delta.type === "text_delta"
269
+ ) {
270
+ process.stdout.write(event.delta.text);
271
+ }
272
+ }
273
+
274
+ console.log("\n✅ Streaming completed with metering!");
275
+ } catch (error) {
276
+ console.error("❌ Streaming error:", error);
277
+ }
278
+ }
279
+
280
+ streamingExample();
281
+ ```
282
+
283
+ ### Step 8: Create .gitignore
284
+
285
+ **Important**: Never commit your API keys!
286
+
287
+ Create `.gitignore`:
288
+
289
+ ```gitignore
290
+ # Environment variables
291
+ .env
292
+ .env.*
293
+ !.env.example
294
+
295
+ # Dependencies
296
+ node_modules/
297
+
298
+ # Logs
299
+ *.log
300
+
301
+ # TypeScript
302
+ dist/
303
+ build/
304
+ ```
305
+
306
+ ### Step 9: Run Your Examples
307
+
308
+ ```bash
309
+ # Basic tests
310
+ npm run test-ts
311
+ npm run test-js
312
+
313
+ # Advanced streaming
314
+ npx tsx examples/streaming.ts
315
+ ```
316
+
317
+ ### Step 10: Project Structure
318
+
319
+ Your final project should look like this:
320
+
321
+ ```
322
+ my-anthropic-project/
323
+ ├── examples/ # Advanced examples
324
+ │ └── streaming.ts
325
+ ├── .env # Environment variables
326
+ ├── .gitignore # Git ignore file
327
+ ├── package.json # Project configuration
328
+ ├── test-anthropic.ts # TypeScript test
329
+ └── test-anthropic.js # JavaScript test
330
+ ```
331
+
332
+ ## Option 2: Clone Our Repository
333
+
334
+ ### Step 1: Clone the Repository
335
+
336
+ ```bash
337
+ # Clone the repository
338
+ git clone https://github.com/revenium/revenium-middleware-anthropic-node-internal.git
339
+ cd revenium-middleware-anthropic-node-internal
340
+ ```
341
+
342
+ ### Step 2: Install Dependencies
343
+
344
+ ```bash
345
+ # Install all dependencies
346
+ npm install
347
+ ```
348
+
349
+ ### Step 3: Setup Environment Variables
350
+
351
+ Create a `.env` file in the project root:
352
+
353
+ ```bash
354
+ # Create .env file
355
+ cp .env.example .env # If available, or create manually
356
+ ```
357
+
358
+ Copy and paste the following into `.env`:
359
+
360
+ ```env
361
+ # Anthropic Configuration
362
+ ANTHROPIC_API_KEY=sk-ant-your_anthropic_api_key_here
363
+
364
+ # Revenium Configuration
365
+ REVENIUM_METERING_API_KEY=hak_your_revenium_api_key_here
366
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
367
+
368
+ # Optional: Enable debug logging
369
+ REVENIUM_DEBUG=true
370
+ ```
371
+
372
+ **⚠️ IMPORTANT - Environment Matching**:
373
+
374
+ - If using QA environment URL `"https://api.qa.hcapp.io/meter"`, ensure your `REVENIUM_METERING_API_KEY` is from the **QA environment**
375
+ - If using Production environment URL `"https://api.revenium.io/meter"`, ensure your `REVENIUM_METERING_API_KEY` is from the **Production environment**
376
+ - **Mismatched environments will cause authentication failures**
377
+
378
+ ### Step 4: Build the Project
379
+
380
+ ```bash
381
+ # Build the middleware
382
+ npm run build
383
+ ```
384
+
385
+ ### Step 5: Run the Examples
386
+
387
+ The repository includes working example files:
388
+
389
+ ```bash
390
+ # Run the basic usage examples (shows all initialization methods)
391
+ npm run example:basic
392
+
393
+ # Run advanced features (streaming, tools, custom metadata)
394
+ npm run example:advanced
395
+
396
+ # Or run examples directly with tsx
397
+ npx tsx examples/basic-usage.ts
398
+ npx tsx examples/advanced-features.ts
399
+ ```
400
+
401
+ These examples demonstrate:
402
+
403
+ - All three initialization approaches (auto, explicit, manual)
404
+ - Basic text generation with usage tracking
405
+ - Streaming responses with metadata
406
+ - Tool/function calling support
407
+ - Custom business metadata integration
408
+ - Error handling and debugging
409
+
410
+ ## Option 3: Add to Existing Project
411
+
412
+ Already have a project? Just install and replace imports:
413
+
414
+ ### Step 1: Install the Package
415
+
416
+ ```bash
417
+ npm install @revenium/anthropic
418
+ ```
419
+
420
+ ### Step 2: Set Environment Variables
421
+
422
+ #### Option A: Use a .env file (Recommended)
423
+
424
+ Create a `.env` file in your project root:
425
+
426
+ ```env
427
+ ANTHROPIC_API_KEY=sk-ant-your_anthropic_api_key
428
+ REVENIUM_METERING_API_KEY=hak_your_revenium_api_key
429
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
430
+ REVENIUM_DEBUG=true
431
+ ```
432
+
433
+ #### Option B: Set variables directly in your terminal
434
+
435
+ **Linux / macOS (bash/zsh)**
436
+
437
+ ```bash
438
+ export ANTHROPIC_API_KEY="sk-ant-your-anthropic-api-key"
439
+ export REVENIUM_METERING_API_KEY="hak-your-revenium-api-key"
440
+ ```
441
+
442
+ **Windows PowerShell**
443
+
444
+ ```bash
445
+ $env:ANTHROPIC_API_KEY="sk-ant-your-anthropic-api-key"
446
+ $env:REVENIUM_METERING_API_KEY="hak-your-revenium-api-key"
447
+ ```
448
+
449
+ **Windows CMD**
450
+
451
+ ```bash
452
+ set ANTHROPIC_API_KEY=sk-ant-your-anthropic-api-key
453
+ set REVENIUM_METERING_API_KEY=hak-your-revenium-api-key
454
+ ```
455
+
456
+ ### Step 3: Update Your Code
457
+
458
+ **Before:**
459
+
460
+ ```typescript
461
+ import Anthropic from "@anthropic-ai/sdk";
462
+ ```
463
+
464
+ **After:**
465
+
466
+ ```typescript
467
+ import "@revenium/anthropic";
468
+ import Anthropic from "@anthropic-ai/sdk";
469
+ ```
470
+
471
+ ### Step 4: Use Anthropic Normally
472
+
473
+ ```typescript
474
+ const anthropic = new Anthropic();
475
+
476
+ // Your existing code works unchanged - metering happens automatically!
477
+ const response = await anthropic.messages.create({
478
+ model: "claude-3-5-sonnet-latest",
479
+ max_tokens: 1024,
480
+ messages: [{ role: "user", content: "Hello, world!" }],
481
+ // Optional: Add metadata for enhanced tracking
482
+ usageMetadata: {
483
+ userId: "user-123",
484
+ sessionId: "session-456",
485
+ },
486
+ });
487
+ ```
488
+
489
+ ---
490
+
491
+ ## 📊 What Gets Tracked
492
+
493
+ The middleware automatically captures:
494
+
495
+ - **Token Usage**: Input and output tokens for accurate billing
496
+ - **Request Duration**: Total time for each API call
497
+ - **Model Information**: Which Claude model was used
498
+ - **Operation Type**: Chat completion, streaming, tool use, etc.
499
+ - **Error Tracking**: Failed requests and error details
500
+ - **Streaming Metrics**: Time to first token for streaming responses
501
+ - **Custom Metadata**: Business context you provide
502
+
503
+ ## 🔧 Advanced Usage
504
+
505
+ ### Initialization Options
506
+
507
+ The middleware supports three initialization patterns:
508
+
509
+ #### Option A: Automatic Initialization (Simplest)
510
+
511
+ ```typescript
512
+ // Simply import - auto-initializes with graceful fallback
513
+ import "@revenium/anthropic";
514
+ import Anthropic from "@anthropic-ai/sdk";
515
+
516
+ // If env vars are set, tracking works automatically
517
+ const anthropic = new Anthropic();
518
+ ```
519
+
520
+ #### Option B: Explicit Initialization (More Control)
521
+
522
+ ```typescript
523
+ import { initialize } from "@revenium/anthropic";
524
+ import Anthropic from "@anthropic-ai/sdk";
525
+
526
+ try {
527
+ initialize();
528
+ // Middleware initialized successfully
529
+ } catch (error) {
530
+ // Handle initialization error appropriately
531
+ throw new Error(`Initialization failed: ${error.message}`);
532
+ }
533
+
534
+ const anthropic = new Anthropic();
535
+ ```
536
+
537
+ #### Option C: Manual Configuration (Full Control)
538
+
539
+ ```typescript
540
+ import { configure } from "@revenium/anthropic";
541
+ import Anthropic from "@anthropic-ai/sdk";
542
+
543
+ configure({
544
+ reveniumApiKey: "hak_your_api_key_here",
545
+ reveniumBaseUrl: "https://api.revenium.io/meter",
546
+ anthropicApiKey: "sk-ant-your_key_here",
547
+ apiTimeout: 5000,
548
+ failSilent: true,
549
+ maxRetries: 3,
550
+ });
551
+
552
+ const anthropic = new Anthropic();
553
+ ```
554
+
555
+ ### Streaming Responses
556
+
557
+ ```typescript
558
+ import "@revenium/anthropic";
559
+ import Anthropic from "@anthropic-ai/sdk";
560
+
561
+ const anthropic = new Anthropic();
562
+
563
+ const stream = await anthropic.messages.create({
564
+ model: "claude-3-5-sonnet-latest",
565
+ max_tokens: 1000,
566
+ messages: [{ role: "user", content: "Write a story about AI" }],
567
+ stream: true,
568
+ usageMetadata: {
569
+ subscriber: {
570
+ id: "user-123",
571
+ email: "user@example.com",
572
+ },
573
+ organizationId: "story-org",
574
+ taskType: "creative-writing",
575
+ agent: "story-writer",
576
+ },
577
+ });
578
+
579
+ for await (const event of stream) {
580
+ if (
581
+ event.type === "content_block_delta" &&
582
+ event.delta.type === "text_delta"
583
+ ) {
584
+ process.stdout.write(event.delta.text);
585
+ }
586
+ }
587
+ ```
588
+
589
+ ### Custom Metadata Tracking
590
+
591
+ Add business context to your AI usage:
592
+
593
+ ```typescript
594
+ // Custom metadata for enhanced tracking (following project structure)
595
+ const customMetadata = {
596
+ subscriber: {
597
+ id: "user-789",
598
+ email: "user@company.com",
599
+ credential: {
600
+ name: "premium-user",
601
+ value: "tier-1",
602
+ },
603
+ },
604
+ organizationId: "org-456",
605
+ productId: "premium-plan",
606
+ taskType: "CUSTOMER_SUPPORT",
607
+ agent: "CustomerSupportBot",
608
+ traceId: "user-session-123",
609
+ responseQualityScore: 9.2,
610
+ };
611
+
612
+ const response = await anthropic.messages.create({
613
+ model: "claude-3-5-sonnet-latest",
614
+ max_tokens: 1024,
615
+ messages: [{ role: "user", content: "Help me with my account" }],
616
+ usageMetadata: customMetadata,
617
+ });
618
+ ```
619
+
620
+ ### Usage Metadata Interface
621
+
622
+ All metadata fields are optional:
623
+
624
+ ```typescript
625
+ interface UsageMetadata {
626
+ traceId?: string; // Session or conversation ID
627
+ taskType?: string; // Type of AI task (e.g., "chat", "analysis")
628
+ organizationId?: string; // Organization/company ID
629
+ subscriptionId?: string; // Billing plan ID
630
+ productId?: string; // Your product/feature ID
631
+ agent?: string; // AI agent identifier
632
+ responseQualityScore?: number; // Quality score (0-1)
633
+ subscriber?: {
634
+ id?: string; // User ID from your system
635
+ email?: string; // User's email address
636
+ credential?: {
637
+ name?: string; // Credential name
638
+ value?: string; // Credential value
639
+ };
640
+ };
641
+ }
642
+ ```
643
+
644
+ ## 🛠️ Configuration Options
645
+
646
+ ### Environment Variables
647
+
648
+ | Variable | Required | Default | Description |
649
+ | ---------------------------- | -------- | ------------------------------- | --------------------------------- |
650
+ | `REVENIUM_METERING_API_KEY` | ✅ | - | Your Revenium API key |
651
+ | `ANTHROPIC_API_KEY` | ✅ | - | Anthropic Claude API key |
652
+ | `REVENIUM_METERING_BASE_URL` | ❌ | `https://api.revenium.io/meter` | Revenium metering API base URL |
653
+ | `REVENIUM_DEBUG` | ❌ | `false` | Enable debug logging (true/false) |
654
+
655
+ **⚠️ Important Note about `REVENIUM_METERING_BASE_URL`:**
656
+
657
+ - This variable is **optional** and defaults to the production URL (`https://api.revenium.io/meter`)
658
+ - If you don't set it explicitly, the middleware will use the default production endpoint
659
+ - However, you may see console warnings or errors if the middleware cannot determine the correct environment
660
+ - **Best practice:** Always set this variable explicitly to match your environment:
661
+
662
+ ```bash
663
+ # For Production
664
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
665
+
666
+ # For QA/Testing
667
+ REVENIUM_METERING_BASE_URL=https://api.qa.hcapp.io/meter
668
+ ```
669
+
670
+ - **Remember:** Your `REVENIUM_METERING_API_KEY` must match the environment of your base URL
671
+
672
+ ### Manual Configuration
673
+
674
+ ```typescript
675
+ import { configure } from "@revenium/anthropic";
676
+
677
+ configure({
678
+ reveniumApiKey: "hak_your_api_key",
679
+ reveniumBaseUrl: "https://api.revenium.io/meter",
680
+ anthropicApiKey: "sk-ant-your_key",
681
+ apiTimeout: 5000,
682
+ failSilent: true,
683
+ maxRetries: 3,
684
+ });
685
+ ```
686
+
687
+ ## 🚨 Troubleshooting
688
+
689
+ ### Common Issues
690
+
691
+ #### "Missing API Key" Error
692
+
693
+ ```bash
694
+ # Make sure you've set the API key
695
+ export ANTHROPIC_API_KEY="sk-ant-your-actual-api-key"
696
+
697
+ # Verify it's set
698
+ echo $ANTHROPIC_API_KEY
699
+ ```
700
+
701
+ #### "Requests not being tracked"
702
+
703
+ ```bash
704
+ # Verify Revenium configuration
705
+ export REVENIUM_METERING_API_KEY="hak-your-actual-revenium-key"
706
+
707
+ # Enable debug logging to see what's happening
708
+ export REVENIUM_DEBUG="true"
709
+ ```
710
+
711
+ #### TypeScript errors with usageMetadata
712
+
713
+ - Ensure you're importing the middleware before using Anthropic
714
+ - Check that your TypeScript version is 4.5+ for module augmentation
715
+ - Verify you're using the latest version: `npm update @revenium/anthropic`
716
+
717
+ #### Build/Import Errors
718
+
719
+ ```bash
720
+ # Clean and reinstall
721
+ rm -rf node_modules package-lock.json
722
+ npm install
723
+
724
+ # For TypeScript projects
725
+ npm run build
726
+ ```
727
+
728
+ ### Debug Mode
729
+
730
+ Enable detailed logging to troubleshoot issues:
731
+
732
+ ```bash
733
+ export REVENIUM_DEBUG="true"
734
+ node your-script.js
735
+ ```
736
+
737
+ This will show:
738
+
739
+ - Request/response details
740
+ - Token counting information
741
+ - Metering data being sent
742
+ - Error details
743
+
744
+ Look for log messages like:
745
+
746
+ - `[Revenium] Anthropic request intercepted`
747
+ - `[Revenium] Usage metadata extracted`
748
+ - `[Revenium] Revenium tracking successful`
749
+
750
+ ## 🔗 Supported Models
751
+
752
+ All Claude models are supported:
753
+
754
+ | Model | Status | Use Case |
755
+ | -------------------------- | --------- | ------------------------------------- |
756
+ | `claude-3-5-sonnet-latest` | ✅ Latest | General purpose, best performance |
757
+ | `claude-3-5-haiku-latest` | ✅ Latest | Fast responses, cost-effective |
758
+ | `claude-3-opus-latest` | ✅ Latest | Complex reasoning, highest capability |
759
+ | `claude-3-sonnet-20240229` | ✅ Stable | Production workloads |
760
+ | `claude-3-haiku-20240307` | ✅ Stable | High-volume applications |
761
+
762
+ ## 📚 Included Examples
763
+
764
+ The package includes these example files:
765
+
766
+ - **basic-usage.ts**: Simple chat completions with all initialization methods
767
+ - **advanced-features.ts**: Streaming, tools, and custom metadata
768
+ - **typescript-monorepo.ts**: TypeScript monorepo integration patterns
769
+
770
+ All examples are in the `examples/` directory of the installed package.
771
+
772
+ ## 🔄 How It Works
773
+
774
+ 1. **Automatic Patching**: When imported, the middleware patches Anthropic's `messages.create` method
775
+ 2. **Request Interception**: All Anthropic requests are intercepted to extract metadata
776
+ 3. **Usage Extraction**: Token counts, model info, and timing data are captured
777
+ 4. **Async Tracking**: Usage data is sent to Revenium in the background (fire-and-forget)
778
+ 5. **Transparent Response**: Original Anthropic responses are returned unchanged
779
+
780
+ The middleware never blocks your application - if Revenium tracking fails, your Anthropic requests continue normally.
781
+
782
+ ## 📋 Requirements
783
+
784
+ - Node.js 16+
785
+ - Anthropic SDK (@anthropic-ai/sdk) v0.20.0+
786
+ - TypeScript 5.0+ (for TypeScript projects)
787
+ - Revenium API key
788
+
789
+ ## 📄 License
790
+
791
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
792
+
793
+ ## 🤝 Support
794
+
795
+ For issues, feature requests, or contributions:
796
+
797
+ - **GitHub Repository**: [revenium/revenium-middleware-anthropic-node-internal](https://github.com/revenium/revenium-middleware-anthropic-node-internal)
798
+ - **Issues**: [Report bugs or request features](https://github.com/revenium/revenium-middleware-anthropic-node-internal/issues)
799
+ - **Contact**: Reach out to the Revenium team for additional support
800
+
801
+ ## Development
802
+
803
+ For development and testing instructions, see [DEVELOPMENT.md](DEVELOPMENT.md).
804
+
805
+ ---
806
+
807
+ **Built with ❤️ by Revenium**