@revenium/perplexity 1.0.25 โ†’ 2.0.2

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 (96) hide show
  1. package/README.md +443 -568
  2. package/dist/cjs/core/config/perplexity-config.js +45 -0
  3. package/dist/cjs/core/config/perplexity-config.js.map +1 -0
  4. package/dist/cjs/core/config/revenium-config.js +80 -0
  5. package/dist/cjs/core/config/revenium-config.js.map +1 -0
  6. package/dist/cjs/core/tracking/metering.js +131 -0
  7. package/dist/cjs/core/tracking/metering.js.map +1 -0
  8. package/dist/cjs/core/wrapper/perplexity-client.js +177 -0
  9. package/dist/cjs/core/wrapper/perplexity-client.js.map +1 -0
  10. package/dist/cjs/index.js +64 -0
  11. package/dist/cjs/index.js.map +1 -0
  12. package/dist/cjs/types/index.js +21 -0
  13. package/dist/cjs/types/index.js.map +1 -0
  14. package/dist/cjs/utils/logger.js +23 -0
  15. package/dist/cjs/utils/logger.js.map +1 -0
  16. package/dist/esm/core/config/perplexity-config.js +40 -0
  17. package/dist/esm/core/config/perplexity-config.js.map +1 -0
  18. package/dist/esm/core/config/revenium-config.js +72 -0
  19. package/dist/esm/core/config/revenium-config.js.map +1 -0
  20. package/dist/esm/core/tracking/metering.js +126 -0
  21. package/dist/esm/core/tracking/metering.js.map +1 -0
  22. package/dist/esm/core/wrapper/perplexity-client.js +170 -0
  23. package/dist/esm/core/wrapper/perplexity-client.js.map +1 -0
  24. package/dist/esm/index.js +44 -0
  25. package/dist/esm/index.js.map +1 -0
  26. package/dist/esm/types/index.js +18 -0
  27. package/dist/esm/types/index.js.map +1 -0
  28. package/dist/esm/utils/logger.js +20 -0
  29. package/dist/esm/utils/logger.js.map +1 -0
  30. package/dist/types/core/config/perplexity-config.d.ts +24 -0
  31. package/dist/types/core/config/perplexity-config.d.ts.map +1 -0
  32. package/dist/types/core/config/revenium-config.d.ts +37 -0
  33. package/dist/types/core/config/revenium-config.d.ts.map +1 -0
  34. package/dist/types/core/tracking/metering.d.ts +31 -0
  35. package/dist/types/core/tracking/metering.d.ts.map +1 -0
  36. package/dist/types/core/wrapper/perplexity-client.d.ts +32 -0
  37. package/dist/types/core/wrapper/perplexity-client.d.ts.map +1 -0
  38. package/dist/types/index.d.ts +34 -0
  39. package/dist/types/index.d.ts.map +1 -0
  40. package/dist/types/types/index.d.ts +159 -0
  41. package/dist/types/types/index.d.ts.map +1 -0
  42. package/dist/types/utils/logger.d.ts +10 -0
  43. package/dist/types/utils/logger.d.ts.map +1 -0
  44. package/package.json +36 -31
  45. package/.env.example +0 -3
  46. package/dist/interfaces/meteringResponse.d.ts +0 -28
  47. package/dist/interfaces/meteringResponse.js +0 -2
  48. package/dist/models/Metering.js +0 -83
  49. package/dist/v1/perplexityV1.service.js +0 -166
  50. package/dist/v2/perplexityV2.service.js +0 -178
  51. package/examples/v1/basic.ts +0 -50
  52. package/examples/v1/chat.ts +0 -40
  53. package/examples/v1/metadata.ts +0 -49
  54. package/examples/v1/streaming.ts +0 -44
  55. package/examples/v2/basic.ts +0 -49
  56. package/examples/v2/chat.ts +0 -60
  57. package/examples/v2/metadata.ts +0 -71
  58. package/examples/v2/streaming.ts +0 -61
  59. package/playground/v1/basic.js +0 -50
  60. package/playground/v1/chat.js +0 -46
  61. package/playground/v1/metadata.js +0 -50
  62. package/playground/v1/streaming.js +0 -44
  63. package/playground/v2/basic.js +0 -49
  64. package/playground/v2/chat.js +0 -72
  65. package/playground/v2/metadata.js +0 -76
  66. package/playground/v2/streaming.js +0 -67
  67. package/src/index.ts +0 -17
  68. package/src/interfaces/chatCompletionRequest.ts +0 -15
  69. package/src/interfaces/credential.ts +0 -4
  70. package/src/interfaces/meteringRequest.ts +0 -14
  71. package/src/interfaces/meteringResponse.ts +0 -29
  72. package/src/interfaces/operation.ts +0 -4
  73. package/src/interfaces/perplexityResponse.ts +0 -63
  74. package/src/interfaces/perplexityStreaming.ts +0 -56
  75. package/src/interfaces/subscriber.ts +0 -8
  76. package/src/interfaces/tokenCounts.ts +0 -7
  77. package/src/interfaces/usageMetadata.ts +0 -27
  78. package/src/models/Logger.ts +0 -38
  79. package/src/models/Metering.ts +0 -121
  80. package/src/utils/calculateDurationMs.ts +0 -3
  81. package/src/utils/constants/constants.ts +0 -10
  82. package/src/utils/constants/logLevels.ts +0 -1
  83. package/src/utils/constants/messages.ts +0 -11
  84. package/src/utils/constants/models.ts +0 -20
  85. package/src/utils/constants/perplexityModels.ts +0 -71
  86. package/src/utils/extractTokenCount.ts +0 -26
  87. package/src/utils/formatTimestamp.ts +0 -3
  88. package/src/utils/generateTransactionId.ts +0 -5
  89. package/src/utils/index.ts +0 -39
  90. package/src/utils/loadEnv.ts +0 -8
  91. package/src/utils/safeExtract.ts +0 -67
  92. package/src/v1/perplexityV1.controller.ts +0 -164
  93. package/src/v1/perplexityV1.service.ts +0 -230
  94. package/src/v2/perplexityV2.controller.ts +0 -219
  95. package/src/v2/perplexityV2.service.ts +0 -260
  96. package/tsconfig.json +0 -15
