@revenium/perplexity 2.0.2 → 2.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -21
  3. package/README.md +271 -625
  4. package/dist/cjs/constants.js +70 -0
  5. package/dist/cjs/constants.js.map +1 -0
  6. package/dist/cjs/core/tracking/metering.js +86 -6
  7. package/dist/cjs/core/tracking/metering.js.map +1 -1
  8. package/dist/cjs/core/wrapper/perplexity-client.js +11 -1
  9. package/dist/cjs/core/wrapper/perplexity-client.js.map +1 -1
  10. package/dist/cjs/index.js +9 -4
  11. package/dist/cjs/index.js.map +1 -1
  12. package/dist/cjs/types/index.js +0 -15
  13. package/dist/cjs/types/index.js.map +1 -1
  14. package/dist/esm/constants.js +67 -0
  15. package/dist/esm/constants.js.map +1 -0
  16. package/dist/esm/core/tracking/metering.js +86 -6
  17. package/dist/esm/core/tracking/metering.js.map +1 -1
  18. package/dist/esm/core/wrapper/perplexity-client.js +11 -1
  19. package/dist/esm/core/wrapper/perplexity-client.js.map +1 -1
  20. package/dist/esm/index.js +4 -1
  21. package/dist/esm/index.js.map +1 -1
  22. package/dist/esm/types/index.js +1 -14
  23. package/dist/esm/types/index.js.map +1 -1
  24. package/dist/types/constants.d.ts +67 -0
  25. package/dist/types/constants.d.ts.map +1 -0
  26. package/dist/types/core/tracking/metering.d.ts.map +1 -1
  27. package/dist/types/index.d.ts +2 -2
  28. package/dist/types/index.d.ts.map +1 -1
  29. package/dist/types/types/index.d.ts +3 -11
  30. package/dist/types/types/index.d.ts.map +1 -1
  31. package/examples/README.md +322 -0
  32. package/examples/advanced-features.ts +148 -0
  33. package/examples/basic.ts +50 -0
  34. package/examples/chat.ts +73 -0
  35. package/examples/getting_started.ts +64 -0
  36. package/examples/metadata.ts +65 -0
  37. package/examples/streaming.ts +50 -0
  38. package/package.json +72 -69
