@revenium/perplexity 1.0.11 → 1.0.15

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.
Files changed (51) hide show
  1. package/.env.example +3 -3
  2. package/README.md +447 -603
  3. package/dist/index.js +19 -0
  4. package/dist/interfaces/chatCompletionRequest.d.ts +8 -0
  5. package/dist/interfaces/chatCompletionRequest.js +2 -0
  6. package/dist/interfaces/credential.d.ts +4 -0
  7. package/dist/interfaces/credential.js +2 -0
  8. package/dist/interfaces/meteringRequest.d.ts +13 -0
  9. package/dist/interfaces/meteringRequest.js +2 -0
  10. package/dist/interfaces/meteringResponse.d.ts +27 -0
  11. package/dist/interfaces/meteringResponse.js +2 -0
  12. package/dist/interfaces/operation.d.ts +4 -0
  13. package/dist/interfaces/operation.js +8 -0
  14. package/dist/interfaces/subscriber.d.ts +8 -0
  15. package/dist/interfaces/subscriber.js +2 -0
  16. package/dist/interfaces/tokenCounts.d.ts +7 -0
  17. package/dist/interfaces/tokenCounts.js +2 -0
  18. package/dist/interfaces/usageMetadata.d.ts +13 -0
  19. package/dist/interfaces/usageMetadata.js +2 -0
  20. package/dist/middleware.d.ts +22 -0
  21. package/dist/middleware.js +129 -0
  22. package/dist/models/Logger.js +35 -0
  23. package/dist/models/Metering.d.ts +9 -0
  24. package/dist/models/Metering.js +72 -0
  25. package/dist/utils/calculateDurationMs.d.ts +1 -0
  26. package/dist/utils/calculateDurationMs.js +6 -0
  27. package/dist/utils/constants/constants.d.ts +6 -0
  28. package/dist/utils/constants/constants.js +11 -0
  29. package/dist/utils/constants/messages.d.ts +5 -0
  30. package/dist/utils/constants/messages.js +8 -0
  31. package/dist/utils/constants/models.d.ts +1 -0
  32. package/dist/utils/constants/models.js +21 -0
  33. package/dist/utils/extractTokenCount.d.ts +2 -0
  34. package/dist/utils/extractTokenCount.js +28 -0
  35. package/dist/utils/formatTimeStamp.d.ts +1 -0
  36. package/dist/utils/formatTimeStamp.js +6 -0
  37. package/dist/utils/generateTransactionId.d.ts +1 -0
  38. package/dist/utils/generateTransactionId.js +7 -0
  39. package/dist/utils/index.d.ts +6 -0
  40. package/dist/utils/index.js +23 -0
  41. package/dist/utils/loadEnv.d.ts +1 -0
  42. package/dist/utils/loadEnv.js +7 -0
  43. package/dist/utils/safeExtract.d.ts +29 -0
  44. package/dist/utils/safeExtract.js +67 -0
  45. package/examples/chat-completions.ts +0 -1
  46. package/examples/enhanced.ts +0 -1
  47. package/examples/streaming.ts +0 -1
  48. package/package.json +47 -45
  49. package/playground/basic.js +0 -1
  50. package/playground/enhanced.js +0 -1
  51. package/playground/streaming.js +0 -1
