@revenium/perplexity 1.0.14 → 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 (45) hide show
  1. package/.env.example +3 -3
  2. package/README.md +447 -448
  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/package.json +47 -45
package/README.md CHANGED
@@ -1,448 +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
- ### 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
- export REVENIUM_LOG_LEVEL="DEBUG" # Enable debug logging
390
- ```
391
-
392
- **Module Import Errors**
393
-
394
- ```json
395
- {
396
- "type": "module"
397
- }
398
- ```
399
-
400
- This will show:
401
-
402
- - Request/response details
403
- - Token counting information
404
- - Metering data being sent
405
- - Error details
406
- - Middleware activation status
407
-
408
- ---
409
-
410
- ## 📚 Examples Repository
411
-
412
- Check out our comprehensive examples:
413
-
414
- - **Basic Usage**: Simple chat completions
415
- - **Streaming**: Real-time response streaming
416
- - **Metadata**: Rich tracking examples
417
- - **Error Handling**: Robust error management
418
- - **Advanced Patterns**: Complex use cases
419
- - **Configuration**: Different setup options
420
-
421
- All examples are in the `/examples` and `/playground` directories.
422
-
423
- ---
424
-
425
- ## 📋 Requirements
426
-
427
- - Node.js 18+
428
- - Perplexity API key
429
- - Revenium API key
430
-
431
- ---
432
-
433
- ## 📄 License
434
-
435
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
436
-
437
- ---
438
-
439
- ## 🤝 Support
440
-
441
- - 📖 [Documentation](https://docs.revenium.com)
442
- - 💬 [Community Support](https://community.revenium.com)
443
- - 📧 [Email Support](mailto:support@revenium.com)
444
- - 🐛 [Report Issues](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
445
-
446
- ---
447
-
448
- **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**