@revenium/anthropic 1.0.3 → 1.0.4

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 CHANGED
@@ -1,806 +1,456 @@
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
- > **Note - 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("\nStreaming 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 git@github.com:revenium/revenium-middleware-anthropic-node.git
339
- cd revenium-middleware-anthropic-node
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` | Yes | - | Your Revenium API key |
651
- | `ANTHROPIC_API_KEY` | Yes | - | Anthropic Claude API key |
652
- | `REVENIUM_METERING_BASE_URL` | No | `https://api.revenium.io/meter` | Revenium metering API base URL |
653
- | `REVENIUM_DEBUG` | No | `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` | Supported (Latest) | General purpose, best performance |
757
- | `claude-3-5-haiku-latest` | Supported (Latest) | Fast responses, cost-effective |
758
- | `claude-3-opus-latest` | Supported (Latest) | Complex reasoning, highest capability |
759
- | `claude-3-sonnet-20240229` | Supported (Stable) | Production workloads |
760
- | `claude-3-haiku-20240307` | Supported (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
-
769
- All examples are in the `examples/` directory of the installed package. For detailed TypeScript patterns and usage, see [examples/README.md](https://github.com/revenium/revenium-middleware-anthropic-node/blob/main/examples/README.md).
770
-
771
- ## How It Works
772
-
773
- 1. **Automatic Patching**: When imported, the middleware patches Anthropic's `messages.create` method
774
- 2. **Request Interception**: All Anthropic requests are intercepted to extract metadata
775
- 3. **Usage Extraction**: Token counts, model info, and timing data are captured
776
- 4. **Async Tracking**: Usage data is sent to Revenium in the background (fire-and-forget)
777
- 5. **Transparent Response**: Original Anthropic responses are returned unchanged
778
-
779
- The middleware never blocks your application - if Revenium tracking fails, your Anthropic requests continue normally.
780
-
781
- ## Requirements
782
-
783
- - Node.js 16+
784
- - Anthropic SDK (@anthropic-ai/sdk) v0.20.0+
785
- - TypeScript 5.0+ (for TypeScript projects)
786
- - Revenium API key
787
-
788
- ## License
789
-
790
- This project is licensed under the MIT License - see the [LICENSE](https://github.com/revenium/revenium-middleware-anthropic-node/blob/main/LICENSE) file for details.
791
-
792
- ## Support
793
-
794
- For issues, feature requests, or contributions:
795
-
796
- - **GitHub Repository**: [revenium/revenium-middleware-anthropic-node](https://github.com/revenium/revenium-middleware-anthropic-node)
797
- - **Issues**: [Report bugs or request features](https://github.com/revenium/revenium-middleware-anthropic-node/issues)
798
- - **Contact**: Reach out to the Revenium team for additional support
799
-
800
- ## Development
801
-
802
- For development and testing instructions, see [DEVELOPMENT.md](https://github.com/revenium/revenium-middleware-anthropic-node/blob/main/DEVELOPMENT.md).
803
-
804
- ---
805
-
806
- **Built by Revenium**
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
+ > **Note - 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
+ ### Quick Start
55
+
56
+ ```bash
57
+ npm install @revenium/anthropic @anthropic-ai/sdk
58
+ ```
59
+
60
+ For complete setup instructions, TypeScript patterns, and usage examples, see [examples/README.md](https://github.com/revenium/revenium-middleware-anthropic-node/blob/HEAD/examples/README.md).
61
+
62
+ ### Step-by-Step Guide
63
+
64
+ The following guide walks you through creating a new project from scratch:
65
+
66
+ ### Step 1: Create Your Project
67
+
68
+ ```bash
69
+ # Create project directory
70
+ mkdir my-anthropic-project
71
+ cd my-anthropic-project
72
+
73
+ # Initialize Node.js project
74
+ npm init -y
75
+ ```
76
+
77
+ ### Step 2: Install Dependencies
78
+
79
+ ```bash
80
+ # Install Revenium middleware and Anthropic SDK
81
+ npm install @revenium/anthropic @anthropic-ai/sdk@^0.55.1 dotenv
82
+
83
+ # For TypeScript projects (optional)
84
+ npm install -D typescript tsx @types/node
85
+ ```
86
+
87
+ ### Step 3: Setup Environment Variables
88
+
89
+ Create a `.env` file in your project root:
90
+
91
+ ```bash
92
+ # Create .env file
93
+ echo. > .env # On Windows (CMD)
94
+ touch .env # On Mac/Linux
95
+ # OR PowerShell
96
+ New-Item -Path .env -ItemType File
97
+ ```
98
+
99
+ Copy and paste the following into `.env`:
100
+
101
+ ```env
102
+ # Anthropic Configuration
103
+ ANTHROPIC_API_KEY=sk-ant-your_anthropic_api_key_here
104
+
105
+ # Revenium Configuration
106
+ REVENIUM_METERING_API_KEY=hak_your_revenium_api_key_here
107
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
108
+
109
+ # Optional: Enable debug logging
110
+ REVENIUM_DEBUG=true
111
+ ```
112
+
113
+ **NOTE**: Replace each `your_..._here` with your actual values.
114
+
115
+ ### Step 4: Protect Your API Keys
116
+
117
+ **CRITICAL**: Create a `.gitignore` file to prevent committing sensitive data like API keys.
118
+
119
+ **Recommended**: Use the industry-standard [GitHub Node.gitignore](https://github.com/github/gitignore/blob/main/Node.gitignore)
120
+
121
+ ```bash
122
+ # Download GitHub's standard Node.gitignore
123
+ curl -o .gitignore https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
124
+ ```
125
+
126
+ **IMPORTANT**: Ensure these patterns are included to protect your environment variables:
127
+
128
+ ```gitignore
129
+ # Environment variables - CRITICAL for API key protection
130
+ .env
131
+ .env.*
132
+ !.env.example
133
+ ```
134
+
135
+ Never commit `.env` files containing your API keys to version control.
136
+
137
+ ### Step 5: Follow the Examples
138
+
139
+ See [examples/README.md](https://github.com/revenium/revenium-middleware-anthropic-node/blob/HEAD/examples/README.md) for complete examples and setup instructions.
140
+
141
+ **Cloned from GitHub?** Run examples with:
142
+
143
+ ```bash
144
+ npm install
145
+ npm run example:basic
146
+ npm run example:advanced
147
+ ```
148
+
149
+ **Browse online:** [`examples/` directory](https://github.com/revenium/revenium-middleware-anthropic-node/tree/HEAD/examples)
150
+
151
+ ---
152
+
153
+ ## What Gets Tracked
154
+
155
+ The middleware automatically captures:
156
+
157
+ - **Token Usage**: Input and output tokens for accurate billing
158
+ - **Request Duration**: Total time for each API call
159
+ - **Model Information**: Which Claude model was used
160
+ - **Operation Type**: Chat completion, streaming, tool use, etc.
161
+ - **Error Tracking**: Failed requests and error details
162
+ - **Streaming Metrics**: Time to first token for streaming responses
163
+ - **Custom Metadata**: Business context you provide
164
+
165
+ ## Advanced Usage
166
+
167
+ ### Initialization Options
168
+
169
+ The middleware supports three initialization patterns:
170
+
171
+ #### Option A: Automatic Initialization (Simplest)
172
+
173
+ ```typescript
174
+ // Simply import - auto-initializes with graceful fallback
175
+ import "@revenium/anthropic";
176
+ import Anthropic from "@anthropic-ai/sdk";
177
+
178
+ // If env vars are set, tracking works automatically
179
+ const anthropic = new Anthropic();
180
+ ```
181
+
182
+ #### Option B: Explicit Initialization (More Control)
183
+
184
+ ```typescript
185
+ import { initialize } from "@revenium/anthropic";
186
+ import Anthropic from "@anthropic-ai/sdk";
187
+
188
+ try {
189
+ initialize();
190
+ // Middleware initialized successfully
191
+ } catch (error) {
192
+ // Handle initialization error appropriately
193
+ throw new Error(`Initialization failed: ${error.message}`);
194
+ }
195
+
196
+ const anthropic = new Anthropic();
197
+ ```
198
+
199
+ #### Option C: Manual Configuration (Full Control)
200
+
201
+ ```typescript
202
+ import { configure } from "@revenium/anthropic";
203
+ import Anthropic from "@anthropic-ai/sdk";
204
+
205
+ configure({
206
+ reveniumApiKey: "hak_your_api_key_here",
207
+ reveniumBaseUrl: "https://api.revenium.io/meter",
208
+ anthropicApiKey: "sk-ant-your_key_here",
209
+ apiTimeout: 5000,
210
+ failSilent: true,
211
+ maxRetries: 3,
212
+ });
213
+
214
+ const anthropic = new Anthropic();
215
+ ```
216
+
217
+ ### Streaming Responses
218
+
219
+ ```typescript
220
+ import "@revenium/anthropic";
221
+ import Anthropic from "@anthropic-ai/sdk";
222
+
223
+ const anthropic = new Anthropic();
224
+
225
+ const stream = await anthropic.messages.create({
226
+ model: "claude-3-5-sonnet-latest",
227
+ max_tokens: 1000,
228
+ messages: [{ role: "user", content: "Write a story about AI" }],
229
+ stream: true,
230
+ usageMetadata: {
231
+ subscriber: {
232
+ id: "user-123",
233
+ email: "user@example.com",
234
+ },
235
+ organizationId: "story-org",
236
+ taskType: "creative-writing",
237
+ agent: "story-writer",
238
+ },
239
+ });
240
+
241
+ for await (const event of stream) {
242
+ if (
243
+ event.type === "content_block_delta" &&
244
+ event.delta.type === "text_delta"
245
+ ) {
246
+ process.stdout.write(event.delta.text);
247
+ }
248
+ }
249
+ ```
250
+
251
+ ### Custom Metadata Tracking
252
+
253
+ Add business context to your AI usage:
254
+
255
+ ```typescript
256
+ // Custom metadata for enhanced tracking (following project structure)
257
+ const customMetadata = {
258
+ subscriber: {
259
+ id: "user-789",
260
+ email: "user@company.com",
261
+ credential: {
262
+ name: "premium-user",
263
+ value: "tier-1",
264
+ },
265
+ },
266
+ organizationId: "org-456",
267
+ productId: "premium-plan",
268
+ taskType: "CUSTOMER_SUPPORT",
269
+ agent: "CustomerSupportBot",
270
+ traceId: "user-session-123",
271
+ responseQualityScore: 9.2,
272
+ };
273
+
274
+ const response = await anthropic.messages.create({
275
+ model: "claude-3-5-sonnet-latest",
276
+ max_tokens: 1024,
277
+ messages: [{ role: "user", content: "Help me with my account" }],
278
+ usageMetadata: customMetadata,
279
+ });
280
+ ```
281
+
282
+ ### Usage Metadata Interface
283
+
284
+ All metadata fields are optional:
285
+
286
+ ```typescript
287
+ interface UsageMetadata {
288
+ traceId?: string; // Session or conversation ID
289
+ taskType?: string; // Type of AI task (e.g., "chat", "analysis")
290
+ organizationId?: string; // Organization/company ID
291
+ subscriptionId?: string; // Billing plan ID
292
+ productId?: string; // Your product/feature ID
293
+ agent?: string; // AI agent identifier
294
+ responseQualityScore?: number; // Quality score (0-1)
295
+ subscriber?: {
296
+ id?: string; // User ID from your system
297
+ email?: string; // User's email address
298
+ credential?: {
299
+ name?: string; // Credential name
300
+ value?: string; // Credential value
301
+ };
302
+ };
303
+ }
304
+ ```
305
+
306
+ ## Configuration Options
307
+
308
+ ### Environment Variables
309
+
310
+ | Variable | Required | Default | Description |
311
+ | ---------------------------- | -------- | ------------------------------- | --------------------------------- |
312
+ | `REVENIUM_METERING_API_KEY` | Yes | - | Your Revenium API key |
313
+ | `ANTHROPIC_API_KEY` | Yes | - | Anthropic Claude API key |
314
+ | `REVENIUM_METERING_BASE_URL` | No | `https://api.revenium.io/meter` | Revenium metering API base URL |
315
+ | `REVENIUM_DEBUG` | No | `false` | Enable debug logging (true/false) |
316
+
317
+ ### Manual Configuration
318
+
319
+ ```typescript
320
+ import { configure } from "@revenium/anthropic";
321
+
322
+ configure({
323
+ reveniumApiKey: "hak_your_api_key",
324
+ reveniumBaseUrl: "https://api.revenium.io/meter",
325
+ anthropicApiKey: "sk-ant-your_key",
326
+ apiTimeout: 5000,
327
+ failSilent: true,
328
+ maxRetries: 3,
329
+ });
330
+ ```
331
+
332
+ ## Troubleshooting
333
+
334
+ ### Common Issues
335
+
336
+ #### "Missing API Key" Error
337
+
338
+ ```bash
339
+ # Make sure you've set the API key
340
+ export ANTHROPIC_API_KEY="sk-ant-your-actual-api-key"
341
+
342
+ # Verify it's set
343
+ echo $ANTHROPIC_API_KEY
344
+ ```
345
+
346
+ #### "Requests not being tracked"
347
+
348
+ ```bash
349
+ # Verify Revenium configuration
350
+ export REVENIUM_METERING_API_KEY="hak-your-actual-revenium-key"
351
+
352
+ # Enable debug logging to see what's happening
353
+ export REVENIUM_DEBUG="true"
354
+ ```
355
+
356
+ #### TypeScript errors with usageMetadata
357
+
358
+ - Ensure you're importing the middleware before using Anthropic
359
+ - Check that your TypeScript version is 4.5+ for module augmentation
360
+ - Verify you're using the latest version: `npm update @revenium/anthropic`
361
+
362
+ #### Build/Import Errors
363
+
364
+ ```bash
365
+ # Clean and reinstall
366
+ rm -rf node_modules package-lock.json
367
+ npm install
368
+
369
+ # For TypeScript projects
370
+ npm run build
371
+ ```
372
+
373
+ ### Debug Mode
374
+
375
+ Enable detailed logging to troubleshoot issues:
376
+
377
+ ```bash
378
+ export REVENIUM_DEBUG="true"
379
+ node your-script.js
380
+ ```
381
+
382
+ This will show:
383
+
384
+ - Request/response details
385
+ - Token counting information
386
+ - Metering data being sent
387
+ - Error details
388
+
389
+ Look for log messages like:
390
+
391
+ - `[Revenium] Anthropic request intercepted`
392
+ - `[Revenium] Usage metadata extracted`
393
+ - `[Revenium] Revenium tracking successful`
394
+
395
+ ## Included Examples
396
+
397
+ The package includes these example files:
398
+
399
+ - **basic-usage.ts**: Simple chat completions with all initialization methods
400
+ - **advanced-features.ts**: Streaming, tools, and custom metadata
401
+
402
+ All examples are in the `examples/` directory of the installed package. For detailed TypeScript patterns and usage, see [examples/README.md](https://github.com/revenium/revenium-middleware-anthropic-node/blob/HEAD/examples/README.md).
403
+
404
+ ## How It Works
405
+
406
+ 1. **Automatic Patching**: When imported, the middleware patches Anthropic's `messages.create` method
407
+ 2. **Request Interception**: All Anthropic requests are intercepted to extract metadata
408
+ 3. **Usage Extraction**: Token counts, model info, and timing data are captured
409
+ 4. **Async Tracking**: Usage data is sent to Revenium in the background (fire-and-forget)
410
+ 5. **Transparent Response**: Original Anthropic responses are returned unchanged
411
+
412
+ The middleware never blocks your application - if Revenium tracking fails, your Anthropic requests continue normally.
413
+
414
+ ## Requirements
415
+
416
+ - Node.js 16+
417
+ - Anthropic SDK (@anthropic-ai/sdk) v0.20.0+
418
+ - TypeScript 5.0+ (for TypeScript projects)
419
+ - Revenium API key
420
+
421
+ ## Documentation
422
+
423
+ For detailed documentation, visit [docs.revenium.io](https://docs.revenium.io)
424
+
425
+ ## Contributing
426
+
427
+ See [CONTRIBUTING.md](https://github.com/revenium/revenium-middleware-anthropic-node/blob/HEAD/CONTRIBUTING.md)
428
+
429
+ ## Code of Conduct
430
+
431
+ See [CODE_OF_CONDUCT.md](https://github.com/revenium/revenium-middleware-anthropic-node/blob/HEAD/CODE_OF_CONDUCT.md)
432
+
433
+ ## Security
434
+
435
+ See [SECURITY.md](https://github.com/revenium/revenium-middleware-anthropic-node/blob/HEAD/SECURITY.md)
436
+
437
+ ## License
438
+
439
+ This project is licensed under the MIT License - see the [LICENSE](https://github.com/revenium/revenium-middleware-anthropic-node/blob/HEAD/LICENSE) file for details.
440
+
441
+ ## Support
442
+
443
+ For issues, feature requests, or contributions:
444
+
445
+ - **GitHub Repository**: [revenium/revenium-middleware-anthropic-node](https://github.com/revenium/revenium-middleware-anthropic-node)
446
+ - **Issues**: [Report bugs or request features](https://github.com/revenium/revenium-middleware-anthropic-node/issues)
447
+ - **Documentation**: [docs.revenium.io](https://docs.revenium.io)
448
+ - **Contact**: Reach out to the Revenium team for additional support
449
+
450
+ ## Development
451
+
452
+ For development and testing instructions, see [DEVELOPMENT.md](https://github.com/revenium/revenium-middleware-anthropic-node/blob/HEAD/DEVELOPMENT.md).
453
+
454
+ ---
455
+
456
+ **Built by Revenium**