@revenium/perplexity 1.0.23 โ†’ 2.0.1

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 (123) hide show
  1. package/README.md +468 -364
  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 -16
  45. package/.env.example +0 -3
  46. package/dist/index.js +0 -19
  47. package/dist/interfaces/chatCompletionRequest.d.ts +0 -9
  48. package/dist/interfaces/chatCompletionRequest.js +0 -2
  49. package/dist/interfaces/credential.d.ts +0 -4
  50. package/dist/interfaces/credential.js +0 -2
  51. package/dist/interfaces/meteringRequest.d.ts +0 -13
  52. package/dist/interfaces/meteringRequest.js +0 -2
  53. package/dist/interfaces/meteringResponse.d.ts +0 -27
  54. package/dist/interfaces/meteringResponse.js +0 -2
  55. package/dist/interfaces/operation.d.ts +0 -4
  56. package/dist/interfaces/operation.js +0 -8
  57. package/dist/interfaces/subscriber.d.ts +0 -8
  58. package/dist/interfaces/subscriber.js +0 -2
  59. package/dist/interfaces/tokenCounts.d.ts +0 -7
  60. package/dist/interfaces/tokenCounts.js +0 -2
  61. package/dist/interfaces/usageMetadata.d.ts +0 -27
  62. package/dist/interfaces/usageMetadata.js +0 -2
  63. package/dist/middleware.d.ts +0 -22
  64. package/dist/middleware.js +0 -129
  65. package/dist/models/Logger.js +0 -35
  66. package/dist/models/Metering.d.ts +0 -9
  67. package/dist/models/Metering.js +0 -80
  68. package/dist/utils/calculateDurationMs.d.ts +0 -1
  69. package/dist/utils/calculateDurationMs.js +0 -6
  70. package/dist/utils/constants/constants.d.ts +0 -6
  71. package/dist/utils/constants/constants.js +0 -11
  72. package/dist/utils/constants/logLevels.d.ts +0 -1
  73. package/dist/utils/constants/logLevels.js +0 -4
  74. package/dist/utils/constants/messages.d.ts +0 -5
  75. package/dist/utils/constants/messages.js +0 -8
  76. package/dist/utils/constants/models.d.ts +0 -1
  77. package/dist/utils/constants/models.js +0 -21
  78. package/dist/utils/extractTokenCount.d.ts +0 -2
  79. package/dist/utils/extractTokenCount.js +0 -28
  80. package/dist/utils/formatTimeStamp.d.ts +0 -1
  81. package/dist/utils/formatTimeStamp.js +0 -6
  82. package/dist/utils/generateTransactionId.d.ts +0 -1
  83. package/dist/utils/generateTransactionId.js +0 -7
  84. package/dist/utils/index.d.ts +0 -6
  85. package/dist/utils/index.js +0 -23
  86. package/dist/utils/loadEnv.d.ts +0 -1
  87. package/dist/utils/loadEnv.js +0 -7
  88. package/dist/utils/safeExtract.d.ts +0 -29
  89. package/dist/utils/safeExtract.js +0 -67
  90. package/examples/basic.ts +0 -17
  91. package/examples/chat-completions.ts +0 -22
  92. package/examples/enhanced.ts +0 -20
  93. package/examples/metadata.ts +0 -43
  94. package/examples/streaming.ts +0 -24
  95. package/playground/basic.js +0 -17
  96. package/playground/chat-completions.js +0 -22
  97. package/playground/enhanced.js +0 -20
  98. package/playground/metadata.js +0 -43
  99. package/playground/streaming.js +0 -24
  100. package/src/index.ts +0 -4
  101. package/src/interfaces/chatCompletionRequest.ts +0 -10
  102. package/src/interfaces/credential.ts +0 -4
  103. package/src/interfaces/meteringRequest.ts +0 -14
  104. package/src/interfaces/meteringResponse.ts +0 -28
  105. package/src/interfaces/operation.ts +0 -4
  106. package/src/interfaces/subscriber.ts +0 -8
  107. package/src/interfaces/tokenCounts.ts +0 -7
  108. package/src/interfaces/usageMetadata.ts +0 -27
  109. package/src/middleware.ts +0 -157
  110. package/src/models/Logger.ts +0 -38
  111. package/src/models/Metering.ts +0 -114
  112. package/src/utils/calculateDurationMs.ts +0 -3
  113. package/src/utils/constants/constants.ts +0 -10
  114. package/src/utils/constants/logLevels.ts +0 -1
  115. package/src/utils/constants/messages.ts +0 -11
  116. package/src/utils/constants/models.ts +0 -20
  117. package/src/utils/extractTokenCount.ts +0 -26
  118. package/src/utils/formatTimestamp.ts +0 -3
  119. package/src/utils/generateTransactionId.ts +0 -5
  120. package/src/utils/index.ts +0 -39
  121. package/src/utils/loadEnv.ts +0 -8
  122. package/src/utils/safeExtract.ts +0 -67
  123. package/tsconfig.json +0 -15