package/README.md CHANGED
@@ -1,750 +1,625 @@
1
- # Revenium Middleware for Perplexity AI (Node.js)
1
+ # Revenium Middleware for Perplexity
2
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)
3
+ A lightweight, production-ready middleware that adds **Revenium metering and tracking** to Perplexity AI API calls.
7
4
 
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.
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)
9
7
 
10
- ## ๐ŸŽฏ **New Architecture: V1 & V2 Controllers**
8
+ ## ๐Ÿš€ Features
11
9
 
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
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
16
17
 
17
- ## ๐Ÿš€ Getting Started
18
+ ## ๐Ÿ“‹ Table of Contents
18
19
 
19
- You have 3 options to start using Revenium Controllers for Perplexity AI:
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)
20
29
 
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) |
26
-
27
- ---
28
-
29
- ## Option 1: Create Project from Scratch
30
-
31
- ### Step 1: Create Project Directory
30
+ ## ๐Ÿ“ฆ Installation
32
31
 
33
32
  ```bash
34
- # Create and navigate to your project
35
- mkdir my-perplexity-ai-project
36
- cd my-perplexity-ai-project
37
-
38
- # Initialize Node.js project
39
- npm init -y
33
+ npm install @revenium/perplexity
40
34
  ```
41
35
 
42
- ### Step 2: Install Dependencies
36
+ ## ๐ŸŽฏ Three Ways to Use This Middleware
43
37
 
44
- ```bash
45
- npm install @revenium/perplexity
46
- ```
38
+ ### Option 1: New Project with npm Package (Recommended)
47
39
 
48
- ### Step 3: Setup Environment Variables
40
+ **Best for:** Starting a new project or adding Perplexity with Revenium to an existing project.
49
41
 
50
- Create a `.env` file in your project root:
42
+ #### Step 1: Create a new project
51
43
 
52
44
  ```bash
53
- # Create .env file
54
- echo. > .env # On Windows (CMD TERMINAL)
55
- touch .env # On Mac/Linux (CMD TERMINAL)
56
- # OR
57
- #PowerShell
58
- New-Item -Path .env -ItemType File
45
+ mkdir my-perplexity-project
46
+ cd my-perplexity-project
47
+ npm init -y
59
48
  ```
60
49
 
61
- Copy and paste the following into `.env`:
50
+ #### Step 2: Install the middleware
62
51
 
63
52
  ```bash
64
- # Perplexity AI Configuration
65
- PERPLEXITY_API_KEY="your_perplexity_api_key_here"
66
-
67
- # Revenium Configuration
68
- REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
69
- REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
70
-
53
+ npm install @revenium/perplexity dotenv
71
54
  ```
