@revenium/perplexity 1.0.22 → 1.0.25

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 (87) hide show
  1. package/README.md +391 -154
  2. package/dist/interfaces/meteringResponse.d.ts +28 -27
  3. package/dist/interfaces/meteringResponse.js +2 -2
  4. package/dist/models/Metering.js +23 -20
  5. package/dist/v1/perplexityV1.service.js +166 -0
  6. package/dist/v2/perplexityV2.service.js +178 -0
  7. package/examples/v1/basic.ts +50 -0
  8. package/examples/v1/chat.ts +40 -0
  9. package/examples/v1/metadata.ts +49 -0
  10. package/examples/v1/streaming.ts +44 -0
  11. package/examples/v2/basic.ts +49 -0
  12. package/examples/v2/chat.ts +60 -0
  13. package/examples/v2/metadata.ts +71 -0
  14. package/examples/v2/streaming.ts +61 -0
  15. package/package.json +26 -11
  16. package/playground/v1/basic.js +50 -0
  17. package/playground/v1/chat.js +46 -0
  18. package/playground/v1/metadata.js +50 -0
  19. package/playground/v1/streaming.js +44 -0
  20. package/playground/v2/basic.js +49 -0
  21. package/playground/v2/chat.js +72 -0
  22. package/playground/v2/metadata.js +76 -0
  23. package/playground/v2/streaming.js +67 -0
  24. package/src/index.ts +14 -1
  25. package/src/interfaces/chatCompletionRequest.ts +7 -2
  26. package/src/interfaces/meteringResponse.ts +1 -0
  27. package/src/interfaces/perplexityResponse.ts +63 -0
  28. package/src/interfaces/perplexityStreaming.ts +56 -0
  29. package/src/models/Metering.ts +9 -2
  30. package/src/utils/constants/perplexityModels.ts +71 -0
  31. package/src/v1/perplexityV1.controller.ts +164 -0
  32. package/src/v1/perplexityV1.service.ts +230 -0
  33. package/src/v2/perplexityV2.controller.ts +219 -0
  34. package/src/v2/perplexityV2.service.ts +260 -0
  35. package/dist/index.js +0 -19
  36. package/dist/interfaces/chatCompletionRequest.d.ts +0 -9
  37. package/dist/interfaces/chatCompletionRequest.js +0 -2
  38. package/dist/interfaces/credential.d.ts +0 -4
  39. package/dist/interfaces/credential.js +0 -2
  40. package/dist/interfaces/meteringRequest.d.ts +0 -13
  41. package/dist/interfaces/meteringRequest.js +0 -2
  42. package/dist/interfaces/operation.d.ts +0 -4
  43. package/dist/interfaces/operation.js +0 -8
  44. package/dist/interfaces/subscriber.d.ts +0 -8
  45. package/dist/interfaces/subscriber.js +0 -2
  46. package/dist/interfaces/tokenCounts.d.ts +0 -7
  47. package/dist/interfaces/tokenCounts.js +0 -2
  48. package/dist/interfaces/usageMetadata.d.ts +0 -27
  49. package/dist/interfaces/usageMetadata.js +0 -2
  50. package/dist/middleware.d.ts +0 -22
  51. package/dist/middleware.js +0 -129
  52. package/dist/models/Logger.js +0 -35
  53. package/dist/models/Metering.d.ts +0 -9
  54. package/dist/utils/calculateDurationMs.d.ts +0 -1
  55. package/dist/utils/calculateDurationMs.js +0 -6
  56. package/dist/utils/constants/constants.d.ts +0 -6
  57. package/dist/utils/constants/constants.js +0 -11
  58. package/dist/utils/constants/logLevels.d.ts +0 -1
  59. package/dist/utils/constants/logLevels.js +0 -4
  60. package/dist/utils/constants/messages.d.ts +0 -5
  61. package/dist/utils/constants/messages.js +0 -8
  62. package/dist/utils/constants/models.d.ts +0 -1
  63. package/dist/utils/constants/models.js +0 -21
  64. package/dist/utils/extractTokenCount.d.ts +0 -2
  65. package/dist/utils/extractTokenCount.js +0 -28
  66. package/dist/utils/formatTimeStamp.d.ts +0 -1
  67. package/dist/utils/formatTimeStamp.js +0 -6
  68. package/dist/utils/generateTransactionId.d.ts +0 -1
  69. package/dist/utils/generateTransactionId.js +0 -7
  70. package/dist/utils/index.d.ts +0 -6
  71. package/dist/utils/index.js +0 -23
  72. package/dist/utils/loadEnv.d.ts +0 -1
  73. package/dist/utils/loadEnv.js +0 -7
  74. package/dist/utils/safeExtract.d.ts +0 -29
  75. package/dist/utils/safeExtract.js +0 -67
  76. package/examples/basic.ts +0 -17
  77. package/examples/chat-completions.ts +0 -22
  78. package/examples/enhanced.ts +0 -20
  79. package/examples/metadata.ts +0 -43
  80. package/examples/streaming.ts +0 -24
  81. package/playground/basic.js +0 -17
  82. package/playground/chat-completions.js +0 -22
  83. package/playground/enhanced.js +0 -20
  84. package/playground/metadata.js +0 -43
  85. package/playground/streaming.js +0 -24
  86. package/src/middleware.ts +0 -157
  87. /package/src/utils/{formatTimeStamp.ts → formatTimestamp.ts} +0 -0