package/README.md CHANGED
@@ -1,625 +1,271 @@
1
- # Revenium Middleware for Perplexity
2
-
3
- A lightweight, production-ready middleware that adds **Revenium metering and tracking** to Perplexity AI API calls.
4
-
5
- [![npm version](https://img.shields.io/npm/v/@revenium/perplexity.svg)](https://www.npmjs.com/package/@revenium/perplexity)
6
- [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)
7
-
8
- ## 🚀 Features
9
-
10
- - ✅ **Zero Configuration** - Works out of the box with environment variables
11
- - ✅ **Automatic Metering** - Tracks all API calls with detailed usage metrics
12
- - ✅ **Streaming Support** - Full support for streaming responses
13
- - **TypeScript First** - Built with TypeScript, includes full type definitions
14
- - **Multi-Format** - Supports both ESM and CommonJS
15
- - **Custom Metadata** - Add custom tracking metadata to any request
16
- - **Production Ready** - Battle-tested and optimized for production use
17
-
18
- ## 📋 Table of Contents
19
-
20
- - [Installation](https://github.com/revenium/revenium-middleware-perplexity-node#-installation)
21
- - [Three Ways to Use This Middleware](https://github.com/revenium/revenium-middleware-perplexity-node#-three-ways-to-use-this-middleware)
22
- - [Option 1: New Project with npm Package](https://github.com/revenium/revenium-middleware-perplexity-node#option-1-new-project-with-npm-package-recommended)
23
- - [Option 2: Clone and Use Locally](https://github.com/revenium/revenium-middleware-perplexity-node#option-2-clone-and-use-locally)
24
- - [Option 3: Add to Existing Project](https://github.com/revenium/revenium-middleware-perplexity-node#option-3-add-to-existing-project)
25
- - [Quick Start](https://github.com/revenium/revenium-middleware-perplexity-node#-quick-start)
26
- - [API Reference](https://github.com/revenium/revenium-middleware-perplexity-node#-api-reference)
27
- - [Examples](https://github.com/revenium/revenium-middleware-perplexity-node#-examples)
28
- - [Environment Variables](https://github.com/revenium/revenium-middleware-perplexity-node#-environment-variables)
29
-
30
- ## 📦 Installation
31
-
32
- ```bash
33
- npm install @revenium/perplexity
34
- ```
35
-
36
- ## 🎯 Three Ways to Use This Middleware
37
-
38
- ### Option 1: New Project with npm Package (Recommended)
39
-
40
- **Best for:** Starting a new project or adding Perplexity with Revenium to an existing project.
41
-
42
- #### Step 1: Create a new project
43
-
44
- ```bash
45
- mkdir my-perplexity-project
46
- cd my-perplexity-project
47
- npm init -y
48
- ```
49
-
50
- #### Step 2: Install the middleware
51
-
52
- ```bash
53
- npm install @revenium/perplexity dotenv
54
- ```
55
-
56
- #### Step 3: Create `.env` file
57
-
58
- ```env
59
- # Perplexity API Configuration
60
- PERPLEXITY_API_KEY=your_perplexity_api_key
61
-
62
- # Revenium Metering Configuration
63
- REVENIUM_METERING_API_KEY=your_revenium_api_key
64
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
65
- ```
66
-
67
- #### Step 4: Create `index.js`
68
-
69
- ```javascript
70
- const {
71
- initializeReveniumFromEnv,
72
- initializePerplexityFromEnv,
73
- createChatCompletion,
74
- PERPLEXITY_MODELS,
75
- } = require("@revenium/perplexity");
76
-
77
- async function main() {
78
- // Initialize configurations
79
- initializeReveniumFromEnv();
80
- initializePerplexityFromEnv();
81
-
82
- // Create a chat completion
83
- const result = await createChatCompletion({
84
- messages: [{ role: "user", content: "What is the capital of France?" }],
85
- model: PERPLEXITY_MODELS.SONAR_PRO,
86
- });
87
-
88
- console.log("Response:", result.content);
89
- console.log("Tokens used:", result.usage.totalTokens);
90
- }
91
-
92
- main().catch(console.error);
93
- ```
94
-
95
- #### Step 5: Run your project
96
-
97
- ```bash
98
- node index.js
99
- ```
100
-
101
- ---
102
-
103
- ### Option 2: Clone and Use Locally
104
-
105
- **Best for:** Development, testing, or contributing to the middleware.
106
-
107
- #### Step 1: Clone the repository
108
-
109
- ```bash
110
- git clone https://github.com/revenium/revenium-middleware-perplexity-node.git
111
- cd revenium-middleware-perplexity-node
112
- ```
113
-
114
- #### Step 2: Install dependencies
115
-
116
- ```bash
117
- npm install
118
- ```
119
-
120
- #### Step 3: Create `.env` file
121
-
122
- ```env
123
- # Perplexity API Configuration
124
- PERPLEXITY_API_KEY=your_perplexity_api_key
125
-
126
- # Revenium Metering Configuration
127
- REVENIUM_METERING_API_KEY=your_revenium_api_key
128
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
129
- ```
130
-
131
- #### Step 4: Build the project
132
-
133
- ```bash
134
- npm run build
135
- ```
136
-
137
- #### Step 5: Run examples
138
-
139
- **TypeScript Examples:**
140
-
141
- ```bash
142
- npm run example:basic # Basic chat completion
143
- npm run example:streaming # Streaming response
144
- npm run example:chat # Multi-turn conversation
145
- npm run example:metadata # Custom metadata
146
- ```
147
-
148
- **JavaScript Playground:**
149
-
150
- ```bash
151
- npm run playground:basic # Basic chat completion
152
- npm run playground:streaming # Streaming response
153
- npm run playground:chat # Multi-turn conversation
154
- npm run playground:metadata # Custom metadata
155
- ```
156
-
157
- #### Step 6: Use in your own code
158
-
159
- After building, you can import from the local build:
160
-
161
- ```javascript
162
- const {
163
- initializeReveniumFromEnv,
164
- initializePerplexityFromEnv,
165
- createChatCompletion,
166
- } = require("./dist/cjs");
167
-
168
- // Your code here...
169
- ```
170
-
171
- ---
172
-
173
- ### Option 3: Add to Existing Project
174
-
175
- **Best for:** Integrating Perplexity with Revenium into an existing Node.js project.
176
-
177
- #### Step 1: Install the middleware
178
-
179
- ```bash
180
- npm install @revenium/perplexity
181
- ```
182
-
183
- #### Step 2: Add environment variables
184
-
185
- Add to your existing `.env` file:
186
-
187
- ```env
188
- # Perplexity API Configuration
189
- PERPLEXITY_API_KEY=your_perplexity_api_key
190
-
191
- # Revenium Metering Configuration
192
- REVENIUM_METERING_API_KEY=your_revenium_api_key
193
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
194
- ```
195
-
196
- #### Step 3: Initialize in your application
197
-
198
- **For CommonJS projects:**
199
-
200
- ```javascript
201
- require("dotenv").config();
202
- const {
203
- initializeReveniumFromEnv,
204
- initializePerplexityFromEnv,
205
- createChatCompletion,
206
- PERPLEXITY_MODELS,
207
- } = require("@revenium/perplexity");
208
-
209
- // Initialize once at app startup
210
- initializeReveniumFromEnv();
211
- initializePerplexityFromEnv();
212
-
213
- // Use anywhere in your app
214
- async function askPerplexity(question) {
215
- const result = await createChatCompletion({
216
- messages: [{ role: "user", content: question }],
217
- model: PERPLEXITY_MODELS.SONAR_PRO,
218
- });
219
- return result.content;
220
- }
221
- ```
222
-
223
- **For ES Modules projects:**
224
-
225
- ```javascript
226
- import "dotenv/config";
227
- import {
228
- initializeReveniumFromEnv,
229
- initializePerplexityFromEnv,
230
- createChatCompletion,
231
- PERPLEXITY_MODELS,
232
- } from "@revenium/perplexity";
233
-
234
- // Initialize once at app startup
235
- initializeReveniumFromEnv();
236
- initializePerplexityFromEnv();
237
-
238
- // Use anywhere in your app
239
- export async function askPerplexity(question) {
240
- const result = await createChatCompletion({
241
- messages: [{ role: "user", content: question }],
242
- model: PERPLEXITY_MODELS.SONAR_PRO,
243
- });
244
- return result.content;
245
- }
246
- ```
247
-
248
- **For TypeScript projects:**
249
-
250
- ```typescript
251
- import "dotenv/config";
252
- import {
253
- initializeReveniumFromEnv,
254
- initializePerplexityFromEnv,
255
- createChatCompletion,
256
- PERPLEXITY_MODELS,
257
- type ChatCompletionResult,
258
- } from "@revenium/perplexity";
259
-
260
- // Initialize once at app startup
261
- initializeReveniumFromEnv();
262
- initializePerplexityFromEnv();
263
-
264
- // Use anywhere in your app
265
- export async function askPerplexity(question: string): Promise<string> {
266
- const result: ChatCompletionResult = await createChatCompletion({
267
- messages: [{ role: "user", content: question }],
268
- model: PERPLEXITY_MODELS.SONAR_PRO,
269
- });
270
- return result.content;
271
- }
272
- ```
273
-
274
- ---
275
-
276
- ## 🔧 Quick Start
277
-
278
- ### 1. Set up environment variables
279
-
280
- Create a `.env` file in your project root:
281
-
282
- ```env
283
- # Perplexity API Configuration
284
- PERPLEXITY_API_KEY=your_perplexity_api_key
285
-
286
- # Revenium Metering Configuration
287
- REVENIUM_METERING_API_KEY=your_revenium_api_key
288
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
289
- ```
290
-
291
- ### 2. Initialize and use
292
-
293
- ```typescript
294
- import {
295
- initializeReveniumFromEnv,
296
- initializePerplexityFromEnv,
297
- createChatCompletion,
298
- PERPLEXITY_MODELS,
299
- } from "@revenium/perplexity";
300
-
301
- // Initialize configurations
302
- initializeReveniumFromEnv();
303
- initializePerplexityFromEnv();
304
-
305
- // Create a chat completion
306
- const result = await createChatCompletion({
307
- messages: [{ role: "user", content: "What is the capital of France?" }],
308
- model: PERPLEXITY_MODELS.SONAR_PRO,
309
- });
310
-
311
- console.log(result.content);
312
- // Output: "The capital of France is Paris."
313
- ```
314
-
315
- ## 📚 API Reference
316
-
317
- ### Configuration
318
-
319
- #### `initializeReveniumFromEnv()`
320
-
321
- Initialize Revenium configuration from environment variables.
322
-
323
- ```typescript
324
- const config = initializeReveniumFromEnv();
325
- ```
326
-
327
- #### `initializePerplexityFromEnv()`
328
-
329
- Initialize Perplexity configuration from environment variables.
330
-
331
- ```typescript
332
- const config = initializePerplexityFromEnv();
333
- ```
334
-
335
- #### `initializeRevenium(config)`
336
-
337
- Initialize Revenium with custom configuration.
338
-
339
- ```typescript
340
- initializeRevenium({
341
- meteringApiKey: "your_api_key",
342
- meteringBaseUrl: "https://api.revenium.io/meter",
343
- teamId: "your_team_id", // Optional
344
- });
345
- ```
346
-
347
- #### `initializePerplexity(config)`
348
-
349
- Initialize Perplexity with custom configuration.
350
-
351
- ```typescript
352
- initializePerplexity({
353
- apiKey: "your_perplexity_api_key",
354
- baseUrl: "https://api.perplexity.ai", // Optional
355
- });
356
- ```
357
-
358
- ### Chat Completions
359
-
360
- #### `createChatCompletion(params)`
361
-
362
- Create a chat completion with automatic metering.
363
-
364
- ```typescript
365
- const result = await createChatCompletion({
366
- messages: [
367
- { role: "system", content: "You are a helpful assistant." },
368
- { role: "user", content: "Hello!" },
369
- ],
370
- model: PERPLEXITY_MODELS.SONAR_PRO,
371
- maxTokens: 100,
372
- temperature: 0.7,
373
- usageMetadata: {
374
- // Optional
375
- subscriber: { id: "user-123" },
376
- organizationId: "org-456",
377
- productId: "product-789",
378
- },
379
- });
380
-
381
- console.log(result.content);
382
- console.log(result.usage);
383
- console.log(result.transactionId);
384
- ```
385
-
386
- **Parameters:**
387
-
388
- - `messages` - Array of message objects with `role` and `content`
389
- - `model` - Perplexity model to use (see [Available Models](https://github.com/revenium/revenium-middleware-perplexity-node#available-models))
390
- - `maxTokens` - Maximum tokens to generate (optional)
391
- - `temperature` - Sampling temperature 0-2 (optional)
392
- - `topP` - Nucleus sampling parameter (optional)
393
- - `presencePenalty` - Presence penalty -2 to 2 (optional)
394
- - `frequencyPenalty` - Frequency penalty -2 to 2 (optional)
395
- - `usageMetadata` - Custom metadata for tracking (optional)
396
-
397
- **Returns:**
398
-
399
- ```typescript
400
- {
401
- content: string;
402
- role: string;
403
- finishReason: string | null;
404
- usage: {
405
- promptTokens: number;
406
- completionTokens: number;
407
- totalTokens: number;
408
- }
409
- model: string;
410
- transactionId: string;
411
- rawResponse: PerplexityResponse;
412
- }
413
- ```
414
-
415
- #### `createStreamingChatCompletion(params)`
416
-
417
- Create a streaming chat completion.
418
-
419
- ```typescript
420
- const result = await createStreamingChatCompletion({
421
- messages: [{ role: "user", content: "Count from 1 to 5" }],
422
- model: PERPLEXITY_MODELS.SONAR_PRO,
423
- });
424
-
425
- for await (const chunk of result.stream) {
426
- const content = chunk.choices[0]?.delta?.content || "";
427
- process.stdout.write(content);
428
- }
429
- ```
430
-
431
- **Returns:**
432
-
433
- ```typescript
434
- {
435
- stream: AsyncGenerator<PerplexityStreamChunk>;
436
- transactionId: string;
437
- model: string;
438
- }
439
- ```
440
-
441
- ### Available Models
442
-
443
- ```typescript
444
- import { PERPLEXITY_MODELS } from "@revenium/perplexity";
445
-
446
- // Online Models (with internet access)
447
- PERPLEXITY_MODELS.SONAR; // "sonar"
448
- PERPLEXITY_MODELS.SONAR_PRO; // "sonar-pro"
449
- PERPLEXITY_MODELS.SONAR_REASONING; // "sonar-reasoning"
450
-
451
- // Chat Models (offline)
452
- PERPLEXITY_MODELS.LLAMA_3_1_SONAR_SMALL_128K_CHAT; // "llama-3.1-sonar-small-128k-chat"
453
- PERPLEXITY_MODELS.LLAMA_3_1_SONAR_LARGE_128K_CHAT; // "llama-3.1-sonar-large-128k-chat"
454
- PERPLEXITY_MODELS.LLAMA_3_1_SONAR_HUGE_128K_CHAT; // "llama-3.1-sonar-huge-128k-chat"
455
- ```
456
-
457
- ### Utility Functions
458
-
459
- #### `disableRevenium()` / `enableRevenium()`
460
-
461
- Temporarily disable or enable Revenium metering.
462
-
463
- ```typescript
464
- import { disableRevenium, enableRevenium } from "@revenium/perplexity";
465
-
466
- disableRevenium(); // Stop sending metering data
467
- // ... make API calls ...
468
- enableRevenium(); // Resume sending metering data
469
- ```
470
-
471
- #### `generateTransactionId()`
472
-
473
- Generate a unique transaction ID.
474
-
475
- ```typescript
476
- import { generateTransactionId } from "@revenium/perplexity";
477
-
478
- const txnId = generateTransactionId();
479
- ```
480
-
481
- ## 📖 Examples
482
-
483
- ### Basic Chat Completion
484
-
485
- ```typescript
486
- import {
487
- initializeReveniumFromEnv,
488
- initializePerplexityFromEnv,
489
- createChatCompletion,
490
- PERPLEXITY_MODELS,
491
- } from "@revenium/perplexity";
492
-
493
- initializeReveniumFromEnv();
494
- initializePerplexityFromEnv();
495
-
496
- const result = await createChatCompletion({
497
- messages: [{ role: "user", content: "What is the capital of France?" }],
498
- model: PERPLEXITY_MODELS.SONAR_PRO,
499
- });
500
-
501
- console.log(result.content);
502
- ```
503
-
504
- ### Streaming Response
505
-
506
- ```typescript
507
- const result = await createStreamingChatCompletion({
508
- messages: [{ role: "user", content: "Write a short poem about AI" }],
509
- model: PERPLEXITY_MODELS.SONAR_PRO,
510
- });
511
-
512
- for await (const chunk of result.stream) {
513
- const content = chunk.choices[0]?.delta?.content || "";
514
- process.stdout.write(content);
515
- }
516
- ```
517
-
518
- ### Multi-turn Conversation
519
-
520
- ```typescript
521
- const messages = [
522
- { role: "system", content: "You are a helpful assistant." },
523
- { role: "user", content: "What is the capital of France?" },
524
- ];
525
-
526
- const response1 = await createChatCompletion({
527
- messages,
528
- model: PERPLEXITY_MODELS.SONAR_PRO,
529
- });
530
-
531
- messages.push({ role: "assistant", content: response1.content });
532
- messages.push({ role: "user", content: "What is its population?" });
533
-
534
- const response2 = await createChatCompletion({
535
- messages,
536
- model: PERPLEXITY_MODELS.SONAR_PRO,
537
- });
538
- ```
539
-
540
- ### Custom Metadata
541
-
542
- ```typescript
543
- const result = await createChatCompletion({
544
- messages: [{ role: "user", content: "Hello!" }],
545
- model: PERPLEXITY_MODELS.SONAR_PRO,
546
- usageMetadata: {
547
- subscriber: {
548
- id: "user-123",
549
- email: "user@example.com",
550
- },
551
- organizationId: "org-456",
552
- productId: "premium-plan",
553
- traceId: "trace-abc-123",
554
- },
555
- });
556
- ```
557
-
558
- ## 🏗️ Project Structure
559
-
560
- ```
561
- revenium-middleware-perplexity-node/
562
- ├── src/
563
- │ ├── core/
564
- │ │ ├── config/ # Configuration management
565
- │ │ ├── tracking/ # Metering and tracking
566
- │ │ └── wrapper/ # Perplexity API wrapper
567
- │ ├── types/ # TypeScript type definitions
568
- │ ├── utils/ # Utility functions
569
- │ └── index.ts # Main entry point
570
- ├── examples/ # TypeScript examples
571
- ├── playground/ # JavaScript examples
572
- └── dist/
573
- ├── cjs/ # CommonJS build
574
- ├── esm/ # ES Modules build
575
- └── types/ # TypeScript definitions
576
- ```
577
-
578
- ## 🧪 Running Examples
579
-
580
- ### TypeScript Examples
581
-
582
- ```bash
583
- npm run example:basic # Basic chat completion
584
- npm run example:streaming # Streaming response
585
- npm run example:chat # Multi-turn conversation
586
- npm run example:metadata # Custom metadata
587
- ```
588
-
589
- ### JavaScript Playground
590
-
591
- ```bash
592
- npm run playground:basic # Basic chat completion
593
- npm run playground:streaming # Streaming response
594
- npm run playground:chat # Multi-turn conversation
595
- npm run playground:metadata # Custom metadata
596
- ```
597
-
598
- ## 🔒 Environment Variables
599
-
600
- | Variable | Required | Description |
601
- | ---------------------------- | -------- | ------------------------------------------------------------------ |
602
- | `PERPLEXITY_API_KEY` | Yes | Your Perplexity API key |
603
- | `REVENIUM_METERING_API_KEY` | Yes | Your Revenium metering API key |
604
- | `REVENIUM_METERING_BASE_URL` | Yes | Revenium metering endpoint (e.g., `https://api.revenium.io/meter`) |
605
-
606
- ## 📄 License
607
-
608
- ISC
609
-
610
- ## 🤝 Contributing
611
-
612
- Contributions are welcome! Please feel free to submit a Pull Request.
613
-
614
- ## 📞 Support
615
-
616
- For issues and questions:
617
-
618
- - GitHub Issues: [revenium-middleware-perplexity-node/issues](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
619
- - Documentation: [Revenium Docs](https://docs.revenium.io)
620
-
621
- ## 🔗 Links
622
-
623
- - [Perplexity AI Documentation](https://docs.perplexity.ai)
624
- - [Revenium Platform](https://revenium.io)
625
- - [npm Package](https://www.npmjs.com/package/@revenium/perplexity)
1
+ # Revenium Middleware for Perplexity
2
+
3
+ A lightweight, production-ready middleware that adds **Revenium metering and tracking** to Perplexity AI API calls.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@revenium/perplexity.svg)](https://www.npmjs.com/package/@revenium/perplexity)
6
+ [![Node.js](https://img.shields.io/badge/Node.js-20%2B-green)](https://nodejs.org/)
7
+ [![Documentation](https://img.shields.io/badge/docs-revenium.io-blue)](https://docs.revenium.io)
8
+ [![Website](https://img.shields.io/badge/website-revenium.ai-blue)](https://www.revenium.ai)
9
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
10
+
11
+ ## Features
12
+
13
+ - **Zero Configuration** - Works out of the box with environment variables
14
+ - **Automatic Metering** - Tracks all API calls with detailed usage metrics
15
+ - **Streaming Support** - Full support for streaming responses
16
+ - **TypeScript First** - Built with TypeScript, includes full type definitions
17
+ - **Multi-Format** - Supports both ESM and CommonJS
18
+ - **Custom Metadata** - Add custom tracking metadata to any request
19
+ - **Production Ready** - Battle-tested and optimized for production use
20
+
21
+ ## Getting Started
22
+
23
+ ### Quick Start
24
+
25
+ ```bash
26
+ npm install @revenium/perplexity dotenv
27
+ ```
28
+
29
+ For complete setup instructions, TypeScript patterns, and usage examples, see [examples/README.md](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/README.md).
30
+
31
+ ### Step-by-Step Guide
32
+
33
+ The following guide walks you through creating a new project from scratch:
34
+
35
+ #### Step 1: Create Your Project
36
+
37
+ ```bash
38
+ # Create project directory
39
+ mkdir my-perplexity-project
40
+ cd my-perplexity-project
41
+
42
+ # Initialize Node.js project
43
+ npm init -y
44
+ ```
45
+
46
+ #### Step 2: Install Dependencies
47
+
48
+ ```bash
49
+ # Install Revenium middleware and Perplexity dependencies
50
+ npm install @revenium/perplexity dotenv
51
+
52
+ # For TypeScript projects (optional)
53
+ npm install -D typescript tsx @types/node
54
+ ```
55
+
56
+ #### Step 3: Setup Environment Variables
57
+
58
+ Create a `.env` file in your project root:
59
+
60
+ ```bash
61
+ # Copy the example file
62
+ cp .env.example .env
63
+
64
+ # Then edit .env with your actual API keys
65
+ ```
66
+
67
+ See [`.env.example`](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/.env.example) for the complete list of environment variables and where to get your API keys.
68
+
69
+ **Replace the placeholder values with your actual keys!**
70
+
71
+ #### Step 4: Follow the Examples
72
+
73
+ See [examples/README.md](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/README.md) for complete examples and setup instructions.
74
+
75
+ **Cloned from GitHub?** Run examples with:
76
+
77
+ ```bash
78
+ npm install
79
+ npm run example:basic
80
+ npm run example:streaming
81
+ npm run example:chat
82
+ npm run example:metadata
83
+ npm run example:advanced
84
+ npm run example:getting-started
85
+ ```
86
+
87
+ **Browse online:** [`examples/` directory](https://github.com/revenium/revenium-middleware-perplexity-node/tree/HEAD/examples)
88
+
89
+ ---
90
+
91
+ ## What Gets Tracked
92
+
93
+ The middleware automatically captures:
94
+
95
+ - **Token Usage**: Prompt and completion tokens for accurate billing
96
+ - **Request Duration**: Total time for each API call
97
+ - **Model Information**: Which Perplexity model was used
98
+ - **Operation Type**: Chat completion, streaming, etc.
99
+ - **Error Tracking**: Failed requests and error details
100
+ - **Streaming Metrics**: Time to first token for streaming responses
101
+ - **Custom Metadata**: Business context you provide
102
+
103
+ ## Advanced Usage
104
+
105
+ For advanced features including:
106
+
107
+ - **Initialization Options** - Environment variables vs manual configuration
108
+ - **Streaming Responses** - Real-time streaming with usage tracking
109
+ - **Custom Metadata Tracking** - Add business context to your API calls
110
+
111
+ See the **[Examples Guide](./examples/README.md)** for detailed documentation and working code examples.
112
+
113
+ ### Metadata Fields Reference
114
+
115
+ The `usageMetadata` parameter supports the following fields for detailed tracking:
116
+
117
+ | Field | Description | Use Case |
118
+ | ----------------------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
119
+ | `traceId` | Unique identifier for session or conversation tracking | Link multiple API calls together for debugging, user session analytics, or distributed tracing across services |
120
+ | `taskType` | Type of AI task being performed | Categorize usage by workload (e.g., "search", "research", "qa") for cost analysis and optimization |
121
+ | `subscriber.id` | Unique user identifier | Track individual user consumption for billing, rate limiting, or user analytics |
122
+ | `subscriber.email` | User's email address | Associate usage with specific users for reporting and communication |
123
+ | `subscriber.credential` | Object containing credential information | Track usage by API keys and credentials |
124
+ | `subscriber.credential.name` | Authentication credential name | Track which API key or service account made the request |
125
+ | `subscriber.credential.value` | Authentication credential value | Associate usage with specific credentials for security auditing |
126
+ | `organizationId` | Organization or company identifier | Multi-tenant cost allocation, usage quotas per organization |
127
+ | `subscriptionId` | Subscription plan identifier | Track usage against subscription limits, identify plan upgrade opportunities |
128
+ | `productId` | Your product or feature identifier | Attribute AI costs to specific features in your application (e.g., "search-bot", "research-assistant") |
129
+ | `agent` | AI agent or bot identifier | Distinguish between multiple AI agents or automation workflows in your system |
130
+ | `responseQualityScore` | Custom quality rating (0.0-1.0) | Track user satisfaction or automated quality metrics for model performance analysis |
131
+
132
+ For complete API documentation and additional details, see the [Revenium API Reference](https://revenium.readme.io/reference/meter_ai_completion).
133
+
134
+ ## Troubleshooting
135
+
136
+ ### Common Issues
137
+
138
+ #### "Missing API Key" Error
139
+
140
+ ```bash
141
+ # Verify your .env file exists and has the required keys
142
+ cat .env
143
+
144
+ # Or use .env.example as a template
145
+ cp .env.example .env
146
+ # Then edit .env with your actual keys
147
+ ```
148
+
149
+ #### "Requests not being tracked"
150
+
151
+ ```bash
152
+ # Enable debug logging to see what's happening
153
+ export DEBUG="true"
154
+
155
+ # Check your .env file has correct values
156
+ cat .env | grep REVENIUM
157
+
158
+ # Verify initialization is called before making requests
159
+ ```
160
+
161
+ #### TypeScript errors with usageMetadata
162
+
163
+ - Ensure you're importing from `@revenium/perplexity`
164
+ - Check that your TypeScript version is 5.0+
165
+ - Verify you're using the latest version: `npm update @revenium/perplexity`
166
+
167
+ #### Build/Import Errors
168
+
169
+ ```bash
170
+ # Clean and reinstall
171
+ rm -rf node_modules
172
+ npm install
173
+
174
+ # For TypeScript projects
175
+ npm run build
176
+ ```
177
+
178
+ ### Debug Mode
179
+
180
+ **SECURITY WARNING: Never enable DEBUG mode in production!**
181
+
182
+ Debug mode is intended for local development only. While sensitive fields (PII, credentials) are automatically redacted from debug logs, debug mode should only be enabled in development environments with test data.
183
+
184
+ Enable debug logging to troubleshoot issues:
185
+
186
+ ```bash
187
+ export DEBUG="true"
188
+ node your-script.js
189
+ ```
190
+
191
+ This will show:
192
+
193
+ - Initialization details
194
+ - Configuration loading
195
+ - API call information (with PII/credentials redacted)
196
+ - Error details
197
+
198
+ **Production environments must NEVER set DEBUG=true.**
199
+
200
+ ## Project Structure
201
+
202
+ ```
203
+ revenium-middleware-perplexity-node/
204
+ ├── src/
205
+ │ ├── core/
206
+ │ │ ├── config/ # Configuration management
207
+ │ │ ├── tracking/ # Metering and tracking
208
+ │ │ └── wrapper/ # Perplexity API wrapper
209
+ │ ├── types/ # TypeScript type definitions
210
+ │ ├── utils/ # Utility functions
211
+ │ └── index.ts # Main entry point
212
+ ├── examples/ # TypeScript examples
213
+ └── dist/
214
+ ├── cjs/ # CommonJS build
215
+ ├── esm/ # ES Modules build
216
+ └── types/ # TypeScript definitions
217
+ ```
218
+
219
+ ## How It Works
220
+
221
+ 1. **Initialization**: When you call `initializePerplexityFromEnv()` and `initializeReveniumFromEnv()`, the middleware sets up configurations
222
+ 2. **Request Wrapping**: All Perplexity API calls go through the middleware wrapper
223
+ 3. **Usage Extraction**: Token counts, model info, and timing data are captured from responses
224
+ 4. **Async Tracking**: Usage data is sent to Revenium in the background (fire-and-forget)
225
+ 5. **Transparent Response**: Original Perplexity responses are returned unchanged
226
+
227
+ The middleware never blocks your application - if Revenium tracking fails, your Perplexity requests continue normally.
228
+
229
+ ## Requirements
230
+
231
+ - Node.js 20+
232
+ - TypeScript 5.0+ (for TypeScript projects)
233
+ - Revenium API key
234
+ - Perplexity API key
235
+
236
+ ## Documentation
237
+
238
+ For detailed documentation, visit [docs.revenium.io](https://docs.revenium.io)
239
+
240
+ ## Contributing
241
+
242
+ See [CONTRIBUTING.md](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/CONTRIBUTING.md)
243
+
244
+ ## Code of Conduct
245
+
246
+ See [CODE_OF_CONDUCT.md](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/CODE_OF_CONDUCT.md)
247
+
248
+ ## Security
249
+
250
+ See [SECURITY.md](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/SECURITY.md)
251
+
252
+ ## License
253
+
254
+ This project is licensed under the MIT License - see the [LICENSE](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/LICENSE) file for details.
255
+
256
+ ## Support
257
+
258
+ For issues, feature requests, or contributions:
259
+
260
+ - **GitHub Repository**: [revenium/revenium-middleware-perplexity-node](https://github.com/revenium/revenium-middleware-perplexity-node)
261
+ - **Issues**: [Report bugs or request features](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
262
+ - **Documentation**: [docs.revenium.io](https://docs.revenium.io)
263
+ - **Contact**: Reach out to the Revenium team for additional support
264
+
265
+ ## Development
266
+
267
+ For development and testing instructions, see [DEVELOPMENT.md](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/DEVELOPMENT.md).
268
+
269
+ ---
270
+
271
+ **Built by Revenium**