72
55
 
73
- ### Step 4: Create Your First Test
56
+ #### Step 3: Create `.env` file
74
57
 
75
- Choose between V1 (compatible) or V2 (enhanced) Controller:
58
+ ```env
59
+ # Perplexity API Configuration
60
+ PERPLEXITY_API_KEY=your_perplexity_api_key
76
61
 
77
- #### Option A: V1 Controller (Compatible)
62
+ # Revenium Metering Configuration
63
+ REVENIUM_METERING_API_KEY=your_revenium_api_key
64
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
65
+ ```
78
66
 
79
- Create `test-perplexity-v1.js`:
67
+ #### Step 4: Create `index.js`
80
68
 
81
69
  ```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
- };
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
+ }
103
91
 
104
- basicV1Example();
92
+ main().catch(console.error);
105
93
  ```
106
94
 
107
- #### Option B: V2 Controller (Enhanced)
95
+ #### Step 5: Run your project
108
96
 
109
- Create `test-perplexity-v2.js`:
97
+ ```bash
98
+ node index.js
99
+ ```
110
100
 
111
- ```javascript
112
- // test-perplexity-v2.js
113
- import { PerplexityV2Controller } from "@revenium/perplexity";
114
-
115
- const basicV2Example = async () => {
116
- try {
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!");
129
- } catch (error) {
130
- console.error("โŒ V2 Controller example failed:", error);
131
- process.exit(1);
132
- }
133
- };
101
+ ---
134
102
 
135
- basicV2Example();
136
- ```
103
+ ### Option 2: Clone and Use Locally
137
104
 
138
- ### Step 5: Update package.json
105
+ **Best for:** Development, testing, or contributing to the middleware.
139
106
 
140
- Add test scripts and module type to your `package.json`:
107
+ #### Step 1: Clone the repository
141
108
 
142
- ```json
143
- {
144
- "name": "my-perplexity-ai-project",
145
- "version": "1.0.0",
146
- "type": "module",
147
- "scripts": {
148
- "test-v1": "node test-perplexity-v1.js",
149
- "test-v2": "node test-perplexity-v2.js"
150
- },
151
- "dependencies": {
152
- "@revenium/perplexity": "^1.0.0"
153
- }
154
- }
109
+ ```bash
110
+ git clone https://github.com/revenium/revenium-middleware-perplexity-node.git
111
+ cd revenium-middleware-perplexity-node
155
112
  ```
156
113
 
157
- โš ๏ธ **Important**: If you get this error when running tests:
114
+ #### Step 2: Install dependencies
158
115
 
159
- ```
160
- SyntaxError: Cannot use import statement outside a module
116
+ ```bash
117
+ npm install
161
118
  ```
162
119
 
163
- Make sure your `package.json` includes `"type": "module"` as shown below.
120
+ #### Step 3: Create `.env` file
164
121
 
165
- ```json
166
- {
167
- "type": "module"
168
- }
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
169
129
  ```
170
130
 
171
- ### Step 6: Run Your Tests
131
+ #### Step 4: Build the project
172
132
 
173
133
  ```bash
174
- # Test V1 Controller (Compatible)
175
- npm run test-v1
176
-
177
- # Test V2 Controller (Enhanced)
178
- npm run test-v2
134
+ npm run build
179
135
  ```
180
136
 
181
- ### Step 7: Create Advanced Examples
137
+ #### Step 5: Run examples
182
138
 
183
- Create an examples directory and add these files:
139
+ **TypeScript Examples:**
184
140
 
185
141
  ```bash
186
- mkdir examples
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
187
146
  ```
188
147
 
189
- #### V1 Streaming Example
190
-
191
- Create `examples/streaming-v1.js`:
148
+ **JavaScript Playground:**
192
149
 
193
- ```javascript
194
- // examples/streaming-v1.js
195
- import { PerplexityV1Controller } from "@revenium/perplexity";
196
-
197
- const streamingV1Example = async () => {
198
- try {
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 ***");
207
- let fullText = "";
208
-
209
- for await (const chunk of stream) {
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();
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
225
155
  ```
226
156
 
227
- #### V2 Streaming Example
157
+ #### Step 6: Use in your own code
228
158
 
229
- Create `examples/streaming-v2.js`:
159
+ After building, you can import from the local build:
230
160
 