package/README.md CHANGED
@@ -5,17 +5,24 @@
5
5
  [![Documentation](https://img.shields.io/badge/docs-available-brightgreen.svg)](https://docs.revenium.io)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
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.
8
+ Automatically track and meter your Perplexity AI API usage with Revenium. This package provides seamless integration with Perplexity AI API using modern Controller architecture, supporting both V1 (compatible) and V2 (enhanced) response formats.
9
+
10
+ ## 🎯 **New Architecture: V1 & V2 Controllers**
11
+
12
+ - **V1 Controller**: Maintains compatibility with existing middleware logic
13
+ - **V2 Controller**: Enhanced response format following [OpenAI Responses API](https://platform.openai.com/docs/guides/migrate-to-responses) guidelines
14
+ - **Service Layer**: Handles API calls, metering, and data transformation
15
+ - **Rich Examples**: TypeScript examples and JavaScript playground files
9
16
 
10
17
  ## 🚀 Getting Started
11
18
 
12
- You have 3 options to start using Revenium middleware for Perplexity AI:
19
+ You have 3 options to start using Revenium Controllers for Perplexity AI:
13
20
 
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) |
21
+ | Option | Description | Best For |
22
+ | ----------------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
23
+ | **Option 1: Create Project from Scratch** | Perfect for new projects. We'll guide you step-by-step using V1 or V2 Controllers. | 👉 [Go to Step-by-Step Guide](#option-1-create-project-from-scratch) |
24
+ | **Option 2: Clone Our Repository** | Quick testing with pre-built V1/V2 examples and playground scripts. | 👉 [Go to Clone Guide](#option-2-clone-repository) |
25
+ | **Option 3: Add to Existing Project** | Already have a project? Just install and use Controllers. | 👉 [Go to Quick Integration](#option-3-existing-project-integration) |
19
26
 
20
27
  ---
21
28
 
@@ -65,36 +72,67 @@ REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
65
72
 
66
73
  ### Step 4: Create Your First Test
67
74
 
68
- Create `test-perplexity.js`:
75
+ Choose between V1 (compatible) or V2 (enhanced) Controller:
76
+
77
+ #### Option A: V1 Controller (Compatible)
78
+
79
+ Create `test-perplexity-v1.js`:
80
+
81
+ ```javascript
82
+ // test-perplexity-v1.js
83
+ import { PerplexityV1Controller } from "@revenium/perplexity";
84
+
85
+ const basicV1Example = async () => {
86
+ try {
87
+ const controller = new PerplexityV1Controller();
88
+
89
+ const result = await controller.createChat(
90
+ ["What is the universe?"],
91
+ "sonar-pro"
92
+ );
93
+
94
+ console.log("*** V1 RESPONSE ***");
95
+ console.log(result.responses[0].text);
96
+ console.log(`📊 Tokens: ${result.usageMetadata.totalTokenCount}`);
97
+ console.log("✅ V1 Controller example successful!");
98
+ } catch (error) {
99
+ console.error("❌ V1 Controller example failed:", error);
100
+ process.exit(1);
101
+ }
102
+ };
103
+
104
+ basicV1Example();
105
+ ```
106
+
107
+ #### Option B: V2 Controller (Enhanced)
108
+
109
+ Create `test-perplexity-v2.js`:
69
110
 
70
111
  ```javascript
71
- // test-perplexity.js
72
- import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
112
+ // test-perplexity-v2.js
113
+ import { PerplexityV2Controller } from "@revenium/perplexity";
73
114
 
74
- const basicExample = async () => {
115
+ const basicV2Example = async () => {
75
116
  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!");
117
+ const controller = new PerplexityV2Controller();
118
+
119
+ const result = await controller.createChat(
120
+ ["What is the universe?"],
121
+ "sonar-pro"
122
+ );
123
+
124
+ console.log("*** V2 ENHANCED RESPONSE ***");
125
+ console.log(result.choices[0].message.content);
126
+ console.log(`📊 Usage: ${result.usage.total_tokens} tokens`);
127
+ console.log(`⚡ Processing: ${result.metadata.processingTime}ms`);
128
+ console.log("✅ V2 Enhanced Controller example successful!");
91
129
  } catch (error) {
92
- console.error("❌ Perplexity basic example failed:", error);
130
+ console.error("❌ V2 Controller example failed:", error);
93
131
  process.exit(1);
94
132
  }
95
133
  };
96
134
 
97
- basicExample();
135
+ basicV2Example();
98
136
  ```
99
137
 
100
138
  ### Step 5: Update package.json
@@ -107,7 +145,8 @@ Add test scripts and module type to your `package.json`:
107
145
  "version": "1.0.0",
108
146
  "type": "module",
109
147
  "scripts": {
110
- "test-perplexity": "node test-perplexity.js"
148
+ "test-v1": "node test-perplexity-v1.js",
149
+ "test-v2": "node test-perplexity-v2.js"
111
150
  },
112
151
  "dependencies": {
113
152
  "@revenium/perplexity": "^1.0.0"
@@ -132,8 +171,11 @@ Make sure your `package.json` includes `"type": "module"` as shown below.
132
171
  ### Step 6: Run Your Tests
133
172
 
134
173
  ```bash
135
- # Test Perplexity AI SDK
136
- npm run test-perplexity
174
+ # Test V1 Controller (Compatible)
175
+ npm run test-v1
176
+
177
+ # Test V2 Controller (Enhanced)
178
+ npm run test-v2
137
179
  ```
138
180
 
139
181
  ### Step 7: Create Advanced Examples
@@ -144,99 +186,164 @@ Create an examples directory and add these files:
144
186
  mkdir examples
145
187
  ```
146
188
 
147
- #### Streaming Example
189
+ #### V1 Streaming Example
148
190
 
149
- Create `examples/streaming-perplexity.js`:
191
+ Create `examples/streaming-v1.js`:
150
192
 
151
193
  ```javascript
152
- // examples/streaming-perplexity.js
153
- import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
194
+ // examples/streaming-v1.js
195
+ import { PerplexityV1Controller } from "@revenium/perplexity";
154
196
 
155
- const streamingExample = async () => {
197
+ const streamingV1Example = async () => {
156
198
  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 ***");
199
+ const controller = new PerplexityV1Controller();
200
+
201
+ const stream = await controller.createStreaming(
202
+ ["What is artificial intelligence?"],
203
+ "sonar-pro"
204
+ );
205
+
206
+ console.log("*** V1 STREAMING RESPONSE ***");
169
207
  let fullText = "";
170
208
 
171
209
  for await (const chunk of stream) {
172
- const content = chunk.choices[0]?.delta?.content;
210
+ if (chunk.text) {
211
+ process.stdout.write(chunk.text);
212
+ fullText += chunk.text;
213
+ }
214
+ }
215
+
216
+ console.log("\n✅ V1 Streaming with metering successful!");
217
+ console.log(`📊 Total response length: ${fullText.length} characters`);
218
+ } catch (error) {
219
+ console.error("❌ V1 streaming example failed:", error);
220
+ process.exit(1);
221
+ }
222
+ };
223
+
224
+ streamingV1Example();
225
+ ```
226
+
227
+ #### V2 Streaming Example
228
+
229
+ Create `examples/streaming-v2.js`:
230
+
231
+ ```javascript
232
+ // examples/streaming-v2.js
233
+ import { PerplexityV2Controller } from "@revenium/perplexity";
234
+
235
+ const streamingV2Example = async () => {
236
+ try {
237
+ const controller = new PerplexityV2Controller();
238
+
239
+ const stream = await controller.createStreaming(
240
+ ["What is artificial intelligence?"],
241
+ "sonar-pro"
242
+ );
243
+
244
+ console.log("*** V2 ENHANCED STREAMING RESPONSE ***");
245
+ let fullText = "";
246
+
247
+ for await (const chunk of stream) {
248
+ const content = chunk.choices?.[0]?.delta?.content;
173
249
  if (content) {
174
250
  process.stdout.write(content);
175
251
  fullText += content;
176
252
  }
177
253
  }
178
254
 
179
- console.log("\n✅ Streaming with metering successful!");
255
+ console.log("\n✅ V2 Enhanced Streaming successful!");
180
256
  console.log(`📊 Total response length: ${fullText.length} characters`);
181
257
  } catch (error) {
182
- console.error("❌ Perplexity streaming example failed:", error);
258
+ console.error("❌ V2 streaming example failed:", error);
183
259
  process.exit(1);
184
260
  }
185
261
  };
186
262
 
187
- streamingExample();
263
+ streamingV2Example();
188
264
  ```
189
265
 
190
- #### METADATA Example
266
+ #### Metadata Example
191
267
 
192
- Create `examples/metadata-perplexity.js`:
268
+ Create `examples/metadata-v1.js`:
193
269
 
194
270
  ```javascript
195
- // examples/metadata-perplexity.js
196
- import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
271
+ // examples/metadata-v1.js
272
+ import { PerplexityV1Controller } from "@revenium/perplexity";
197
273
 
198
- const metadataExample = async () => {
274
+ const metadataV1Example = async () => {
199
275
  try {
200
- const middleware = new PerplexityReveniumMiddleware();
201
- const model = middleware.getGenerativeModel("sonar-pro");
202
- const result = await model.createChatCompletion({
203
- model: "sonar-pro",
204
- messages: [{ role: "user", content: "What is the capital of France?" }],
205
- usageMetadata: {
206
- taskType: "test",
207
- subscriberEmail: "test@revenium.ai",
208
- subscriberId: "123456",
209
- subscriberCredentialName: "apiKey",
210
- subscriberCredential: "keyValue",
211
- organizationId: "123456",
212
- subscriptionId: "123456",
213
- productId: "free-trial",
214
- agent: "perplexity",
215
- responseQualityScore: 100,
216
- transactionId: "123456",
217
- timeToFirstToken: 1000,
218
- requestTime: new Date(),
219
- completionStartTime: new Date(),
220
- operationType: "CHAT",
221
- inputTokenCount: 10,
222
- outputTokenCount: 10,
223
- reasoningTokenCount: 20,
224
- cacheCreationTokenCount: 0,
225
- cacheReadTokenCount: 0,
226
- totalTokenCount: 40,
227
- responseTime: new Date(),
228
- requestDuration: 1000,
229
- stopReason: "END",
230
- },
231
- });
232
- console.log("[BASIC REQUEST]", result.choices[0].message);
276
+ const controller = new PerplexityV1Controller();
277
+
278
+ // Custom metadata for tracking
279
+ const customMetadata = {
280
+ traceId: "trace-12345",
281
+ taskType: "research-query",
282
+ subscriberEmail: "user@example.com",
283
+ subscriberId: "user-456",
284
+ organizationId: "org-789",
285
+ agent: "perplexity-v1-demo",
286
+ };
287
+
288
+ const result = await controller.createChat(
289
+ ["What is the capital of France?"],
290
+ "sonar-pro",
291
+ customMetadata
292
+ );
293
+
294
+ console.log("*** V1 RESPONSE WITH METADATA ***");
295
+ console.log(result.responses[0].text);
296
+ console.log(`📊 Tokens: ${result.usageMetadata.totalTokenCount}`);
297
+ console.log(`🏷️ Trace ID: ${customMetadata.traceId}`);
298
+ console.log("✅ V1 Metadata example successful!");
233
299
  } catch (error) {
234
- console.error("❌ Perplexity streaming example failed:", error);
300
+ console.error("❌ V1 metadata example failed:", error);
235
301
  process.exit(1);
236
302
  }
237
303
  };
238
304
 
239
- metadataExample();
305
+ metadataV1Example();
306
+ ```
307
+
308
+ Create `examples/metadata-v2.js`:
309
+
310
+ ```javascript
311
+ // examples/metadata-v2.js
312
+ import { PerplexityV2Controller } from "@revenium/perplexity";
313
+
314
+ const metadataV2Example = async () => {
315
+ try {
316
+ const controller = new PerplexityV2Controller();
317
+
318
+ // Enhanced metadata for V2
319
+ const customMetadata = {
320
+ traceId: "trace-v2-67890",
321
+ taskType: "enhanced-research",
322
+ subscriberEmail: "user@example.com",
323
+ subscriberId: "user-456",
324
+ organizationId: "org-789",
325
+ agent: "perplexity-v2-demo",
326
+ };
327
+
328
+ const result = await controller.createChat(
329
+ ["What is the capital of France?"],
330
+ "sonar-pro",
331
+ customMetadata
332
+ );
333
+
334
+ console.log("*** V2 ENHANCED RESPONSE WITH METADATA ***");
335
+ console.log(result.choices[0].message.content);
336
+ console.log(`📊 Usage: ${result.usage.total_tokens} tokens`);
337
+ console.log(`⚡ Processing: ${result.metadata.processingTime}ms`);
338
+ console.log(`🏷️ Trace ID: ${customMetadata.traceId}`);
339
+ console.log("✅ V2 Enhanced Metadata example successful!");
340
+ } catch (error) {
341
+ console.error("❌ V2 metadata example failed:", error);
342
+ process.exit(1);
343
+ }
344
+ };
345
+
346
+ metadataV2Example();
240
347
  ```
241
348
 
242
349
  ### Step 8: Update package.json
@@ -247,9 +354,12 @@ metadataExample();
247
354
  "version": "1.0.0",
248
355
  "type": "module",
249
356
  "scripts": {
250
- "test-perplexity": "node test-perplexity.js",
251
- "test-perplexity-stream": "node examples/streaming-perplexity.js",
252
- "test-perplexity-metadata": "node examples/metadata-perplexity.js"
357
+ "test-v1": "node test-perplexity-v1.js",
358
+ "test-v2": "node test-perplexity-v2.js",
359
+ "test-v1-stream": "node examples/streaming-v1.js",
360
+ "test-v2-stream": "node examples/streaming-v2.js",
361
+ "test-v1-metadata": "node examples/metadata-v1.js",
362
+ "test-v2-metadata": "node examples/metadata-v2.js"
253
363
  },
254
364
  "dependencies": {
255
365
  "@revenium/perplexity": "^1.0.0"
@@ -260,12 +370,13 @@ metadataExample();
260
370
  ### Step 9: Test Advanced Examples
261
371
 
262
372
  ```bash
263
- # Test streaming
264
- npm run test-perplexity-stream
265
-
266
- # Test metadata
267
- npm run test-perplexity-metadata
373
+ # Test V1 examples
374
+ npm run test-v1-stream
375
+ npm run test-v1-metadata
268
376
 
377
+ # Test V2 examples
378
+ npm run test-v2-stream
379
+ npm run test-v2-metadata
269
380
  ```
270
381
 
271
382
  ---
@@ -299,27 +410,46 @@ REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
299
410
  REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
300
411
  ```
301
412
 
302
- ### Run Perplexity AI Examples
413
+ ### Run V1 & V2 Examples
303
414
 
304
415
  ```bash
305
- # Perplexity AI examples
306
-
307
- npm run e-basic # Basic chat completion
308
- npm run e-streaming # Streaming response
309
- npm run e-enhanced # Enhanced request
310
- npm run e-chat-completions # Chat completions
311
- npm run e-metadata # Metadata request
312
-
313
- # Playground examples
314
- # Required build first
416
+ # Build the project first
315
417
  npm run build
316
- ## Change type to module in package.json
317
- "type": "module",
318
- # Then run any of the following
319
- npm run p-basic
320
- npm run p-streaming
321
- npm run p-enhanced
322
- npm run p-metadata
418
+
419
+ # V1 Controller Examples (TypeScript)
420
+ npm run e-v1-basic # V1 Basic chat completion
421
+ npm run e-v1-streaming # V1 Streaming response
422
+ npm run e-v1-chat # V1 Multi-turn chat
423
+ npm run e-v1-metadata # V1 Metadata tracking
424
+
425
+ # V2 Controller Examples (TypeScript)
426
+ npm run e-v2-basic # V2 Enhanced chat completion
427
+ npm run e-v2-streaming # V2 Enhanced streaming
428
+ npm run e-v2-chat # V2 Enhanced multi-turn chat
429
+ npm run e-v2-metadata # V2 Enhanced metadata
430
+
431
+ # V1 Playground Examples (JavaScript)
432
+ npm run p-v1-basic # V1 Basic (JavaScript)
433
+ npm run p-v1-streaming # V1 Streaming (JavaScript)
434
+ npm run p-v1-chat # V1 Chat (JavaScript)
435
+ npm run p-v1-metadata # V1 Metadata (JavaScript)
436
+
437
+ # V2 Playground Examples (JavaScript)
438
+ npm run p-v2-basic # V2 Enhanced (JavaScript)
439
+ npm run p-v2-streaming # V2 Enhanced Streaming (JavaScript)
440
+ npm run p-v2-chat # V2 Enhanced Chat (JavaScript)
441
+ npm run p-v2-metadata # V2 Enhanced Metadata (JavaScript)
442
+
443
+ # Convenience Scripts
444
+ npm run examples:v1 # Run V1 basic example
445
+ npm run examples:v2 # Run V2 basic example
446
+ npm run examples:all # Run both V1 and V2 examples
447
+ npm run playground:v1 # Run V1 playground basic
448
+ npm run playground:v2 # Run V2 playground basic
449
+ npm run playground:all # Run both V1 and V2 playground
450
+ npm run test:v1 # Test all V1 examples
451
+ npm run test:v2 # Test all V2 examples
452
+ npm run test:all # Test all V1 and V2 examples
323
453
  ```
324
454
 
325
455
  ---
@@ -352,31 +482,45 @@ REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
352
482
  import { OpenAI } from "openai";
353
483
  ```
354
484
 
355
- **After:**
485
+ **After (V1 Controller):**
356
486
 
357
487
  ```javascript
358
- import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
488
+ import { PerplexityV1Controller } from "@revenium/perplexity";
489
+ ```
490
+
491
+ **After (V2 Controller):**
492
+
493
+ ```javascript
494
+ import { PerplexityV2Controller } from "@revenium/perplexity";
359
495
  ```
360
496
 
361
497
  ### Step 4. Update Your Code
362
498
 
363
- #### Revenium Client Example
499
+ #### V1 Controller Example (Compatible)
500
+
501
+ ```javascript
502
+ import { PerplexityV1Controller } from "@revenium/perplexity";
503
+
504
+ // Initialize V1 Controller
505
+ const controller = new PerplexityV1Controller();
506
+ const result = await controller.createChat(["Hello world"], "sonar-pro");
507
+
508
+ console.log("[V1 EXAMPLE]", result.responses[0].text);
509
+ console.log(`Tokens: ${result.usageMetadata.totalTokenCount}`);
510
+ ```
511
+
512
+ #### V2 Controller Example (Enhanced)
364
513
 
365
514
  ```javascript
366
- import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
367
-
368
- // Initialize (API key from environment variable)
369
- const middleware = new PerplexityReveniumMiddleware();
370
- const model = middleware.getGenerativeModel("sonar-pro");
371
- const result = await model.createChatCompletion({
372
- messages: [
373
- {
374
- role: "user",
375
- content: "Hello world",
376
- },
377
- ],
378
- });
379
- console.log("[BASIC EXAMPLE]", result.choices[0].message.content);
515
+ import { PerplexityV2Controller } from "@revenium/perplexity";
516
+
517
+ // Initialize V2 Controller
518
+ const controller = new PerplexityV2Controller();
519
+ const result = await controller.createChat(["Hello world"], "sonar-pro");
520
+
521
+ console.log("[V2 ENHANCED EXAMPLE]", result.choices[0].message.content);
522
+ console.log(`Usage: ${result.usage.total_tokens} tokens`);
523
+ console.log(`Processing: ${result.metadata.processingTime}ms`);
380
524
  ```
381
525
 
382
526
  ---
@@ -385,31 +529,98 @@ console.log("[BASIC EXAMPLE]", result.choices[0].message.content);
385
529
 
386
530
  ### Streaming Responses
387
531
 
388
- #### Revenium Client Streaming
532
+ #### V1 Controller Streaming
389
533
 
390
534
  ```javascript
391
- const stream = await model.createChatCompletionStream({
392
- messages: [
393
- {
394
- role: "user",
395
- content: "Hello world",
396
- },
397
- ],
398
- });
535
+ import { PerplexityV1Controller } from "@revenium/perplexity";
536
+
537
+ const controller = new PerplexityV1Controller();
538
+ const stream = await controller.createStreaming(["Hello world"], "sonar-pro");
539
+
399
540
  for await (const chunk of stream) {
400
- process.stdout.write(chunk.choices[0]?.delta?.content || "");
541
+ if (chunk.text) {
542
+ process.stdout.write(chunk.text);
543
+ }
401
544
  }
402
545
  ```
403
546
 
547
+ #### V2 Controller Streaming (Enhanced)
548
+
549
+ ```javascript
550
+ import { PerplexityV2Controller } from "@revenium/perplexity";
551
+
552
+ const controller = new PerplexityV2Controller();
553
+ const stream = await controller.createStreaming(["Hello world"], "sonar-pro");
554
+
555
+ for await (const chunk of stream) {
556
+ const content = chunk.choices?.[0]?.delta?.content;
557
+ if (content) {
558
+ process.stdout.write(content);
559
+ }
560
+ }
561
+ ```
562
+
563
+ ### Custom Metadata Tracking
564
+
565
+ #### V1 Metadata Example
566
+
567
+ ```javascript
568
+ const customMetadata = {
569
+ traceId: "trace-12345",
570
+ taskType: "research-query",
571
+ subscriberEmail: "user@example.com",
572
+ organizationId: "org-789",
573
+ agent: "perplexity-v1-demo",
574
+ };
575
+
576
+ const result = await controller.createChat(
577
+ ["What is AI?"],
578
+ "sonar-pro",
579
+ customMetadata
580
+ );
581
+ ```
582
+
583
+ #### V2 Enhanced Metadata Example
584
+
585
+ ```javascript
586
+ const customMetadata = {
587
+ traceId: "trace-v2-67890",
588
+ taskType: "enhanced-research",
589
+ subscriberEmail: "user@example.com",
590
+ organizationId: "org-789",
591
+ agent: "perplexity-v2-demo",
592
+ };
593
+
594
+ const result = await controller.createChat(
595
+ ["What is AI?"],
596
+ "sonar-pro",
597
+ customMetadata
598
+ );
599
+
600
+ // V2 provides additional metadata
601
+ console.log(`Processing time: ${result.metadata.processingTime}ms`);
602
+ console.log(`Transaction ID: ${result.metadata.transactionId}`);
603
+ ```
604
+
404
605
  ## 📊 What Gets Tracked
405
606
 
607
+ ### V1 Controller Tracking
608
+
406
609
  - **Token Usage**: Input and output tokens for accurate billing
407
610
  - **Request Duration**: Total time for each API call
408
611
  - **Model Information**: Which model was used
409
612
  - **Operation Type**: Chat completion, streaming
410
613
  - **Error Tracking**: Failed requests and error details
411
- - **Streaming Metrics**: Time to first token for streaming responses
412
614
  - **Custom Metadata**: Rich business context and user tracking
615
+ - **Transaction ID**: Unique identifier for each request
616
+
617
+ ### V2 Enhanced Tracking (Additional)
618
+
619
+ - **Processing Time**: Enhanced timing metrics
620
+ - **Enhanced Metadata**: Additional context following OpenAI Responses API
621
+ - **Response Format**: OpenAI-compatible response structure
622
+ - **Model Performance**: Enhanced model capability tracking
623
+ - **Streaming Metrics**: Time to first token for streaming responses
413
624
 
414
625
  ---
415
626
 
@@ -420,6 +631,18 @@ for await (const chunk of stream) {
420
631
  - **sonar-pro** (Latest and most capable)
421
632
  - **sonar-small** (Fast and efficient)
422
633
  - **sonar-medium** (Balanced performance)
634
+ - **llama-3.1-sonar-small-128k-online** (Llama-based with online search)
635
+ - **llama-3.1-sonar-large-128k-online** (Large Llama model with online search)
636
+ - **llama-3.1-sonar-huge-128k-online** (Huge Llama model with online search)
637
+
638
+ ### Model Capabilities
639
+
640
+ Both V1 and V2 Controllers support:
641
+
642
+ - **Chat Completions**: All models support chat completions
643
+ - **Streaming**: Real-time response streaming
644
+ - **Online Search**: Models with "online" in the name support web search
645
+ - **Large Context**: 128k context window for Llama models
423
646
 
424
647
  _Note: Model availability depends on your Perplexity AI account and API access level._
425
648
 
@@ -474,16 +697,30 @@ This will show:
474
697
 
475
698
  ## 📚 Examples Repository
476
699
 
477
- Check out our comprehensive examples:
700
+ Check out our comprehensive examples organized by version:
478
701
 
479
- - **Basic Usage**: Simple chat completions
480
- - **Streaming**: Real-time response streaming
481
- - **Metadata**: Rich tracking examples
482
- - **Error Handling**: Robust error management
483
- - **Advanced Patterns**: Complex use cases
484
- - **Configuration**: Different setup options
702
+ ### V1 Controller Examples (Compatible)
703
+
704
+ - **Basic Usage**: Simple chat completions with V1 response format
705
+ - **Streaming**: Real-time response streaming with V1 format
706
+ - **Multi-turn Chat**: Conversation handling with V1 controllers
707
+ - **Metadata**: Rich tracking examples with V1 metadata
708
+ - **Model Capabilities**: Check model features and capabilities
709
+
710
+ ### V2 Controller Examples (Enhanced)
711
+
712
+ - **Enhanced Basic**: Chat completions with OpenAI-compatible responses
713
+ - **Enhanced Streaming**: Streaming with enhanced metadata and timing
714
+ - **Enhanced Chat**: Multi-turn conversations with V2 enhancements
715
+ - **Enhanced Metadata**: Advanced tracking with processing time metrics
716
+ - **Model Performance**: Enhanced model capability and performance tracking
717
+
718
+ ### File Organization
485
719
 
486
- All examples are in the `/examples` and `/playground` directories.
720
+ - **`/examples/v1/`**: TypeScript examples using V1 Controllers (development)
721
+ - **`/examples/v2/`**: TypeScript examples using V2 Controllers (development)
722
+ - **`/playground/v1/`**: JavaScript examples using V1 Controllers (production)
723
+ - **`/playground/v2/`**: JavaScript examples using V2 Controllers (production)
487
724
 
488
725
  ---
489
726