package/README.md CHANGED
@@ -1,521 +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 middleware provides seamless integration with Perplexity AI SDK, requiring minimal code changes.
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
- ## ๐Ÿš€ Getting Started
8
+ ## ๐Ÿš€ Features
11
9
 
12
- You have 3 options to start using Revenium middleware for Perplexity AI:
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
13
17
 
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) |
18
+ ## ๐Ÿ“‹ Table of Contents
19
19
 
20
- ---
21
-
22
- ## Option 1: Create Project from Scratch
20
+ - [Installation](#-installation)
21
+ - [Three Ways to Use This Middleware](#-three-ways-to-use-this-middleware)
22
+ - [Option 1: New Project with npm Package](#option-1-new-project-with-npm-package-recommended)
23
+ - [Option 2: Clone and Use Locally](#option-2-clone-and-use-locally)
24
+ - [Option 3: Add to Existing Project](#option-3-add-to-existing-project)
25
+ - [Quick Start](#-quick-start)
26
+ - [API Reference](#-api-reference)
27
+ - [Examples](#-examples)
28
+ - [Environment Variables](#-environment-variables)
23
29
 
24
- ### Step 1: Create Project Directory
30
+ ## ๐Ÿ“ฆ Installation
25
31
 
26
32
  ```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
+ npm install @revenium/perplexity
33
34
  ```
34
35
 
35
- ### Step 2: Install Dependencies
36
+ ## ๐ŸŽฏ Three Ways to Use This Middleware
36
37
 
37
- ```bash
38
- npm install @revenium/perplexity
39
- ```
38
+ ### Option 1: New Project with npm Package (Recommended)
40
39
 
41
- ### Step 3: Setup Environment Variables
40
+ **Best for:** Starting a new project or adding Perplexity with Revenium to an existing project.
42
41
 
43
- Create a `.env` file in your project root:
42
+ #### Step 1: Create a new project
44
43
 
45
44
  ```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
45
+ mkdir my-perplexity-project
46
+ cd my-perplexity-project
47
+ npm init -y
52
48
  ```
53
49
 
54
- Copy and paste the following into `.env`:
50
+ #### Step 2: Install the middleware
55
51
 
56
52
  ```bash
57
- # Perplexity AI Configuration
58
- PERPLEXITY_API_KEY="your_perplexity_api_key_here"
53
+ npm install @revenium/perplexity dotenv
54
+ ```
59
55
 
60
- # Revenium Configuration
61
- REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
62
- REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
56
+ #### Step 3: Create `.env` file
63
57
 
64
- ```
58
+ ```env
59
+ # Perplexity API Configuration
60
+ PERPLEXITY_API_KEY=your_perplexity_api_key
65
61
 
66
- ### Step 4: Create Your First Test
62
+ # Revenium Metering Configuration
63
+ REVENIUM_METERING_API_KEY=your_revenium_api_key
64
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
65
+ ```
67
66
 
68
- Create `test-perplexity.js`:
67
+ #### Step 4: Create `index.js`
69
68
 
70
69
  ```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
- };
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
+ }
96
91
 
97
- basicExample();
92
+ main().catch(console.error);
98
93
  ```
99
94
 
100
- ### Step 5: Update package.json
101
-
102
- Add test scripts and module type to your `package.json`:
95
+ #### Step 5: Run your project
103
96
 
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
- }
97
+ ```bash
98
+ node index.js
116
99
  ```
117
100
 
118
- โš ๏ธ **Important**: If you get this error when running tests:
101
+ ---
102
+
103
+ ### Option 2: Clone and Use Locally
119
104
 
105
+ **Best for:** Development, testing, or contributing to the middleware.
106
+
107
+ #### Step 1: Clone the repository
108
+
109
+ ```bash
110
+ git clone https://github.com/revenium/revenium-middleware-perplexity-node.git
111
+ cd revenium-middleware-perplexity-node
120
112
  ```
121
- SyntaxError: Cannot use import statement outside a module
113
+
114
+ #### Step 2: Install dependencies
115
+
116
+ ```bash
117
+ npm install
122
118
  ```
123
119
 
124
- Make sure your `package.json` includes `"type": "module"` as shown below.
120
+ #### Step 3: Create `.env` file
125
121
 
126
- ```json
127
- {
128
- "type": "module"
129
- }
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
130
129
  ```
131
130
 
132
- ### Step 6: Run Your Tests
131
+ #### Step 4: Build the project
133
132
 
134
133
  ```bash
135
- # Test Perplexity AI SDK
136
- npm run test-perplexity
134
+ npm run build
137
135
  ```
138
136
 
139
- ### Step 7: Create Advanced Examples
137
+ #### Step 5: Run examples
138
+
139
+ **TypeScript Examples:**
140
140
 
141
- Create an examples directory and add these files:
141
+ ```bash
142
+ npm run example:basic # Basic chat completion
143
+ npm run example:streaming # Streaming response
144
+ npm run example:chat # Multi-turn conversation
145
+ npm run example:metadata # Custom metadata
146
+ ```
147
+
148
+ **JavaScript Playground:**
142
149
 
143
150
  ```bash
144
- mkdir examples
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
145
155
  ```
146
156
 
147
- #### Streaming Example
157
+ #### Step 6: Use in your own code
148
158
 
149
- Create `examples/streaming-perplexity.js`:
159
+ After building, you can import from the local build:
150
160
 
151
161
  ```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
- };
162
+ const {
163
+ initializeReveniumFromEnv,
164
+ initializePerplexityFromEnv,
165
+ createChatCompletion,
166
+ } = require("./dist/cjs");
186
167
 
187
- streamingExample();
168
+ // Your code here...
188
169
  ```
189
170
 
190
- #### METADATA Example
171
+ ---
191
172
 
192
- Create `examples/metadata-perplexity.js`:
173
+ ### Option 3: Add to Existing Project
193
174
 
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
- 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);
233
- } catch (error) {
234
- console.error("โŒ Perplexity streaming example failed:", error);
235
- process.exit(1);
236
- }
237
- };
175
+ **Best for:** Integrating Perplexity with Revenium into an existing Node.js project.
238
176
 
239
- metadataExample();
177
+ #### Step 1: Install the middleware
178
+
179
+ ```bash
180
+ npm install @revenium/perplexity
240
181
  ```
241
182
 
242
- ### Step 8: Update package.json
183
+ #### Step 2: Add environment variables
243
184
 
244
- ```json
245
- {
246
- "name": "my-perplexity-ai-project",
247
- "version": "1.0.0",
248
- "type": "module",
249
- "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"
253
- },
254
- "dependencies": {
255
- "@revenium/perplexity": "^1.0.0"
256
- }
257
- }
185
+ Add to your existing `.env` file:
186
+
187
+ ```env
188
+ # Perplexity API Configuration
189
+ PERPLEXITY_API_KEY=your_perplexity_api_key
190
+
191
+ # Revenium Metering Configuration
192
+ REVENIUM_METERING_API_KEY=your_revenium_api_key
193
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
258
194
  ```
259
195
 
260
- ### Step 9: Test Advanced Examples
196
+ #### Step 3: Initialize in your application
261
197
 
262
- ```bash
263
- # Test streaming
264
- npm run test-perplexity-stream
198
+ **For CommonJS projects:**
265
199
 
266
- # Test metadata
267
- npm run test-perplexity-metadata
200
+ ```javascript
201
+ require("dotenv").config();
202
+ const {
203
+ initializeReveniumFromEnv,
204
+ initializePerplexityFromEnv,
205
+ createChatCompletion,
206
+ PERPLEXITY_MODELS,
207
+ } = require("@revenium/perplexity");
208
+
209
+ // Initialize once at app startup
210
+ initializeReveniumFromEnv();
211
+ initializePerplexityFromEnv();
212
+
213
+ // Use anywhere in your app
214
+ async function askPerplexity(question) {
215
+ const result = await createChatCompletion({
216
+ messages: [{ role: "user", content: question }],
217
+ model: PERPLEXITY_MODELS.SONAR_PRO,
218
+ });
219
+ return result.content;
220
+ }
221
+ ```
268
222
 
223
+ **For ES Modules projects:**
224
+
225
+ ```javascript
226
+ import "dotenv/config";
227
+ import {
228
+ initializeReveniumFromEnv,
229
+ initializePerplexityFromEnv,
230
+ createChatCompletion,
231
+ PERPLEXITY_MODELS,
232
+ } from "@revenium/perplexity";
233
+
234
+ // Initialize once at app startup
235
+ initializeReveniumFromEnv();
236
+ initializePerplexityFromEnv();
237
+
238
+ // Use anywhere in your app
239
+ export async function askPerplexity(question) {
240
+ const result = await createChatCompletion({
241
+ messages: [{ role: "user", content: question }],
242
+ model: PERPLEXITY_MODELS.SONAR_PRO,
243
+ });
244
+ return result.content;
245
+ }
246
+ ```
247
+
248
+ **For TypeScript projects:**
249
+
250
+ ```typescript
251
+ import "dotenv/config";
252
+ import {
253
+ initializeReveniumFromEnv,
254
+ initializePerplexityFromEnv,
255
+ createChatCompletion,
256
+ PERPLEXITY_MODELS,
257
+ type ChatCompletionResult,
258
+ } from "@revenium/perplexity";
259
+
260
+ // Initialize once at app startup
261
+ initializeReveniumFromEnv();
262
+ initializePerplexityFromEnv();
263
+
264
+ // Use anywhere in your app
265
+ export async function askPerplexity(question: string): Promise<string> {
266
+ const result: ChatCompletionResult = await createChatCompletion({
267
+ messages: [{ role: "user", content: question }],
268
+ model: PERPLEXITY_MODELS.SONAR_PRO,
269
+ });
270
+ return result.content;
271
+ }
269
272
  ```
270
273
 
271
274
  ---
272
275
 
273
- ## Option 2: Clone Repository
276
+ ## ๐Ÿ”ง Quick Start
274
277
 
275
- Perfect for testing with pre-built examples:
278
+ ### 1. Set up environment variables
276
279
 
277
- ```bash
278
- # Clone the repository
279
- git clone git@github.com:revenium/revenium-middleware-perplexity-node.git
280
- cd revenium-middleware-perplexity-node
280
+ Create a `.env` file in your project root:
281
281
 
282
- # Install dependencies
283
- npm install
284
- npm install @revenium/perplexity
282
+ ```env
283
+ # Perplexity API Configuration
284
+ PERPLEXITY_API_KEY=your_perplexity_api_key
285
285
 
286
- # Create your .env file
287
- cp .env.example .env
288
- # 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
289
289
  ```
290
290
 
291
- ### Configure Environment Variables
291
+ ### 2. Initialize and use
292
292
 
293
- Edit your `.env` file:
293
+ ```typescript
294
+ import {
295
+ initializeReveniumFromEnv,
296
+ initializePerplexityFromEnv,
297
+ createChatCompletion,
298
+ PERPLEXITY_MODELS,
299
+ } from "@revenium/perplexity";
294
300
 
295
- ```bash
296
- # For Perplexity AI SDK
297
- PERPLEXITY_API_KEY="your_perplexity_api_key_here"
298
- REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
299
- REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
300
- ```
301
+ // Initialize configurations
302
+ initializeReveniumFromEnv();
303
+ initializePerplexityFromEnv();
301
304
 
302
- ### Run Perplexity AI 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
+ });
303
310
 
304
- ```bash
305
- # Perplexity AI examples
306
- ## Change type to commonjs in package.json
307
- "type": "commonjs",
308
- # Then run any of the following
309
- npm run e-basic # Basic chat completion
310
- npm run e-streaming # Streaming response
311
- npm run e-enhanced # Enhanced request
312
- npm run e-chat-completions # Chat completions
313
- npm run e-metadata # Metadata request
314
-
315
- # Playground examples
316
- # Required build first
317
- npm run build
318
- ## Change type to module in package.json
319
- "type": "module",
320
- # Then run any of the following
321
- npm run p-basic
322
- npm run p-streaming
323
- npm run p-enhanced
324
- npm run p-metadata
311
+ console.log(result.content);
312
+ // Output: "The capital of France is Paris."
325
313
  ```
326
314
 
327
- ---
315
+ ## ๐Ÿ“š API Reference
328
316
 
329
- ## Option 3: Existing Project Integration
317
+ ### Configuration
330
318
 
331
- Already have a project? Just install and replace imports:
319
+ #### `initializeReveniumFromEnv()`
332
320
 
333
- ### Step 1. Install the Package
321
+ Initialize Revenium configuration from environment variables.
334
322
 
335
- ```bash
336
- npm install @revenium/perplexity
323
+ ```typescript
324
+ const config = initializeReveniumFromEnv();
337
325
  ```
338
326
 
339
- ### Step 2. Add Environment Variables
327
+ #### `initializePerplexityFromEnv()`
340
328
 
341
- Add to your existing `.env` file:
329
+ Initialize Perplexity configuration from environment variables.
342
330
 
343
- ```bash
344
- PERPLEXITY_API_KEY="your_perplexity_api_key_here"
345
- REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
346
- REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
331
+ ```typescript
332
+ const config = initializePerplexityFromEnv();
347
333
  ```
348
334
 
349
- ### Step 3. Replace Your Imports
335
+ #### `initializeRevenium(config)`
350
336
 
351
- **Before:**
337
+ Initialize Revenium with custom configuration.
352
338
 
353
- ```javascript
354
- 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
+ });
355
345
  ```
356
346
 
357
- **After:**
347
+ #### `initializePerplexity(config)`
358
348
 
359
- ```javascript
360
- import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
349
+ Initialize Perplexity with custom configuration.
350
+
351
+ ```typescript
352
+ initializePerplexity({
353
+ apiKey: "your_perplexity_api_key",
354
+ baseUrl: "https://api.perplexity.ai", // Optional
355
+ });
361
356
  ```
362
357
 
363
- ### Step 4. Update Your Code
358
+ ### Chat Completions
364
359
 
365
- #### Revenium Client Example
360
+ #### `createChatCompletion(params)`
366
361
 
367
- ```javascript
368
- import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
362
+ Create a chat completion with automatic metering.
369
363
 
370
- // Initialize (API key from environment variable)
371
- const middleware = new PerplexityReveniumMiddleware();
372
- const model = middleware.getGenerativeModel("sonar-pro");
373
- const result = await model.createChatCompletion({
364
+ ```typescript
365
+ const result = await createChatCompletion({
374
366
  messages: [
375
- {
376
- role: "user",
377
- content: "Hello world",
378
- },
367
+ { role: "system", content: "You are a helpful assistant." },
368
+ { role: "user", content: "Hello!" },
379
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
+ },
380
379
  });
381
- console.log("[BASIC EXAMPLE]", result.choices[0].message.content);
380
+
381
+ console.log(result.content);
382
+ console.log(result.usage);
383
+ console.log(result.transactionId);
382
384
  ```
383
385
 
384
- ---
386
+ **Parameters:**
387
+
388
+ - `messages` - Array of message objects with `role` and `content`
389
+ - `model` - Perplexity model to use (see [Available Models](#available-models))
390
+ - `maxTokens` - Maximum tokens to generate (optional)
391
+ - `temperature` - Sampling temperature 0-2 (optional)
392
+ - `topP` - Nucleus sampling parameter (optional)
393
+ - `presencePenalty` - Presence penalty -2 to 2 (optional)
394
+ - `frequencyPenalty` - Frequency penalty -2 to 2 (optional)
395
+ - `usageMetadata` - Custom metadata for tracking (optional)
396
+
397
+ **Returns:**
385
398
 
386
- ## ๐Ÿ”ง Advanced Usage
399
+ ```typescript
400
+ {
401
+ content: string;
402
+ role: string;
403
+ finishReason: string | null;
404
+ usage: {
405
+ promptTokens: number;
406
+ completionTokens: number;
407
+ totalTokens: number;
408
+ }
409
+ model: string;
410
+ transactionId: string;
411
+ rawResponse: PerplexityResponse;
412
+ }
413
+ ```
387
414
 
388
- ### Streaming Responses
415
+ #### `createStreamingChatCompletion(params)`
389
416
 
390
- #### Revenium Client Streaming
417
+ Create a streaming chat completion.
391
418
 
392
- ```javascript
393
- const stream = await model.createChatCompletionStream({
394
- messages: [
395
- {
396
- role: "user",
397
- content: "Hello world",
398
- },
399
- ],
419
+ ```typescript
420
+ const result = await createStreamingChatCompletion({
421
+ messages: [{ role: "user", content: "Count from 1 to 5" }],
422
+ model: PERPLEXITY_MODELS.SONAR_PRO,
400
423
  });
401
- for await (const chunk of stream) {
402
- process.stdout.write(chunk.choices[0]?.delta?.content || "");
424
+
425
+ for await (const chunk of result.stream) {
426
+ const content = chunk.choices[0]?.delta?.content || "";
427
+ process.stdout.write(content);
403
428
  }
404
429
  ```
405
430
 
406
- ## ๐Ÿ“Š What Gets Tracked
431
+ **Returns:**
407
432
 
408
- - **Token Usage**: Input and output tokens for accurate billing
409
- - **Request Duration**: Total time for each API call
410
- - **Model Information**: Which model was used
411
- - **Operation Type**: Chat completion, streaming
412
- - **Error Tracking**: Failed requests and error details
413
- - **Streaming Metrics**: Time to first token for streaming responses
414
- - **Custom Metadata**: Rich business context and user tracking
415
-
416
- ---
433
+ ```typescript
434
+ {
435
+ stream: AsyncGenerator<PerplexityStreamChunk>;
436
+ transactionId: string;
437
+ model: string;
438
+ }
439
+ ```
417
440
 
418
- ## ๐Ÿ”— Supported Models
441
+ ### Available Models
419
442
 
420
- ### Chat Models
443
+ ```typescript
444
+ import { PERPLEXITY_MODELS } from "@revenium/perplexity";
421
445
 
422
- - **sonar-pro** (Latest and most capable)
423
- - **sonar-small** (Fast and efficient)
424
- - **sonar-medium** (Balanced performance)
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"
425
450
 
426
- _Note: Model availability depends on your Perplexity AI account and API access level._
451
+ // Chat Models (offline)
452
+ PERPLEXITY_MODELS.LLAMA_3_1_SONAR_SMALL_128K_CHAT; // "llama-3.1-sonar-small-128k-chat"
453
+ PERPLEXITY_MODELS.LLAMA_3_1_SONAR_LARGE_128K_CHAT; // "llama-3.1-sonar-large-128k-chat"
454
+ PERPLEXITY_MODELS.LLAMA_3_1_SONAR_HUGE_128K_CHAT; // "llama-3.1-sonar-huge-128k-chat"
455
+ ```
427
456
 
428
- ---
457
+ ### Utility Functions
429
458
 
430
- ## ๐Ÿ› ๏ธ Configuration Options
459
+ #### `disableRevenium()` / `enableRevenium()`
431
460
 
432
- ### Environment Variables
461
+ Temporarily disable or enable Revenium metering.
433
462
 
434
- | Variable | Required | Description |
435
- | ---------------------------- | -------- | ---------------------------------------------------------- |
436
- | `PERPLEXITY_API_KEY` | โœ… | Your Perplexity API key |
437
- | `REVENIUM_METERING_API_KEY` | โœ… | Your Revenium API key |
438
- | `REVENIUM_METERING_BASE_URL` | โŒ | Revenium base URL (default: https://api.revenium.io/meter) |
463
+ ```typescript
464
+ import { disableRevenium, enableRevenium } from "@revenium/perplexity";
439
465
 
440
- ---
466
+ disableRevenium(); // Stop sending metering data
467
+ // ... make API calls ...
468
+ enableRevenium(); // Resume sending metering data
469
+ ```
441
470
 
442
- ## ๐Ÿšจ Troubleshooting
471
+ #### `generateTransactionId()`
443
472
 
444
- ### Common Issues
473
+ Generate a unique transaction ID.
445
474
 
446
- **"Missing API Key" Error**
475
+ ```typescript
476
+ import { generateTransactionId } from "@revenium/perplexity";
447
477
 
448
- ```bash
449
- export PERPLEXITY_API_KEY="your-actual-api-key"
450
- echo $PERPLEXITY_API_KEY # Verify it's set
478
+ const txnId = generateTransactionId();
451
479
  ```
452
480
 
453
- **"Requests not being tracked"**
481
+ ## ๐Ÿ“– Examples
454
482
 
455
- ```bash
456
- export REVENIUM_METERING_API_KEY="your-actual-revenium-key"
483
+ ### Basic Chat Completion
484
+
485
+ ```typescript
486
+ import {
487
+ initializeReveniumFromEnv,
488
+ initializePerplexityFromEnv,
489
+ createChatCompletion,
490
+ PERPLEXITY_MODELS,
491
+ } from "@revenium/perplexity";
492
+
493
+ initializeReveniumFromEnv();
494
+ initializePerplexityFromEnv();
495
+
496
+ const result = await createChatCompletion({
497
+ messages: [{ role: "user", content: "What is the capital of France?" }],
498
+ model: PERPLEXITY_MODELS.SONAR_PRO,
499
+ });
500
+
501
+ console.log(result.content);
457
502
  ```
458
503
 
459
- **Module Import Errors**
504
+ ### Streaming Response
460
505
 
461
- ```json
462
- {
463
- "type": "module"
506
+ ```typescript
507
+ const result = await createStreamingChatCompletion({
508
+ messages: [{ role: "user", content: "Write a short poem about AI" }],
509
+ model: PERPLEXITY_MODELS.SONAR_PRO,
510
+ });
511
+
512
+ for await (const chunk of result.stream) {
513
+ const content = chunk.choices[0]?.delta?.content || "";
514
+ process.stdout.write(content);
464
515
  }
465
516
  ```
466
517
 
467
- ```json
468
- {
469
- "type": "commonjs"
470
- }
518
+ ### Multi-turn Conversation
519
+
520
+ ```typescript
521
+ const messages = [
522
+ { role: "system", content: "You are a helpful assistant." },
523
+ { role: "user", content: "What is the capital of France?" },
524
+ ];
525
+
526
+ const response1 = await createChatCompletion({
527
+ messages,
528
+ model: PERPLEXITY_MODELS.SONAR_PRO,
529
+ });
530
+
531
+ messages.push({ role: "assistant", content: response1.content });
532
+ messages.push({ role: "user", content: "What is its population?" });
533
+
534
+ const response2 = await createChatCompletion({
535
+ messages,
536
+ model: PERPLEXITY_MODELS.SONAR_PRO,
537
+ });
471
538
  ```
472
539
 
473
- This will show:
540
+ ### Custom Metadata
474
541
 
475
- - Request/response details
476
- - Token counting information
477
- - Metering data being sent
478
- - Error details
479
- - Middleware activation status
542
+ ```typescript
543
+ const result = await createChatCompletion({
544
+ messages: [{ role: "user", content: "Hello!" }],
545
+ model: PERPLEXITY_MODELS.SONAR_PRO,
546
+ usageMetadata: {
547
+ subscriber: {
548
+ id: "user-123",
549
+ email: "user@example.com",
550
+ },
551
+ organizationId: "org-456",
552
+ productId: "premium-plan",
553
+ traceId: "trace-abc-123",
554
+ },
555
+ });
556
+ ```
480
557
 
481
- ---
558
+ ## ๐Ÿ—๏ธ Project Structure
482
559
 
483
- ## ๐Ÿ“š Examples Repository
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
+ ```
484
577
 
485
- Check out our comprehensive examples:
578
+ ## ๐Ÿงช Running Examples
486
579
 
487
- - **Basic Usage**: Simple chat completions
488
- - **Streaming**: Real-time response streaming
489
- - **Metadata**: Rich tracking examples
490
- - **Error Handling**: Robust error management
491
- - **Advanced Patterns**: Complex use cases
492
- - **Configuration**: Different setup options
580
+ ### TypeScript Examples
493
581
 
494
- All examples are in the `/examples` and `/playground` directories.
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
+ ```
495
588
 
496
- ---
589
+ ### JavaScript Playground
497
590
 
498
- ## ๐Ÿ“‹ Requirements
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
+ ```
499
597
 
500
- - Node.js 18+
501
- - Perplexity API key
502
- - Revenium API key
598
+ ## ๐Ÿ”’ Environment Variables
503
599
 
504
- ---
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`) |
505
605
 
506
606
  ## ๐Ÿ“„ License
507
607
 
508
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
608
+ ISC
509
609
 
510
- ---
610
+ ## ๐Ÿค Contributing
511
611
 
512
- ## ๐Ÿค Support
612
+ Contributions are welcome! Please feel free to submit a Pull Request.
513
613
 
514
- - ๐Ÿ“– [Documentation](https://docs.revenium.com)
515
- - ๐Ÿ’ฌ [Community Support](https://community.revenium.com)
516
- - ๐Ÿ“ง [Email Support](mailto:support@revenium.com)
517
- - ๐Ÿ› [Report Issues](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
614
+ ## ๐Ÿ“ž Support
518
615
 
519
- ---
616
+ For issues and questions:
617
+
618
+ - GitHub Issues: [revenium-middleware-perplexity-node/issues](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
619
+ - Documentation: [Revenium Docs](https://docs.revenium.io)
620
+
621
+ ## ๐Ÿ”— Links
520
622
 
521
- **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)