231
161
  ```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;
249
- if (content) {
250
- process.stdout.write(content);
251
- fullText += content;
252
- }
253
- }
254
-
255
- console.log("\nโœ… V2 Enhanced Streaming successful!");
256
- console.log(`๐Ÿ“Š Total response length: ${fullText.length} characters`);
257
- } catch (error) {
258
- console.error("โŒ V2 streaming example failed:", error);
259
- process.exit(1);
260
- }
261
- };
162
+ const {
163
+ initializeReveniumFromEnv,
164
+ initializePerplexityFromEnv,
165
+ createChatCompletion,
166
+ } = require("./dist/cjs");
262
167
 
263
- streamingV2Example();
168
+ // Your code here...
264
169
  ```
265
170
 
266
- #### Metadata Example
171
+ ---
267
172
 
268
- Create `examples/metadata-v1.js`:
173
+ ### Option 3: Add to Existing Project
269
174
 
270
- ```javascript
271
- // examples/metadata-v1.js
272
- import { PerplexityV1Controller } from "@revenium/perplexity";
273
-
274
- const metadataV1Example = async () => {
275
- try {
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!");
299
- } catch (error) {
300
- console.error("โŒ V1 metadata example failed:", error);
301
- process.exit(1);
302
- }
303
- };
175
+ **Best for:** Integrating Perplexity with Revenium into an existing Node.js project.
304
176
 
305
- metadataV1Example();
177
+ #### Step 1: Install the middleware
178
+
179
+ ```bash
180
+ npm install @revenium/perplexity
306
181
  ```
307
182
 
308
- Create `examples/metadata-v2.js`:
183
+ #### Step 2: Add environment variables
309
184
 
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
- };
185
+ Add to your existing `.env` file:
345
186
 
346
- metadataV2Example();
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
347
194
  ```
348
195
 
349
- ### Step 8: Update package.json
196
+ #### Step 3: Initialize in your application
350
197
 
351
- ```json
352
- {
353
- "name": "my-perplexity-ai-project",
354
- "version": "1.0.0",
355
- "type": "module",
356
- "scripts": {
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"
363
- },
364
- "dependencies": {
365
- "@revenium/perplexity": "^1.0.0"
366
- }
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;
367
220
  }
368
221
  ```
369
222
 
370
- ### Step 9: Test Advanced Examples
223
+ **For ES Modules projects:**
371
224
 
372
- ```bash
373
- # Test V1 examples
374
- npm run test-v1-stream
375
- npm run test-v1-metadata
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
+ ```
376
247
 
377
- # Test V2 examples
378
- npm run test-v2-stream
379
- npm run test-v2-metadata
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
+ }
380
272
  ```
381
273
 
382
274
  ---
383
275
 
384
- ## Option 2: Clone Repository
276
+ ## ๐Ÿ”ง Quick Start
385
277
 
386
- Perfect for testing with pre-built examples:
278
+ ### 1. Set up environment variables
387
279
 
388
- ```bash
389
- # Clone the repository
390
- git clone git@github.com:revenium/revenium-middleware-perplexity-node.git
391
- cd revenium-middleware-perplexity-node
280
+ Create a `.env` file in your project root:
392
281
 
393
- # Install dependencies
394
- npm install
395
- npm install @revenium/perplexity
282
+ ```env
283
+ # Perplexity API Configuration
284
+ PERPLEXITY_API_KEY=your_perplexity_api_key
396
285
 
397
- # Create your .env file
398
- cp .env.example .env
399
- # Edit .env with your API keys
286
+ # Revenium Metering Configuration
287
+ REVENIUM_METERING_API_KEY=your_revenium_api_key
288
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
400
289
  ```
401
290
 
402
- ### Configure Environment Variables
291
+ ### 2. Initialize and use
403
292
 