package/README.md CHANGED
@@ -1,603 +1,447 @@
1
- # Revenium Middleware for Perplexity AI (Node.js)
2
-
3
- [![npm version](https://badge.fury.io/js/%40revenium%2Fperplexity.svg)](https://badge.fury.io/js/%40revenium%2Fperplexity)
4
- [![Node Versions](https://img.shields.io/node/v/@revenium/perplexity.svg)](https://www.npmjs.com/package/@revenium/perplexity)
5
- [![Documentation](https://img.shields.io/badge/docs-available-brightgreen.svg)](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 Perplexity AI API usage with Revenium. This middleware provides seamless integration with Perplexity AI SDK, requiring minimal code changes.
9
-
10
- ## 🚀 Getting Started
11
-
12
- You have 3 options to start using Revenium middleware for Perplexity AI:
13
-
14
- | Option | Description | Best For |
15
- | ----------------------------------------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
16
- | **Option 1: Create Project from Scratch** | Perfect for new projects. We'll guide you step-by-step from mkdir to running tests. | 👉 [Go to Step-by-Step Guide](#option-1-create-project-from-scratch) |
17
- | **Option 2: Clone Our Repository** | Quick testing with pre-built examples and playground scripts. | 👉 [Go to Clone Guide](#option-2-clone-repository) |
18
- | **Option 3: Add to Existing Project** | Already have a project? Just install and replace imports. | 👉 [Go to Quick Integration](#option-3-existing-project-integration) |
19
-
20
- ---
21
-
22
- ## Option 1: Create Project from Scratch
23
-
24
- ### Step 1: Create Project Directory
25
-
26
- ```bash
27
- # Create and navigate to your project
28
- mkdir my-perplexity-ai-project
29
- cd my-perplexity-ai-project
30
-
31
- # Initialize Node.js project
32
- npm init -y
33
- ```
34
-
35
- ### Step 2: Install Dependencies
36
-
37
- ```bash
38
- npm install @revenium/perplexity
39
- ```
40
-
41
- ### Step 3: Setup Environment Variables
42
-
43
- Create a `.env` file in your project root:
44
-
45
- ```bash
46
- # Create .env file
47
- echo. > .env # On Windows (CMD TERMINAL)
48
- touch .env # On Mac/Linux (CMD TERMINAL)
49
- # OR
50
- #PowerShell
51
- New-Item -Path .env -ItemType File
52
- ```
53
-
54
- Copy and paste the following into `.env`:
55
-
56
- ```bash
57
- # Perplexity AI Configuration
58
- PERPLEXITY_API_KEY=your_perplexity_api_key_here
59
-
60
- # Revenium Configuration
61
- REVENIUM_METERING_API_KEY=your_revenium_api_key_here
62
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
63
-
64
- ```
65
-
66
- ### Step 4: Create Your First Test
67
-
68
- Create `test-perplexity.js`:
69
-
70
- ```javascript
71
- // test-perplexity.js
72
- import { createPerplexityClient } from "@revenium/perplexity";
73
-
74
- const client = createPerplexityClient();
75
-
76
- try {
77
- const result = await client.createChatCompletion({
78
- model: "sonar-pro",
79
- messages: [
80
- {
81
- role: "user",
82
- content: "What is the universe?",
83
- },
84
- ],
85
- });
86
-
87
- const text = result.choices[0]?.message?.content;
88
- console.log("*** RESPONSE ***");
89
- console.log(text);
90
- console.log("✅ Basic Perplexity AI example successful!");
91
- } catch (error) {
92
- console.error("❌ Perplexity basic example failed:", error);
93
- process.exit(1);
94
- }
95
- ```
96
-
97
- ### Step 5: Update package.json
98
-
99
- Add test scripts and module type to your `package.json`:
100
-
101
- ```json
102
- {
103
- "name": "my-perplexity-ai-project",
104
- "version": "1.0.0",
105
- "type": "module",
106
- "scripts": {
107
- "test-perplexity": "node test-perplexity.js"
108
- },
109
- "dependencies": {
110
- "@revenium/perplexity": "^1.0.0"
111
- }
112
- }
113
- ```
114
-
115
- ⚠️ **Important**: If you get this error when running tests:
116
-
117
- ```
118
- SyntaxError: Cannot use import statement outside a module
119
- ```
120
-
121
- Make sure your `package.json` includes `"type": "module"` as shown below.
122
-
123
- ```json
124
- {
125
- "type": "module"
126
- }
127
- ```
128
-
129
- ### Step 6: Run Your Tests
130
-
131
- ```bash
132
- # Test Perplexity AI SDK
133
- npm run test-perplexity
134
- ```
135
-
136
- ### Step 7: Create Advanced Examples
137
-
138
- Create an examples directory and add these files:
139
-
140
- ```bash
141
- mkdir examples
142
- ```
143
-
144
- #### Streaming Example
145
-
146
- Create `examples/streaming-perplexity.js`:
147
-
148
- ```javascript
149
- // examples/streaming-perplexity.js
150
- import { createPerplexityClient } from "@revenium/perplexity";
151
-
152
- const client = createPerplexityClient();
153
-
154
- try {
155
- const stream = await client.createStreamingChatCompletion({
156
- model: "sonar-pro",
157
- messages: [
158
- {
159
- role: "user",
160
- content: "What is artificial intelligence?",
161
- },
162
- ],
163
- });
164
-
165
- console.log("*** STREAMING RESPONSE ***");
166
- let fullText = "";
167
-
168
- for await (const chunk of stream) {
169
- const content = chunk.choices[0]?.delta?.content;
170
- if (content) {
171
- process.stdout.write(content);
172
- fullText += content;
173
- }
174
- }
175
-
176
- console.log("\n✅ Streaming with metering successful!");
177
- console.log(`📊 Total response length: ${fullText.length} characters`);
178
- } catch (error) {
179
- console.error("❌ Perplexity streaming example failed:", error);
180
- process.exit(1);
181
- }
182
- ```
183
-
184
- #### Metadata Example
185
-
186
- Create `examples/metadata-perplexity.js`:
187
-
188
- ```javascript
189
- // examples/metadata-perplexity.js
190
- import { createPerplexityClient } from "@revenium/perplexity";
191
-
192
- const client = createPerplexityClient();
193
-
194
- try {
195
- const result = await client.createChatCompletion({
196
- model: "sonar-pro",
197
- messages: [
198
- {
199
- role: "user",
200
- content: "Analyze this quarterly report",
201
- },
202
- ],
203
- usageMetadata: {
204
- // User tracking
205
- traceId: "conv-28a7e9d4",
206
- taskType: "document-analysis",
207
- subscriberEmail: "user@example.com",
208
- subscriberId: "user-123",
209
- subscriberCredentialName: "api-key-1",
210
-
211
- // Business context
212
- organizationId: "acme-corp",
213
- subscriptionId: "premium-plan",
214
- productId: "business-intelligence",
215
- agent: "analysis-assistant",
216
- responseQualityScore: 0.95,
217
- },
218
- });
219
-
220
- console.log("*** METADATA RESPONSE ***");
221
- console.log("Response:", result.choices[0]?.message?.content);
222
- console.log("✅ Metadata tracking with metering successful!");
223
- } catch (error) {
224
- console.error("❌ Perplexity metadata example failed:", error);
225
- process.exit(1);
226
- }
227
- ```
228
-
229
- ### Step 8: Update package.json
230
-
231
- ```json
232
- {
233
- "name": "my-perplexity-ai-project",
234
- "version": "1.0.0",
235
- "type": "module",
236
- "scripts": {
237
- "test-perplexity": "node test-perplexity.js",
238
- "test-perplexity-stream": "node examples/streaming-perplexity.js",
239
- "test-perplexity-metadata": "node examples/metadata-perplexity.js"
240
- },
241
- "dependencies": {
242
- "@revenium/perplexity": "^1.0.0"
243
- }
244
- }
245
- ```
246
-
247
- ### Step 9: Test Advanced Examples
248
-
249
- ```bash
250
- # Test streaming
251
- npm run test-perplexity-stream
252
-
253
- # Test metadata
254
- npm run test-perplexity-metadata
255
- ```
256
-
257
- ---
258
-
259
- ## Option 2: Clone Repository
260
-
261
- Perfect for testing with pre-built examples:
262
-
263
- ```bash
264
- # Clone the repository
265
- git clone git@github.com:revenium/revenium-middleware-perplexity-node.git
266
- cd revenium-middleware-perplexity-node
267
-
268
- # Install dependencies
269
- npm install
270
-
271
- # Create your .env file
272
- cp .env.example .env
273
- # Edit .env with your API keys
274
- ```
275
-
276
- ### Configure Environment Variables
277
-
278
- Edit your `.env` file:
279
-
280
- ```bash
281
- # For Perplexity AI SDK
282
- PERPLEXITY_API_KEY=your_perplexity_api_key_here
283
- REVENIUM_METERING_API_KEY=your_revenium_api_key_here
284
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
285
- ```
286
-
287
- ### Run Perplexity AI Examples
288
-
289
- ```bash
290
- # Perplexity AI examples
291
- npm run p-basic # Basic chat completion
292
- npm run p-streaming # Streaming response
293
- npm run p-metadata # Rich metadata tracking
294
-
295
- # Playground examples
296
- # Required build first
297
- npm run build
298
- # Then run any of the following
299
- npm run p-perplexity-basic
300
- npm run p-perplexity-streaming
301
- npm run p-perplexity-metadata
302
- ```
303
-
304
- ---
305
-
306
- ## Option 3: Existing Project Integration
307
-
308
- Already have a project? Just install and replace imports:
309
-
310
- ### Step 1. Install the Package
311
-
312
- ```bash
313
- npm install @revenium/perplexity
314
- ```
315
-
316
- ### Step 2. Add Environment Variables
317
-
318
- Add to your existing `.env` file:
319
-
320
- ```bash
321
- PERPLEXITY_API_KEY=your_perplexity_api_key_here
322
- REVENIUM_METERING_API_KEY=your_revenium_api_key_here
323
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
324
- # Optional: Enable debug logging
325
- REVENIUM_LOG_LEVEL=INFO
326
- ```
327
-
328
- ### Step 3. Replace Your Imports
329
-
330
- **Before:**
331
-
332
- ```javascript
333
- import { OpenAI } from "openai";
334
- ```
335
-
336
- **After:**
337
-
338
- ```javascript
339
- import { createPerplexityClient } from "@revenium/perplexity";
340
- ```
341
-
342
- **Or Use OpenAI Client (Alternative):**
343
-
344
- ```javascript
345
- import { OpenAI } from "openai";
346
- import "@revenium/perplexity"; // Import middleware to activate tracking
347
- ```
348
-
349
- ### Step 4. Update Your Code
350
-
351
- #### Revenium Client Example
352
-
353
- ```javascript
354
- import { createPerplexityClient } from "@revenium/perplexity";
355
-
356
- // Initialize (API key from environment variable)
357
- const client = createPerplexityClient();
358
-
359
- // Make your request - metering happens automatically!
360
- const result = await client.createChatCompletion({
361
- model: "sonar-pro",
362
- messages: [{ role: "user", content: "What is artificial intelligence?" }],
363
- });
364
- console.log(result.choices[0]?.message?.content);
365
- ```
366
-
367
- #### OpenAI Client Example
368
-
369
- ```javascript
370
- import { OpenAI } from "openai";
371
- import "@revenium/perplexity"; // Import middleware for automatic tracking
372
-
373
- // Initialize OpenAI client for Perplexity
374
- const client = new OpenAI({
375
- apiKey: process.env.PERPLEXITY_API_KEY,
376
- baseURL: "https://api.perplexity.ai",
377
- });
378
-
379
- // Make your request - metering happens automatically!
380
- const result = await client.chat.completions.create({
381
- model: "sonar-pro",
382
- messages: [{ role: "user", content: "What is artificial intelligence?" }],
383
- });
384
- console.log(result.choices[0]?.message?.content);
385
- ```
386
-
387
- ---
388
-
389
- ## 🔧 Advanced Usage
390
-
391
- ### Streaming Responses
392
-
393
- #### Revenium Client Streaming
394
-
395
- ```javascript
396
- const stream = await client.createStreamingChatCompletion({
397
- model: "sonar-pro",
398
- messages: [{ role: "user", content: "Write a story about AI" }],
399
- });
400
-
401
- for await (const chunk of stream) {
402
- const content = chunk.choices[0]?.delta?.content;
403
- if (content) process.stdout.write(content);
404
- }
405
- ```
406
-
407
- #### OpenAI Client Streaming
408
-
409
- ```javascript
410
- import { OpenAI } from "openai";
411
- import "@revenium/perplexity";
412
-
413
- const client = new OpenAI({
414
- apiKey: process.env.PERPLEXITY_API_KEY,
415
- baseURL: "https://api.perplexity.ai",
416
- });
417
-
418
- const stream = await client.chat.completions.create({
419
- model: "sonar-pro",
420
- messages: [{ role: "user", content: "Write a story about AI" }],
421
- stream: true,
422
- });
423
-
424
- for await (const chunk of stream) {
425
- const content = chunk.choices[0]?.delta?.content;
426
- if (content) process.stdout.write(content);
427
- }
428
- ```
429
-
430
- ### Rich Metadata Tracking
431
-
432
- ```javascript
433
- import { createPerplexityClient } from "@revenium/perplexity";
434
-
435
- const client = createPerplexityClient();
436
-
437
- const response = await client.createChatCompletion({
438
- model: "sonar-pro",
439
- messages: [
440
- {
441
- role: "user",
442
- content: "Analyze this quarterly report",
443
- },
444
- ],
445
- usageMetadata: {
446
- // User tracking
447
- traceId: "conv-28a7e9d4",
448
- taskType: "document-analysis",
449
- subscriberEmail: "user@example.com",
450
- subscriberId: "user-123",
451
- subscriberCredentialName: "api-key-1",
452
-
453
- // Business context
454
- organizationId: "acme-corp",
455
- subscriptionId: "premium-plan",
456
- productId: "business-intelligence",
457
- agent: "analysis-assistant",
458
- responseQualityScore: 0.95,
459
- },
460
- });
461
- ```
462
-
463
- ---
464
-
465
- ## 📊 What Gets Tracked
466
-
467
- - **Token Usage**: Input and output tokens for accurate billing
468
- - **Request Duration**: Total time for each API call
469
- - **Model Information**: Which model was used
470
- - **Operation Type**: Chat completion, streaming
471
- - **Error Tracking**: Failed requests and error details
472
- - **Streaming Metrics**: Time to first token for streaming responses
473
- - **Custom Metadata**: Rich business context and user tracking
474
-
475
- ---
476
-
477
- ## 🔗 Supported Models
478
-
479
- ### Chat Models
480
-
481
- - **sonar-pro** (Latest and most capable)
482
- - **sonar-small** (Fast and efficient)
483
- - **sonar-medium** (Balanced performance)
484
-
485
- _Note: Model availability depends on your Perplexity AI account and API access level._
486
-
487
- ---
488
-
489
- ## 🛠️ Configuration Options
490
-
491
- ### Environment Variables
492
-
493
- | Variable | Required | Description |
494
- | ---------------------------- | -------- | --------------------------------------------------------------- |
495
- | `PERPLEXITY_API_KEY` | ✅ | Your Perplexity API key |
496
- | `REVENIUM_METERING_API_KEY` | ✅ | Your Revenium API key |
497
- | `PERPLEXITY_BASE_URL` | ❌ | Custom Perplexity base URL (default: https://api.perplexity.ai) |
498
- | `REVENIUM_METERING_BASE_URL` | ❌ | Revenium base URL (default: https://api.revenium.io/meter/v2) |
499
- | `REVENIUM_LOG_LEVEL` | ❌ | Log level: DEBUG, INFO, WARNING, ERROR |
500
-
501
- ### Manual Configuration
502
-
503
- ```javascript
504
- // Revenium client with custom configuration
505
- const client = createPerplexityClient(
506
- "your-api-key",
507
- "https://api.perplexity.ai"
508
- );
509
-
510
- // OpenAI client with custom base URL
511
- const openaiClient = new OpenAI({
512
- apiKey: "your-api-key",
513
- baseURL: "https://custom-perplexity-endpoint.com",
514
- });
515
- ```
516
-
517
- ---
518
-
519
- ## 🚨 Troubleshooting
520
-
521
- ### Common Issues
522
-
523
- **"Missing API Key" Error**
524
-
525
- ```bash
526
- export PERPLEXITY_API_KEY="your-actual-api-key"
527
- echo $PERPLEXITY_API_KEY # Verify it's set
528
- ```
529
-
530
- **"Requests not being tracked"**
531
-
532
- ```bash
533
- export REVENIUM_METERING_API_KEY="your-actual-revenium-key"
534
- export REVENIUM_LOG_LEVEL="DEBUG" # Enable debug logging
535
- ```
536
-
537
- **Module Import Errors**
538
-
539
- ```json
540
- {
541
- "type": "module"
542
- }
543
- ```
544
-
545
- ### Debug Mode
546
-
547
- Enable detailed logging to troubleshoot issues:
548
-
549
- ```bash
550
- export REVENIUM_LOG_LEVEL="DEBUG"
551
- export REVENIUM_VERBOSE_STARTUP="true"
552
- node your-script.js
553
- ```
554
-
555
- This will show:
556
-
557
- - Request/response details
558
- - Token counting information
559
- - Metering data being sent
560
- - Error details
561
- - Middleware activation status
562
-
563
- ---
564
-
565
- ## 📚 Examples Repository
566
-
567
- Check out our comprehensive examples:
568
-
569
- - **Basic Usage**: Simple chat completions
570
- - **Streaming**: Real-time response streaming
571
- - **Metadata**: Rich tracking examples
572
- - **Error Handling**: Robust error management
573
- - **Advanced Patterns**: Complex use cases
574
- - **Configuration**: Different setup options
575
-
576
- All examples are in the `/examples` and `/playground` directories.
577
-
578
- ---
579
-
580
- ## 📋 Requirements
581
-
582
- - Node.js 18+
583
- - Perplexity API key
584
- - Revenium API key
585
-
586
- ---
587
-
588
- ## 📄 License
589
-
590
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
591
-
592
- ---
593
-
594
- ## 🤝 Support
595
-
596
- - 📖 [Documentation](https://docs.revenium.io)
597
- - 💬 [Community Support](https://community.revenium.io)
598
- - 📧 [Email Support](mailto:support@revenium.io)
599
- - 🐛 [Report Issues](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
600
-
601
- ---
602
-
603
- **Built with ❤️ by Revenium**
1
+ # Revenium Middleware for Perplexity AI (Node.js)
2
+
3
+ [![npm version](https://badge.fury.io/js/%40revenium%2Fperplexity.svg)](https://badge.fury.io/js/%40revenium%2Fperplexity)
4
+ [![Node Versions](https://img.shields.io/node/v/@revenium/perplexity.svg)](https://www.npmjs.com/package/@revenium/perplexity)
5
+ [![Documentation](https://img.shields.io/badge/docs-available-brightgreen.svg)](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 Perplexity AI API usage with Revenium. This middleware provides seamless integration with Perplexity AI SDK, requiring minimal code changes.
9
+
10
+ ## 🚀 Getting Started
11
+
12
+ You have 3 options to start using Revenium middleware for Perplexity AI:
13
+
14
+ | Option | Description | Best For |
15
+ | ----------------------------------------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
16
+ | **Option 1: Create Project from Scratch** | Perfect for new projects. We'll guide you step-by-step from mkdir to running tests. | 👉 [Go to Step-by-Step Guide](#option-1-create-project-from-scratch) |
17
+ | **Option 2: Clone Our Repository** | Quick testing with pre-built examples and playground scripts. | 👉 [Go to Clone Guide](#option-2-clone-repository) |
18
+ | **Option 3: Add to Existing Project** | Already have a project? Just install and replace imports. | 👉 [Go to Quick Integration](#option-3-existing-project-integration) |
19
+
20
+ ---
21
+
22
+ ## Option 1: Create Project from Scratch
23
+
24
+ ### Step 1: Create Project Directory
25
+
26
+ ```bash
27
+ # Create and navigate to your project
28
+ mkdir my-perplexity-ai-project
29
+ cd my-perplexity-ai-project
30
+
31
+ # Initialize Node.js project
32
+ npm init -y
33
+ ```
34
+
35
+ ### Step 2: Install Dependencies
36
+
37
+ ```bash
38
+ npm install @revenium/perplexity
39
+ ```
40
+
41
+ ### Step 3: Setup Environment Variables
42
+
43
+ Create a `.env` file in your project root:
44
+
45
+ ```bash
46
+ # Create .env file
47
+ echo. > .env # On Windows (CMD TERMINAL)
48
+ touch .env # On Mac/Linux (CMD TERMINAL)
49
+ # OR
50
+ #PowerShell
51
+ New-Item -Path .env -ItemType File
52
+ ```
53
+
54
+ Copy and paste the following into `.env`:
55
+
56
+ ```bash
57
+ # Perplexity AI Configuration
58
+ PERPLEXITY_API_KEY="your_perplexity_api_key_here"
59
+
60
+ # Revenium Configuration
61
+ REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
62
+ REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
63
+
64
+ ```
65
+
66
+ ### Step 4: Create Your First Test
67
+
68
+ Create `test-perplexity.js`:
69
+
70
+ ```javascript
71
+ // test-perplexity.js
72
+ import { createPerplexityClient } from "@revenium/perplexity";
73
+
74
+ const client = createPerplexityClient();
75
+
76
+ try {
77
+ const result = await client.createChatCompletion({
78
+ model: "sonar-pro",
79
+ messages: [
80
+ {
81
+ role: "user",
82
+ content: "What is the universe?",
83
+ },
84
+ ],
85
+ });
86
+
87
+ const text = result.choices[0]?.message?.content;
88
+ console.log("*** RESPONSE ***");
89
+ console.log(text);
90
+ console.log("✅ Basic Perplexity AI example successful!");
91
+ } catch (error) {
92
+ console.error("❌ Perplexity basic example failed:", error);
93
+ process.exit(1);
94
+ }
95
+ ```
96
+
97
+ ### Step 5: Update package.json
98
+
99
+ Add test scripts and module type to your `package.json`:
100
+
101
+ ```json
102
+ {
103
+ "name": "my-perplexity-ai-project",
104
+ "version": "1.0.0",
105
+ "type": "module",
106
+ "scripts": {
107
+ "test-perplexity": "node test-perplexity.js"
108
+ },
109
+ "dependencies": {
110
+ "@revenium/perplexity": "^1.0.0"
111
+ }
112
+ }
113
+ ```
114
+
115
+ ⚠️ **Important**: If you get this error when running tests:
116
+
117
+ ```
118
+ SyntaxError: Cannot use import statement outside a module
119
+ ```
120
+
121
+ Make sure your `package.json` includes `"type": "module"` as shown below.
122
+
123
+ ```json
124
+ {
125
+ "type": "module"
126
+ }
127
+ ```
128
+
129
+ ### Step 6: Run Your Tests
130
+
131
+ ```bash
132
+ # Test Perplexity AI SDK
133
+ npm run test-perplexity
134
+ ```
135
+
136
+ ### Step 7: Create Advanced Examples
137
+
138
+ Create an examples directory and add these files:
139
+
140
+ ```bash
141
+ mkdir examples
142
+ ```
143
+
144
+ #### Streaming Example
145
+
146
+ Create `examples/streaming-perplexity.js`:
147
+
148
+ ```javascript
149
+ // examples/streaming-perplexity.js
150
+ import { createPerplexityClient } from "@revenium/perplexity";
151
+
152
+ const client = createPerplexityClient();
153
+
154
+ try {
155
+ const stream = await client.createStreamingChatCompletion({
156
+ model: "sonar-pro",
157
+ messages: [
158
+ {
159
+ role: "user",
160
+ content: "What is artificial intelligence?",
161
+ },
162
+ ],
163
+ });
164
+
165
+ console.log("*** STREAMING RESPONSE ***");
166
+ let fullText = "";
167
+
168
+ for await (const chunk of stream) {
169
+ const content = chunk.choices[0]?.delta?.content;
170
+ if (content) {
171
+ process.stdout.write(content);
172
+ fullText += content;
173
+ }
174
+ }
175
+
176
+ console.log("\n✅ Streaming with metering successful!");
177
+ console.log(`📊 Total response length: ${fullText.length} characters`);
178
+ } catch (error) {
179
+ console.error("❌ Perplexity streaming example failed:", error);
180
+ process.exit(1);
181
+ }
182
+ ```
183
+
184
+ ### Step 8: Update package.json
185
+
186
+ ```json
187
+ {
188
+ "name": "my-perplexity-ai-project",
189
+ "version": "1.0.0",
190
+ "type": "module",
191
+ "scripts": {
192
+ "test-perplexity": "node test-perplexity.js",
193
+ "test-perplexity-stream": "node examples/streaming-perplexity.js"
194
+ },
195
+ "dependencies": {
196
+ "@revenium/perplexity": "^1.0.0"
197
+ }
198
+ }
199
+ ```
200
+
201
+ ### Step 9: Test Advanced Examples
202
+
203
+ ```bash
204
+ # Test streaming
205
+ npm run test-perplexity-stream
206
+
207
+ ```
208
+
209
+ ---
210
+
211
+ ## Option 2: Clone Repository
212
+
213
+ Perfect for testing with pre-built examples:
214
+
215
+ ```bash
216
+ # Clone the repository
217
+ git clone git@github.com:revenium/revenium-middleware-perplexity-node.git
218
+ cd revenium-middleware-perplexity-node
219
+
220
+ # Install dependencies
221
+ npm install
222
+ npm install @revenium/perplexity
223
+
224
+ # Create your .env file
225
+ cp .env.example .env
226
+ # Edit .env with your API keys
227
+ ```
228
+
229
+ ### Configure Environment Variables
230
+
231
+ Edit your `.env` file:
232
+
233
+ ```bash
234
+ # For Perplexity AI SDK
235
+ PERPLEXITY_API_KEY="your_perplexity_api_key_here"
236
+ REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
237
+ REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
238
+ ```
239
+
240
+ ### Run Perplexity AI Examples
241
+
242
+ ```bash
243
+ # Perplexity AI examples
244
+
245
+ npm run e-basic # Basic chat completion
246
+ npm run e-streaming # Streaming response
247
+ npm run e-enhanced # Enhanced request
248
+ npm run e-chat-completions # Chat completions
249
+
250
+ # Playground examples
251
+ # Required build first
252
+ npm run build
253
+ # Then run any of the following
254
+ npm run p-basic
255
+ npm run p-streaming
256
+ npm run p-enhanced
257
+ ```
258
+
259
+ ---
260
+
261
+ ## Option 3: Existing Project Integration
262
+
263
+ Already have a project? Just install and replace imports:
264
+
265
+ ### Step 1. Install the Package
266
+
267
+ ```bash
268
+ npm install @revenium/perplexity
269
+ ```
270
+
271
+ ### Step 2. Add Environment Variables
272
+
273
+ Add to your existing `.env` file:
274
+
275
+ ```bash
276
+ PERPLEXITY_API_KEY="your_perplexity_api_key_here"
277
+ REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
278
+ REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
279
+ ```
280
+
281
+ ### Step 3. Replace Your Imports
282
+
283
+ **Before:**
284
+
285
+ ```javascript
286
+ import { OpenAI } from "openai";
287
+ ```
288
+
289
+ **After:**
290
+
291
+ ```javascript
292
+ import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
293
+ ```
294
+
295
+ ### Step 4. Update Your Code
296
+
297
+ #### Revenium Client Example
298
+
299
+ ```javascript
300
+ import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
301
+
302
+ // Initialize (API key from environment variable)
303
+ const middleware = new PerplexityReveniumMiddleware();
304
+ const model = middleware.getGenerativeModel("sonar-pro");
305
+ const result = await model.createChatCompletion({
306
+ messages: [
307
+ {
308
+ role: "user",
309
+ content: "Hello world",
310
+ },
311
+ ],
312
+ });
313
+ console.log("[BASIC EXAMPLE]", result.choices[0].message.content);
314
+ ```
315
+
316
+ ---
317
+
318
+ ## 🔧 Advanced Usage
319
+
320
+ ### Streaming Responses
321
+
322
+ #### Revenium Client Streaming
323
+
324
+ ```javascript
325
+ const stream = await model.createChatCompletionStream({
326
+ messages: [
327
+ {
328
+ role: "user",
329
+ content: "Hello world",
330
+ },
331
+ ],
332
+ });
333
+ for await (const chunk of stream) {
334
+ process.stdout.write(chunk.choices[0]?.delta?.content || "");
335
+ }
336
+ ```
337
+
338
+ ## 📊 What Gets Tracked
339
+
340
+ - **Token Usage**: Input and output tokens for accurate billing
341
+ - **Request Duration**: Total time for each API call
342
+ - **Model Information**: Which model was used
343
+ - **Operation Type**: Chat completion, streaming
344
+ - **Error Tracking**: Failed requests and error details
345
+ - **Streaming Metrics**: Time to first token for streaming responses
346
+ - **Custom Metadata**: Rich business context and user tracking
347
+
348
+ ---
349
+
350
+ ## 🔗 Supported Models
351
+
352
+ ### Chat Models
353
+
354
+ - **sonar-pro** (Latest and most capable)
355
+ - **sonar-small** (Fast and efficient)
356
+ - **sonar-medium** (Balanced performance)
357
+
358
+ _Note: Model availability depends on your Perplexity AI account and API access level._
359
+
360
+ ---
361
+
362
+ ## 🛠️ Configuration Options
363
+
364
+ ### Environment Variables
365
+
366
+ | Variable | Required | Description |
367
+ | ---------------------------- | -------- | ---------------------------------------------------------- |
368
+ | `PERPLEXITY_API_KEY` | ✅ | Your Perplexity API key |
369
+ | `REVENIUM_METERING_API_KEY` | ✅ | Your Revenium API key |
370
+ | `REVENIUM_METERING_BASE_URL` | ❌ | Revenium base URL (default: https://api.revenium.io/meter) |
371
+
372
+ ---
373
+
374
+ ## 🚨 Troubleshooting
375
+
376
+ ### Common Issues
377
+
378
+ **"Missing API Key" Error**
379
+
380
+ ```bash
381
+ export PERPLEXITY_API_KEY="your-actual-api-key"
382
+ echo $PERPLEXITY_API_KEY # Verify it's set
383
+ ```
384
+
385
+ **"Requests not being tracked"**
386
+
387
+ ```bash
388
+ export REVENIUM_METERING_API_KEY="your-actual-revenium-key"
389
+ ```
390
+
391
+ **Module Import Errors**
392
+
393
+ ```json
394
+ {
395
+ "type": "module"
396
+ }
397
+ ```
398
+
399
+ This will show:
400
+
401
+ - Request/response details
402
+ - Token counting information
403
+ - Metering data being sent
404
+ - Error details
405
+ - Middleware activation status
406
+
407
+ ---
408
+
409
+ ## 📚 Examples Repository
410
+
411
+ Check out our comprehensive examples:
412
+
413
+ - **Basic Usage**: Simple chat completions
414
+ - **Streaming**: Real-time response streaming
415
+ - **Metadata**: Rich tracking examples
416
+ - **Error Handling**: Robust error management
417
+ - **Advanced Patterns**: Complex use cases
418
+ - **Configuration**: Different setup options
419
+
420
+ All examples are in the `/examples` and `/playground` directories.
421
+
422
+ ---
423
+
424
+ ## 📋 Requirements
425
+
426
+ - Node.js 18+
427
+ - Perplexity API key
428
+ - Revenium API key
429
+
430
+ ---
431
+
432
+ ## 📄 License
433
+
434
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
435
+
436
+ ---
437
+
438
+ ## 🤝 Support
439
+
440
+ - 📖 [Documentation](https://docs.revenium.com)
441
+ - 💬 [Community Support](https://community.revenium.com)
442
+ - 📧 [Email Support](mailto:support@revenium.com)
443
+ - 🐛 [Report Issues](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
444
+
445
+ ---
446
+
447
+ **Built with ❤️ by Revenium**