@revenium/perplexity 1.0.14 → 1.0.17

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 (46) hide show
  1. package/.env.example +3 -3
  2. package/README.md +504 -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 +46 -45
  46. package/src/middleware.ts +1 -1
package/README.md CHANGED
@@ -1,448 +1,504 @@
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 { PerplexityReveniumMiddleware } from "@revenium/perplexity";
73
+
74
+ const basicExample = async () => {
75
+ try {
76
+ const middleware = new PerplexityReveniumMiddleware();
77
+ const model = middleware.getGenerativeModel("sonar-pro");
78
+ const result = await model.createChatCompletion({
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
+ basicExample();
98
+ ```
99
+
100
+ ### Step 5: Update package.json
101
+
102
+ Add test scripts and module type to your `package.json`:
103
+
104
+ ```json
105
+ {
106
+ "name": "my-perplexity-ai-project",
107
+ "version": "1.0.0",
108
+ "type": "module",
109
+ "scripts": {
110
+ "test-perplexity": "node test-perplexity.js"
111
+ },
112
+ "dependencies": {
113
+ "@revenium/perplexity": "^1.0.0"
114
+ }
115
+ }
116
+ ```
117
+
118
+ ⚠️ **Important**: If you get this error when running tests:
119
+
120
+ ```
121
+ SyntaxError: Cannot use import statement outside a module
122
+ ```
123
+
124
+ Make sure your `package.json` includes `"type": "module"` as shown below.
125
+
126
+ ```json
127
+ {
128
+ "type": "module"
129
+ }
130
+ ```
131
+
132
+ ### Step 6: Run Your Tests
133
+
134
+ ```bash
135
+ # Test Perplexity AI SDK
136
+ npm run test-perplexity
137
+ ```
138
+
139
+ ### Step 7: Create Advanced Examples
140
+
141
+ Create an examples directory and add these files:
142
+
143
+ ```bash
144
+ mkdir examples
145
+ ```
146
+
147
+ #### Streaming Example
148
+
149
+ Create `examples/streaming-perplexity.js`:
150
+
151
+ ```javascript
152
+ // examples/streaming-perplexity.js
153
+ import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
154
+
155
+ const streamingExample = async () => {
156
+ try {
157
+ const middleware = new PerplexityReveniumMiddleware();
158
+ const model = middleware.getGenerativeModel("sonar-pro");
159
+ const stream = await model.createChatCompletionStream({
160
+ messages: [
161
+ {
162
+ role: "user",
163
+ content: "What is artificial intelligence?",
164
+ },
165
+ ],
166
+ });
167
+
168
+ console.log("*** STREAMING RESPONSE ***");
169
+ let fullText = "";
170
+
171
+ for await (const chunk of stream) {
172
+ const content = chunk.choices[0]?.delta?.content;
173
+ if (content) {
174
+ process.stdout.write(content);
175
+ fullText += content;
176
+ }
177
+ }
178
+
179
+ console.log("\n✅ Streaming with metering successful!");
180
+ console.log(`📊 Total response length: ${fullText.length} characters`);
181
+ } catch (error) {
182
+ console.error("❌ Perplexity streaming example failed:", error);
183
+ process.exit(1);
184
+ }
185
+ };
186
+
187
+ streamingExample();
188
+ ```
189
+
190
+ #### Metadata Example
191
+
192
+ Create `examples/metadata-perplexity.js`:
193
+
194
+ ```javascript
195
+ // examples/metadata-perplexity.js
196
+ import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
197
+
198
+ const metadataExample = async () => {
199
+ try {
200
+ const middleware = new PerplexityReveniumMiddleware();
201
+ const model = middleware.getGenerativeModel("sonar-pro");
202
+ const result = await model.createChatCompletion({
203
+ messages: [
204
+ {
205
+ role: "user",
206
+ content: "Analyze this quarterly report",
207
+ },
208
+ ],
209
+ usageMetadata: {
210
+ // User tracking
211
+ traceId: "conv-28a7e9d4",
212
+ taskType: "document-analysis",
213
+ subscriberEmail: "user@example.com",
214
+ subscriberId: "user-123",
215
+ subscriberCredentialName: "api-key-1",
216
+
217
+ // Business context
218
+ organizationId: "acme-corp",
219
+ subscriptionId: "premium-plan",
220
+ productId: "business-intelligence",
221
+ agent: "analysis-assistant",
222
+ responseQualityScore: 0.95,
223
+ },
224
+ });
225
+
226
+ console.log("*** METADATA RESPONSE ***");
227
+ console.log("Response:", result.choices[0]?.message?.content);
228
+ console.log("✅ Metadata tracking with metering successful!");
229
+ } catch (error) {
230
+ console.error("❌ Perplexity metadata example failed:", error);
231
+ process.exit(1);
232
+ }
233
+ };
234
+
235
+ metadataExample();
236
+ ```
237
+
238
+ ### Step 8: Update package.json
239
+
240
+ ```json
241
+ {
242
+ "name": "my-perplexity-ai-project",
243
+ "version": "1.0.0",
244
+ "type": "module",
245
+ "scripts": {
246
+ "test-perplexity": "node test-perplexity.js",
247
+ "test-perplexity-stream": "node examples/streaming-perplexity.js",
248
+ "test-perplexity-metadata": "node examples/metadata-perplexity.js"
249
+ },
250
+ "dependencies": {
251
+ "@revenium/perplexity": "^1.0.0"
252
+ }
253
+ }
254
+ ```
255
+
256
+ ### Step 9: Test Advanced Examples
257
+
258
+ ```bash
259
+ # Test streaming
260
+ npm run test-perplexity-stream
261
+
262
+ # Test metadata
263
+ npm run test-perplexity-metadata
264
+ ```
265
+
266
+ ---
267
+
268
+ ## Option 2: Clone Repository
269
+
270
+ Perfect for testing with pre-built examples:
271
+
272
+ ```bash
273
+ # Clone the repository
274
+ git clone git@github.com:revenium/revenium-middleware-perplexity-node.git
275
+ cd revenium-middleware-perplexity-node
276
+
277
+ # Install dependencies
278
+ npm install
279
+ npm install @revenium/perplexity
280
+
281
+ # Create your .env file
282
+ cp .env.example .env
283
+ # Edit .env with your API keys
284
+ ```
285
+
286
+ ### Configure Environment Variables
287
+
288
+ Edit your `.env` file:
289
+
290
+ ```bash
291
+ # For Perplexity AI SDK
292
+ PERPLEXITY_API_KEY="your_perplexity_api_key_here"
293
+ REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
294
+ REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
295
+ ```
296
+
297
+ ### Run Perplexity AI Examples
298
+
299
+ ```bash
300
+ # Perplexity AI examples
301
+
302
+ npm run e-basic # Basic chat completion
303
+ npm run e-streaming # Streaming response
304
+ npm run e-enhanced # Enhanced request
305
+ npm run e-chat-completions # Chat completions
306
+
307
+ # Playground examples
308
+ # Required build first
309
+ npm run build
310
+ # Then run any of the following
311
+ npm run p-basic
312
+ npm run p-streaming
313
+ npm run p-enhanced
314
+ ```
315
+
316
+ ---
317
+
318
+ ## Option 3: Existing Project Integration
319
+
320
+ Already have a project? Just install and replace imports:
321
+
322
+ ### Step 1. Install the Package
323
+
324
+ ```bash
325
+ npm install @revenium/perplexity
326
+ ```
327
+
328
+ ### Step 2. Add Environment Variables
329
+
330
+ Add to your existing `.env` file:
331
+
332
+ ```bash
333
+ PERPLEXITY_API_KEY="your_perplexity_api_key_here"
334
+ REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
335
+ REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
336
+ ```
337
+
338
+ ### Step 3. Replace Your Imports
339
+
340
+ **Before:**
341
+
342
+ ```javascript
343
+ import { OpenAI } from "openai";
344
+ ```
345
+
346
+ **After:**
347
+
348
+ ```javascript
349
+ import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
350
+ ```
351
+
352
+ ### Step 4. Update Your Code
353
+
354
+ #### Revenium Client Example
355
+
356
+ ```javascript
357
+ import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
358
+
359
+ // Initialize (API key from environment variable)
360
+ const middleware = new PerplexityReveniumMiddleware();
361
+ const model = middleware.getGenerativeModel("sonar-pro");
362
+ const result = await model.createChatCompletion({
363
+ messages: [
364
+ {
365
+ role: "user",
366
+ content: "Hello world",
367
+ },
368
+ ],
369
+ });
370
+ console.log("[BASIC EXAMPLE]", result.choices[0].message.content);
371
+ ```
372
+
373
+ ---
374
+
375
+ ## 🔧 Advanced Usage
376
+
377
+ ### Streaming Responses
378
+
379
+ #### Revenium Client Streaming
380
+
381
+ ```javascript
382
+ const stream = await model.createChatCompletionStream({
383
+ messages: [
384
+ {
385
+ role: "user",
386
+ content: "Hello world",
387
+ },
388
+ ],
389
+ });
390
+ for await (const chunk of stream) {
391
+ process.stdout.write(chunk.choices[0]?.delta?.content || "");
392
+ }
393
+ ```
394
+
395
+ ## 📊 What Gets Tracked
396
+
397
+ - **Token Usage**: Input and output tokens for accurate billing
398
+ - **Request Duration**: Total time for each API call
399
+ - **Model Information**: Which model was used
400
+ - **Operation Type**: Chat completion, streaming
401
+ - **Error Tracking**: Failed requests and error details
402
+ - **Streaming Metrics**: Time to first token for streaming responses
403
+ - **Custom Metadata**: Rich business context and user tracking
404
+
405
+ ---
406
+
407
+ ## 🔗 Supported Models
408
+
409
+ ### Chat Models
410
+
411
+ - **sonar-pro** (Latest and most capable)
412
+ - **sonar-small** (Fast and efficient)
413
+ - **sonar-medium** (Balanced performance)
414
+
415
+ _Note: Model availability depends on your Perplexity AI account and API access level._
416
+
417
+ ---
418
+
419
+ ## 🛠️ Configuration Options
420
+
421
+ ### Environment Variables
422
+
423
+ | Variable | Required | Description |
424
+ | ---------------------------- | -------- | ---------------------------------------------------------- |
425
+ | `PERPLEXITY_API_KEY` | ✅ | Your Perplexity API key |
426
+ | `REVENIUM_METERING_API_KEY` | ✅ | Your Revenium API key |
427
+ | `REVENIUM_METERING_BASE_URL` | ❌ | Revenium base URL (default: https://api.revenium.io/meter) |
428
+
429
+ ---
430
+
431
+ ## 🚨 Troubleshooting
432
+
433
+ ### Common Issues
434
+
435
+ **"Missing API Key" Error**
436
+
437
+ ```bash
438
+ export PERPLEXITY_API_KEY="your-actual-api-key"
439
+ echo $PERPLEXITY_API_KEY # Verify it's set
440
+ ```
441
+
442
+ **"Requests not being tracked"**
443
+
444
+ ```bash
445
+ export REVENIUM_METERING_API_KEY="your-actual-revenium-key"
446
+ ```
447
+
448
+ **Module Import Errors**
449
+
450
+ ```json
451
+ {
452
+ "type": "module"
453
+ }
454
+ ```
455
+
456
+ This will show:
457
+
458
+ - Request/response details
459
+ - Token counting information
460
+ - Metering data being sent
461
+ - Error details
462
+ - Middleware activation status
463
+
464
+ ---
465
+
466
+ ## 📚 Examples Repository
467
+
468
+ Check out our comprehensive examples:
469
+
470
+ - **Basic Usage**: Simple chat completions
471
+ - **Streaming**: Real-time response streaming
472
+ - **Metadata**: Rich tracking examples
473
+ - **Error Handling**: Robust error management
474
+ - **Advanced Patterns**: Complex use cases
475
+ - **Configuration**: Different setup options
476
+
477
+ All examples are in the `/examples` and `/playground` directories.
478
+
479
+ ---
480
+
481
+ ## 📋 Requirements
482
+
483
+ - Node.js 18+
484
+ - Perplexity API key
485
+ - Revenium API key
486
+
487
+ ---
488
+
489
+ ## 📄 License
490
+
491
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
492
+
493
+ ---
494
+
495
+ ## 🤝 Support
496
+
497
+ - 📖 [Documentation](https://docs.revenium.com)
498
+ - 💬 [Community Support](https://community.revenium.com)
499
+ - 📧 [Email Support](mailto:support@revenium.com)
500
+ - 🐛 [Report Issues](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
501
+
502
+ ---
503
+
504
+ **Built with ❤️ by Revenium**