404
- Edit your `.env` file:
293
+ ```typescript
294
+ import {
295
+ initializeReveniumFromEnv,
296
+ initializePerplexityFromEnv,
297
+ createChatCompletion,
298
+ PERPLEXITY_MODELS,
299
+ } from "@revenium/perplexity";
405
300
 
406
- ```bash
407
- # For Perplexity AI SDK
408
- PERPLEXITY_API_KEY="your_perplexity_api_key_here"
409
- REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
410
- REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
411
- ```
301
+ // Initialize configurations
302
+ initializeReveniumFromEnv();
303
+ initializePerplexityFromEnv();
412
304
 
413
- ### Run V1 & V2 Examples
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
+ });
414
310
 
415
- ```bash
416
- # Build the project first
417
- npm run build
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
311
+ console.log(result.content);
312
+ // Output: "The capital of France is Paris."
453
313
  ```
454
314
 
455
- ---
315
+ ## ๐Ÿ“š API Reference
456
316
 
457
- ## Option 3: Existing Project Integration
317
+ ### Configuration
458
318
 
459
- Already have a project? Just install and replace imports:
319
+ #### `initializeReveniumFromEnv()`
460
320
 
461
- ### Step 1. Install the Package
321
+ Initialize Revenium configuration from environment variables.
462
322
 
463
- ```bash
464
- npm install @revenium/perplexity
323
+ ```typescript
324
+ const config = initializeReveniumFromEnv();
465
325
  ```
466
326
 
467
- ### Step 2. Add Environment Variables
327
+ #### `initializePerplexityFromEnv()`
468
328
 
469
- Add to your existing `.env` file:
329
+ Initialize Perplexity configuration from environment variables.
470
330
 
471
- ```bash
472
- PERPLEXITY_API_KEY="your_perplexity_api_key_here"
473
- REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
474
- REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
331
+ ```typescript
332
+ const config = initializePerplexityFromEnv();
475
333
  ```
476
334
 
477
- ### Step 3. Replace Your Imports
335
+ #### `initializeRevenium(config)`
478
336
 
479
- **Before:**
337
+ Initialize Revenium with custom configuration.
480
338
 
481
- ```javascript
482
- import { OpenAI } from "openai";
339
+ ```typescript
340
+ initializeRevenium({
341
+ meteringApiKey: "your_api_key",
342
+ meteringBaseUrl: "https://api.revenium.io/meter",
343
+ teamId: "your_team_id", // Optional
344
+ });
483
345
  ```
484
346
 
485
- **After (V1 Controller):**
486
-
487
- ```javascript
488
- import { PerplexityV1Controller } from "@revenium/perplexity";
489
- ```
347
+ #### `initializePerplexity(config)`
490
348
 
491
- **After (V2 Controller):**
349
+ Initialize Perplexity with custom configuration.
492
350
 
493
- ```javascript
494
- import { PerplexityV2Controller } from "@revenium/perplexity";
351
+ ```typescript
352
+ initializePerplexity({
353
+ apiKey: "your_perplexity_api_key",
354
+ baseUrl: "https://api.perplexity.ai", // Optional
355
+ });
495
356
  ```
496
357
 
497
- ### Step 4. Update Your Code
498
-
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");
358
+ ### Chat Completions
507
359
 
508
- console.log("[V1 EXAMPLE]", result.responses[0].text);
509
- console.log(`Tokens: ${result.usageMetadata.totalTokenCount}`);
510
- ```
360
+ #### `createChatCompletion(params)`
511
361
 
512
- #### V2 Controller Example (Enhanced)
362
+ Create a chat completion with automatic metering.
513
363
 
514
- ```javascript
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");
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
+ });
520
380
 
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`);
381
+ console.log(result.content);
382
+ console.log(result.usage);
383
+ console.log(result.transactionId);
524
384
  ```
525
385
 
526
- ---
527
-
528
- ## ๐Ÿ”ง Advanced Usage
386
+ **Parameters:**
529
387
 
530
- ### Streaming Responses
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)
531
396
 
532
- #### V1 Controller Streaming
533
-
534
- ```javascript
535
- import { PerplexityV1Controller } from "@revenium/perplexity";
397
+ **Returns:**
536
398
 
537
- const controller = new PerplexityV1Controller();
538
- const stream = await controller.createStreaming(["Hello world"], "sonar-pro");
539
-
540
- for await (const chunk of stream) {
541
- if (chunk.text) {
542
- process.stdout.write(chunk.text);
399
+ ```typescript
400
+ {
401
+ content: string;
402
+ role: string;
403
+ finishReason: string | null;
404
+ usage: {
405
+ promptTokens: number;
406
+ completionTokens: number;
407
+ totalTokens: number;
543
408
  }
409
+ model: string;
410
+ transactionId: string;
411
+ rawResponse: PerplexityResponse;
544
412
  }
545
413
  ```
546
414
 
547
- #### V2 Controller Streaming (Enhanced)
415
+ #### `createStreamingChatCompletion(params)`
548
416
 
549
- ```javascript
550
- import { PerplexityV2Controller } from "@revenium/perplexity";
417
+ Create a streaming chat completion.
551
418
 
552
- const controller = new PerplexityV2Controller();
553
- const stream = await controller.createStreaming(["Hello world"], "sonar-pro");
419
+ ```typescript
420
+ const result = await createStreamingChatCompletion({
421
+ messages: [{ role: "user", content: "Count from 1 to 5" }],
422
+ model: PERPLEXITY_MODELS.SONAR_PRO,
423
+ });
554
424
 
555
- for await (const chunk of stream) {
556
- const content = chunk.choices?.[0]?.delta?.content;
557
- if (content) {
558
- process.stdout.write(content);
559
- }
425
+ for await (const chunk of result.stream) {
426
+ const content = chunk.choices[0]?.delta?.content || "";
427
+ process.stdout.write(content);
560
428
  }
561
429
  ```
562
430
 
563
- ### Custom Metadata Tracking
431
+ **Returns:**
564
432
 
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
- );
433
+ ```typescript
434
+ {
435
+ stream: AsyncGenerator<PerplexityStreamChunk>;
436
+ transactionId: string;
437
+ model: string;
438
+ }
581
439
  ```
582
440
 
583
- #### V2 Enhanced Metadata Example
441
+ ### Available Models
584
442
 
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
- };
443
+ ```typescript
444
+ import { PERPLEXITY_MODELS } from "@revenium/perplexity";
593
445
 
594
- const result = await controller.createChat(
595
- ["What is AI?"],
596
- "sonar-pro",
597
- customMetadata
598
- );
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"
599
450
 
600
- // V2 provides additional metadata
601
- console.log(`Processing time: ${result.metadata.processingTime}ms`);
602
- console.log(`Transaction ID: ${result.metadata.transactionId}`);
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"
603
455
  ```
604
456
 
605
- ## ๐Ÿ“Š What Gets Tracked
606
-
607
- ### V1 Controller Tracking
457
+ ### Utility Functions
608
458
 
609
- - **Token Usage**: Input and output tokens for accurate billing
610
- - **Request Duration**: Total time for each API call
611
- - **Model Information**: Which model was used
612
- - **Operation Type**: Chat completion, streaming
613
- - **Error Tracking**: Failed requests and error details
614
- - **Custom Metadata**: Rich business context and user tracking
615
- - **Transaction ID**: Unique identifier for each request
459
+ #### `disableRevenium()` / `enableRevenium()`
616
460
 
617
- ### V2 Enhanced Tracking (Additional)
461
+ Temporarily disable or enable Revenium metering.
618
462
 
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
463
+ ```typescript
464
+ import { disableRevenium, enableRevenium } from "@revenium/perplexity";
624
465
 
625
- ---
466
+ disableRevenium(); // Stop sending metering data
467
+ // ... make API calls ...
468
+ enableRevenium(); // Resume sending metering data
469
+ ```
626
470
 
627
- ## ๐Ÿ”— Supported Models
471
+ #### `generateTransactionId()`
628
472
 
629
- ### Chat Models
473
+ Generate a unique transaction ID.
630
474
 
631
- - **sonar-pro** (Latest and most capable)
632
- - **sonar-small** (Fast and efficient)
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)
475
+ ```typescript
476
+ import { generateTransactionId } from "@revenium/perplexity";
637
477
 
638
- ### Model Capabilities
478
+ const txnId = generateTransactionId();
479
+ ```
639
480
 
640
- Both V1 and V2 Controllers support:
481
+ ## ๐Ÿ“– Examples
641
482
 
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
483
+ ### Basic Chat Completion
646
484
 
647
- _Note: Model availability depends on your Perplexity AI account and API access level._
485
+ ```typescript
486
+ import {
487
+ initializeReveniumFromEnv,
488
+ initializePerplexityFromEnv,
489
+ createChatCompletion,
490
+ PERPLEXITY_MODELS,
491
+ } from "@revenium/perplexity";
648
492
 
649
- ---
493
+ initializeReveniumFromEnv();
494
+ initializePerplexityFromEnv();
650
495
 
651
- ## ๐Ÿ› ๏ธ Configuration Options
496
+ const result = await createChatCompletion({
497
+ messages: [{ role: "user", content: "What is the capital of France?" }],
498
+ model: PERPLEXITY_MODELS.SONAR_PRO,
499
+ });
652
500
 
653
- ### Environment Variables
501
+ console.log(result.content);
502
+ ```
654
503
 
655
- | Variable | Required | Description |
656
- | ---------------------------- | -------- | ---------------------------------------------------------- |
657
- | `PERPLEXITY_API_KEY` | โœ… | Your Perplexity API key |
658
- | `REVENIUM_METERING_API_KEY` | โœ… | Your Revenium API key |
659
- | `REVENIUM_METERING_BASE_URL` | โŒ | Revenium base URL (default: https://api.revenium.io/meter) |
504
+ ### Streaming Response
660
505
 
661
- ---
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
+ });
662
511
 
663
- ## ๐Ÿšจ Troubleshooting
512
+ for await (const chunk of result.stream) {
513
+ const content = chunk.choices[0]?.delta?.content || "";
514
+ process.stdout.write(content);
515
+ }
516
+ ```
664
517
 
665
- ### Common Issues
518
+ ### Multi-turn Conversation
666
519
 
667
- **"Missing API Key" Error**
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
+ ];
668
525
 
669
- ```bash
670
- export PERPLEXITY_API_KEY="your-actual-api-key"
671
- echo $PERPLEXITY_API_KEY # Verify it's set
672
- ```
526
+ const response1 = await createChatCompletion({
527
+ messages,
528
+ model: PERPLEXITY_MODELS.SONAR_PRO,
529
+ });
673
530
 
674
- **"Requests not being tracked"**
531
+ messages.push({ role: "assistant", content: response1.content });
532
+ messages.push({ role: "user", content: "What is its population?" });
675
533
 
676
- ```bash
677
- export REVENIUM_METERING_API_KEY="your-actual-revenium-key"
534
+ const response2 = await createChatCompletion({
535
+ messages,
536
+ model: PERPLEXITY_MODELS.SONAR_PRO,
537
+ });
678
538
  ```
679
539
 
680
- **Module Import Errors**
540
+ ### Custom Metadata
681
541
 
682
- ```json
683
- {
684
- "type": "module"
685
- }
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
+ });
686
556
  ```
687
557
 
688
- This will show:
558
+ ## ๐Ÿ—๏ธ Project Structure
689
559
 
690
- - Request/response details
691
- - Token counting information
692
- - Metering data being sent
693
- - Error details
694
- - Middleware activation status
695
-
696
- ---
697
-
698
- ## ๐Ÿ“š Examples Repository
699
-
700
- Check out our comprehensive examples organized by version:
701
-
702
- ### V1 Controller Examples (Compatible)
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
+ ```
703
577
 
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
578
+ ## ๐Ÿงช Running Examples
709
579
 
710
- ### V2 Controller Examples (Enhanced)
580
+ ### TypeScript Examples
711
581
 
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
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
+ ```
717
588
 
718
- ### File Organization
589
+ ### JavaScript Playground
719
590
 
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)
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
+ ```
724
597
 
725
- ---
598
+ ## ๐Ÿ”’ Environment Variables
726
599
 
727
- ## ๐Ÿ“‹ Requirements
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`) |
728
605
 
729
- - Node.js 18+
730
- - Perplexity API key
731
- - Revenium API key
606
+ ## ๐Ÿ“„ License
732
607
 
733
- ---
608
+ ISC
734
609
 
735
- ## ๐Ÿ“„ License
610
+ ## ๐Ÿค Contributing
736
611
 
737
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
612
+ Contributions are welcome! Please feel free to submit a Pull Request.
738
613
 
739
- ---
614
+ ## ๐Ÿ“ž Support
740
615
 
741
- ## ๐Ÿค Support
616
+ For issues and questions:
742
617
 
743
- - ๐Ÿ“– [Documentation](https://docs.revenium.com)
744
- - ๐Ÿ’ฌ [Community Support](https://community.revenium.com)
745
- - ๐Ÿ“ง [Email Support](mailto:support@revenium.com)
746
- - ๐Ÿ› [Report Issues](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
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)
747
620
 
748
- ---
621
+ ## ๐Ÿ”— Links
749
622
 
750
- **Built with โค๏ธ by Revenium**
623
+ - [Perplexity AI Documentation](https://docs.perplexity.ai)
624
+ - [Revenium Platform](https://revenium.io)
625
+ - [npm Package](https://www.npmjs.com/package/@revenium/perplexity)