@revenium/perplexity 2.0.3 → 2.0.5

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 (183) hide show
  1. package/CHANGELOG.md +47 -10
  2. package/README.md +144 -720
  3. package/SECURITY.md +34 -0
  4. package/dist/cjs/constants/models.js +38 -0
  5. package/dist/cjs/constants/models.js.map +1 -0
  6. package/dist/cjs/core/client/index.js +13 -0
  7. package/dist/cjs/core/client/index.js.map +1 -0
  8. package/dist/cjs/core/client/manager.js +85 -0
  9. package/dist/cjs/core/client/manager.js.map +1 -0
  10. package/dist/cjs/core/config/index.js +21 -0
  11. package/dist/cjs/core/config/index.js.map +1 -0
  12. package/dist/cjs/core/config/loader.js +48 -0
  13. package/dist/cjs/core/config/loader.js.map +1 -0
  14. package/dist/cjs/core/config/manager.js +77 -0
  15. package/dist/cjs/core/config/manager.js.map +1 -0
  16. package/dist/cjs/core/config/validator.js +45 -0
  17. package/dist/cjs/core/config/validator.js.map +1 -0
  18. package/dist/cjs/core/middleware/index.js +14 -0
  19. package/dist/cjs/core/middleware/index.js.map +1 -0
  20. package/dist/cjs/core/middleware/interfaces.js +94 -0
  21. package/dist/cjs/core/middleware/interfaces.js.map +1 -0
  22. package/dist/cjs/core/middleware/revenium-client.js +44 -0
  23. package/dist/cjs/core/middleware/revenium-client.js.map +1 -0
  24. package/dist/cjs/core/middleware/streaming-wrapper.js +80 -0
  25. package/dist/cjs/core/middleware/streaming-wrapper.js.map +1 -0
  26. package/dist/cjs/core/providers/detector.js +38 -0
  27. package/dist/cjs/core/providers/detector.js.map +1 -0
  28. package/dist/cjs/core/providers/index.js +14 -0
  29. package/dist/cjs/core/providers/index.js.map +1 -0
  30. package/dist/cjs/core/tracking/api-client.js +67 -0
  31. package/dist/cjs/core/tracking/api-client.js.map +1 -0
  32. package/dist/cjs/core/tracking/index.js +21 -0
  33. package/dist/cjs/core/tracking/index.js.map +1 -0
  34. package/dist/cjs/core/tracking/payload-builder.js +95 -0
  35. package/dist/cjs/core/tracking/payload-builder.js.map +1 -0
  36. package/dist/cjs/core/tracking/usage-tracker.js +83 -0
  37. package/dist/cjs/core/tracking/usage-tracker.js.map +1 -0
  38. package/dist/cjs/index.js +60 -54
  39. package/dist/cjs/index.js.map +1 -0
  40. package/dist/cjs/types/function-parameters.js +14 -0
  41. package/dist/cjs/types/function-parameters.js.map +1 -0
  42. package/dist/cjs/types/index.js +20 -16
  43. package/dist/cjs/types/index.js.map +1 -0
  44. package/dist/cjs/utils/constants.js +20 -0
  45. package/dist/cjs/utils/constants.js.map +1 -0
  46. package/dist/cjs/utils/error-handler.js +194 -0
  47. package/dist/cjs/utils/error-handler.js.map +1 -0
  48. package/dist/cjs/utils/metadata-builder.js +191 -0
  49. package/dist/cjs/utils/metadata-builder.js.map +1 -0
  50. package/dist/cjs/utils/stop-reason-mapper.js +74 -0
  51. package/dist/cjs/utils/stop-reason-mapper.js.map +1 -0
  52. package/dist/cjs/utils/transaction-id.js +19 -0
  53. package/dist/cjs/utils/transaction-id.js.map +1 -0
  54. package/dist/cjs/utils/url-builder.js +57 -0
  55. package/dist/cjs/utils/url-builder.js.map +1 -0
  56. package/dist/esm/constants/models.js +35 -0
  57. package/dist/esm/constants/models.js.map +1 -0
  58. package/dist/esm/core/client/index.js +5 -0
  59. package/dist/esm/core/client/index.js.map +1 -0
  60. package/dist/esm/core/client/manager.js +78 -0
  61. package/dist/esm/core/client/manager.js.map +1 -0
  62. package/dist/esm/core/config/index.js +11 -0
  63. package/dist/esm/core/config/index.js.map +1 -0
  64. package/dist/esm/core/config/loader.js +45 -0
  65. package/dist/esm/core/config/loader.js.map +1 -0
  66. package/dist/esm/core/config/manager.js +70 -0
  67. package/dist/esm/core/config/manager.js.map +1 -0
  68. package/dist/esm/core/config/validator.js +42 -0
  69. package/dist/esm/core/config/validator.js.map +1 -0
  70. package/dist/esm/core/middleware/index.js +7 -0
  71. package/dist/esm/core/middleware/index.js.map +1 -0
  72. package/dist/esm/core/middleware/interfaces.js +89 -0
  73. package/dist/esm/core/middleware/interfaces.js.map +1 -0
  74. package/dist/esm/core/middleware/revenium-client.js +37 -0
  75. package/dist/esm/core/middleware/revenium-client.js.map +1 -0
  76. package/dist/esm/core/middleware/streaming-wrapper.js +76 -0
  77. package/dist/esm/core/middleware/streaming-wrapper.js.map +1 -0
  78. package/dist/esm/core/providers/detector.js +34 -0
  79. package/dist/esm/core/providers/detector.js.map +1 -0
  80. package/dist/esm/core/providers/index.js +9 -0
  81. package/dist/esm/core/providers/index.js.map +1 -0
  82. package/dist/esm/core/tracking/api-client.js +64 -0
  83. package/dist/esm/core/tracking/api-client.js.map +1 -0
  84. package/dist/esm/core/tracking/index.js +13 -0
  85. package/dist/esm/core/tracking/index.js.map +1 -0
  86. package/dist/esm/core/tracking/payload-builder.js +92 -0
  87. package/dist/esm/core/tracking/payload-builder.js.map +1 -0
  88. package/dist/esm/core/tracking/usage-tracker.js +79 -0
  89. package/dist/esm/core/tracking/usage-tracker.js.map +1 -0
  90. package/dist/esm/index.js +46 -36
  91. package/dist/esm/index.js.map +1 -0
  92. package/dist/esm/types/function-parameters.js +13 -0
  93. package/dist/esm/types/function-parameters.js.map +1 -0
  94. package/dist/esm/types/index.js +6 -15
  95. package/dist/esm/types/index.js.map +1 -0
  96. package/dist/esm/utils/constants.js +17 -0
  97. package/dist/esm/utils/constants.js.map +1 -0
  98. package/dist/esm/utils/error-handler.js +182 -0
  99. package/dist/esm/utils/error-handler.js.map +1 -0
  100. package/dist/esm/utils/metadata-builder.js +183 -0
  101. package/dist/esm/utils/metadata-builder.js.map +1 -0
  102. package/dist/esm/utils/stop-reason-mapper.js +69 -0
  103. package/dist/esm/utils/stop-reason-mapper.js.map +1 -0
  104. package/dist/esm/utils/transaction-id.js +16 -0
  105. package/dist/esm/utils/transaction-id.js.map +1 -0
  106. package/dist/esm/utils/url-builder.js +53 -0
  107. package/dist/esm/utils/url-builder.js.map +1 -0
  108. package/dist/types/constants/models.d.ts +39 -0
  109. package/dist/types/constants/models.d.ts.map +1 -0
  110. package/dist/types/core/client/index.d.ts +5 -0
  111. package/dist/types/core/client/index.d.ts.map +1 -0
  112. package/dist/types/core/client/manager.d.ts +44 -0
  113. package/dist/types/core/client/manager.d.ts.map +1 -0
  114. package/dist/types/core/config/index.d.ts +10 -0
  115. package/dist/types/core/config/index.d.ts.map +1 -0
  116. package/dist/types/core/config/loader.d.ts +13 -0
  117. package/dist/types/core/config/loader.d.ts.map +1 -0
  118. package/dist/types/core/config/manager.d.ts +28 -0
  119. package/dist/types/core/config/manager.d.ts.map +1 -0
  120. package/dist/types/core/config/validator.d.ts +12 -0
  121. package/dist/types/core/config/validator.d.ts.map +1 -0
  122. package/dist/types/core/middleware/index.d.ts +7 -0
  123. package/dist/types/core/middleware/index.d.ts.map +1 -0
  124. package/dist/types/core/middleware/interfaces.d.ts +35 -0
  125. package/dist/types/core/middleware/interfaces.d.ts.map +1 -0
  126. package/dist/types/core/middleware/revenium-client.d.ts +25 -0
  127. package/dist/types/core/middleware/revenium-client.d.ts.map +1 -0
  128. package/dist/types/core/middleware/streaming-wrapper.d.ts +21 -0
  129. package/dist/types/core/middleware/streaming-wrapper.d.ts.map +1 -0
  130. package/dist/types/core/providers/detector.d.ts +24 -0
  131. package/dist/types/core/providers/detector.d.ts.map +1 -0
  132. package/dist/types/core/providers/index.d.ts +8 -0
  133. package/dist/types/core/providers/index.d.ts.map +1 -0
  134. package/dist/types/core/tracking/api-client.d.ts +17 -0
  135. package/dist/types/core/tracking/api-client.d.ts.map +1 -0
  136. package/dist/types/core/tracking/index.d.ts +11 -0
  137. package/dist/types/core/tracking/index.d.ts.map +1 -0
  138. package/dist/types/core/tracking/payload-builder.d.ts +24 -0
  139. package/dist/types/core/tracking/payload-builder.d.ts.map +1 -0
  140. package/dist/types/core/tracking/usage-tracker.d.ts +30 -0
  141. package/dist/types/core/tracking/usage-tracker.d.ts.map +1 -0
  142. package/dist/types/index.d.ts +56 -27
  143. package/dist/types/index.d.ts.map +1 -0
  144. package/dist/types/types/function-parameters.d.ts +185 -0
  145. package/dist/types/types/function-parameters.d.ts.map +1 -0
  146. package/dist/types/types/index.d.ts +108 -137
  147. package/dist/types/types/index.d.ts.map +1 -0
  148. package/dist/types/utils/constants.d.ts +9 -0
  149. package/dist/types/utils/constants.d.ts.map +1 -0
  150. package/dist/types/utils/error-handler.d.ts +95 -0
  151. package/dist/types/utils/error-handler.d.ts.map +1 -0
  152. package/dist/types/utils/metadata-builder.d.ts +65 -0
  153. package/dist/types/utils/metadata-builder.d.ts.map +1 -0
  154. package/dist/types/utils/stop-reason-mapper.d.ts +29 -0
  155. package/dist/types/utils/stop-reason-mapper.d.ts.map +1 -0
  156. package/dist/types/utils/transaction-id.d.ts +14 -0
  157. package/dist/types/utils/transaction-id.d.ts.map +1 -0
  158. package/dist/types/utils/url-builder.d.ts +22 -0
  159. package/dist/types/utils/url-builder.d.ts.map +1 -0
  160. package/examples/README.md +136 -233
  161. package/examples/advanced.ts +123 -0
  162. package/examples/basic.ts +36 -46
  163. package/examples/getting_started.ts +41 -0
  164. package/examples/metadata.ts +55 -59
  165. package/examples/stream.ts +53 -0
  166. package/package.json +12 -17
  167. package/dist/cjs/core/config/perplexity-config.js +0 -45
  168. package/dist/cjs/core/config/revenium-config.js +0 -80
  169. package/dist/cjs/core/tracking/metering.js +0 -131
  170. package/dist/cjs/core/wrapper/perplexity-client.js +0 -177
  171. package/dist/cjs/utils/logger.js +0 -23
  172. package/dist/esm/core/config/perplexity-config.js +0 -40
  173. package/dist/esm/core/config/revenium-config.js +0 -72
  174. package/dist/esm/core/tracking/metering.js +0 -126
  175. package/dist/esm/core/wrapper/perplexity-client.js +0 -170
  176. package/dist/esm/utils/logger.js +0 -20
  177. package/dist/types/core/config/perplexity-config.d.ts +0 -24
  178. package/dist/types/core/config/revenium-config.d.ts +0 -37
  179. package/dist/types/core/tracking/metering.d.ts +0 -31
  180. package/dist/types/core/wrapper/perplexity-client.d.ts +0 -32
  181. package/dist/types/utils/logger.d.ts +0 -10
  182. package/examples/chat.ts +0 -87
  183. package/examples/streaming.ts +0 -61
package/README.md CHANGED
@@ -3,827 +3,251 @@
3
3
  A lightweight, production-ready middleware that adds **Revenium metering and tracking** to Perplexity AI API calls.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@revenium/perplexity.svg)](https://www.npmjs.com/package/@revenium/perplexity)
6
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
6
+ [![Node.js](https://img.shields.io/badge/Node.js-20%2B-green)](https://nodejs.org/)
7
+ [![Documentation](https://img.shields.io/badge/docs-revenium.io-blue)](https://docs.revenium.io)
8
+ [![Website](https://img.shields.io/badge/website-revenium.ai-blue)](https://www.revenium.ai)
9
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
10
 
8
11
  ## Features
9
12
 
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
+ - **Automatic Metering** - Tracks all API calls with detailed usage metrics
14
+ - **Streaming Support** - Full support for streaming responses
15
+ - **TypeScript First** - Built with TypeScript, includes full type definitions
16
+ - **Multi-Format** - Supports both ESM and CommonJS
17
+ - **Custom Metadata** - Add custom tracking metadata to any request
18
+ - **Production Ready** - Battle-tested and optimized for production use
17
19
 
18
- ## Package Migration
20
+ ## Getting Started
19
21
 
20
- This package has been renamed from `revenium-middleware-perplexity-node` to `@revenium/perplexity` for better organization and simpler naming.
21
-
22
- ### Migration Steps
23
-
24
- If you're upgrading from the old package:
25
-
26
- ```bash
27
- # Uninstall the old package
28
- npm uninstall revenium-middleware-perplexity-node
29
-
30
- # Install the new package
31
- npm install @revenium/perplexity
32
- ```
33
-
34
- **Update your imports:**
35
-
36
- ```typescript
37
- // Old import
38
- import "revenium-middleware-perplexity-node";
39
-
40
- // New import
41
- import "@revenium/perplexity";
42
- ```
43
-
44
- All functionality remains exactly the same - only the package name has changed.
45
-
46
- ## Table of Contents
47
-
48
- - [Installation](https://github.com/revenium/revenium-middleware-perplexity-node#-installation)
49
- - [Three Ways to Use This Middleware](https://github.com/revenium/revenium-middleware-perplexity-node#-three-ways-to-use-this-middleware)
50
- - [Option 1: New Project with npm Package](https://github.com/revenium/revenium-middleware-perplexity-node#option-1-new-project-with-npm-package-recommended)
51
- - [Option 2: Clone and Use Locally](https://github.com/revenium/revenium-middleware-perplexity-node#option-2-clone-and-use-locally)
52
- - [Option 3: Add to Existing Project](https://github.com/revenium/revenium-middleware-perplexity-node#option-3-add-to-existing-project)
53
- - [Quick Start](https://github.com/revenium/revenium-middleware-perplexity-node#-quick-start)
54
- - [API Reference](https://github.com/revenium/revenium-middleware-perplexity-node#-api-reference)
55
- - [Examples](https://github.com/revenium/revenium-middleware-perplexity-node#-examples)
56
- - [Environment Variables](https://github.com/revenium/revenium-middleware-perplexity-node#-environment-variables)
57
-
58
- ## Installation
22
+ ### Quick Start
59
23
 
60
24
  ```bash
61
- npm install @revenium/perplexity
25
+ npm install @revenium/perplexity dotenv
62
26
  ```
63
27
 
64
- ## Three Ways to Use This Middleware
28
+ For complete setup instructions, TypeScript patterns, and usage examples, see [examples/README.md](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/README.md).
65
29
 
66
- ### Option 1: New Project with npm Package (Recommended)
30
+ ### Step-by-Step Guide
67
31
 
68
- **Best for:** Starting a new project or adding Perplexity with Revenium to an existing project.
32
+ The following guide walks you through creating a new project from scratch:
69
33
 
70
- #### Step 1: Create a new project
34
+ #### Step 1: Create Your Project
71
35
 
72
36
  ```bash
37
+ # Create project directory
73
38
  mkdir my-perplexity-project
74
39
  cd my-perplexity-project
40
+
41
+ # Initialize npm project
75
42
  npm init -y
76
43
  ```
77
44
 
78
- #### Step 2: Install the middleware
45
+ #### Step 2: Install Dependencies
79
46
 
80
47
  ```bash
48
+ # Install Revenium middleware and Perplexity dependencies
81
49
  npm install @revenium/perplexity dotenv
82
- ```
83
-
84
- #### Step 3: Create `.env` file
85
-
86
- ```env
87
- # Perplexity API Configuration
88
- PERPLEXITY_API_KEY=your_perplexity_api_key
89
-
90
- # Revenium Metering Configuration
91
- REVENIUM_METERING_API_KEY=your_revenium_api_key
92
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
93
- ```
94
-
95
- #### Step 4: Create `index.js`
96
-
97
- ```javascript
98
- const {
99
- initializeReveniumFromEnv,
100
- initializePerplexityFromEnv,
101
- createChatCompletion,
102
- PERPLEXITY_MODELS,
103
- } = require("@revenium/perplexity");
104
50
 
105
- async function main() {
106
- // Initialize configurations
107
- initializeReveniumFromEnv();
108
- initializePerplexityFromEnv();
109
-
110
- // Create a chat completion
111
- const result = await createChatCompletion({
112
- messages: [{ role: "user", content: "What is the capital of France?" }],
113
- model: PERPLEXITY_MODELS.SONAR_PRO,
114
- });
115
-
116
- console.log("Response:", result.content);
117
- console.log("Tokens used:", result.usage.totalTokens);
118
- }
119
-
120
- main().catch(console.error);
121
- ```
122
-
123
- #### Step 5: Run your project
124
-
125
- ```bash
126
- node index.js
51
+ # For TypeScript projects (optional)
52
+ npm install -D typescript tsx @types/node
127
53
  ```
128
54
 
129
- ---
130
-
131
- ### Option 2: Clone and Use Locally
132
-
133
- **Best for:** Development, testing, or contributing to the middleware.
134
-
135
- #### Step 1: Clone the repository
136
-
137
- ```bash
138
- git clone https://github.com/revenium/revenium-middleware-perplexity-node.git
139
- cd revenium-middleware-perplexity-node
140
- ```
55
+ #### Step 3: Setup Environment Variables
141
56
 
142
- #### Step 2: Install dependencies
57
+ Create a `.env` file in your project root.
143
58
 
144
59
  ```bash
145
- npm install
146
- ```
147
-
148
- #### Step 3: Create `.env` file
149
-
150
- ```env
151
- # Perplexity API Configuration
152
- PERPLEXITY_API_KEY=your_perplexity_api_key
60
+ # Copy the example file
61
+ cp .env.example .env
153
62
 
154
- # Revenium Metering Configuration
155
- REVENIUM_METERING_API_KEY=your_revenium_api_key
156
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
63
+ # Then edit .env with your actual API keys
157
64
  ```
158
65
 
159
- #### Step 4: Build the project
160
-
161
- ```bash
162
- npm run build
163
- ```
66
+ See [`.env.example`](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/.env.example) for the complete list of environment variables and where to get your API keys.
164
67
 
165
- #### Step 5: Run examples
68
+ **Replace the placeholder values with your actual keys!**
166
69
 
167
- **TypeScript Examples:**
70
+ #### Step 4: Follow the Examples
168
71
 
169
- ```bash
170
- npm run example:basic # Basic chat completion
171
- npm run example:streaming # Streaming response
172
- npm run example:chat # Multi-turn conversation
173
- npm run example:metadata # Custom metadata
174
- ```
72
+ **For complete examples and usage patterns, see [examples/README.md](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/README.md) for complete examples and setup instructions.
175
73
 
176
- **JavaScript Playground:**
74
+ **Cloned from GitHub?** Run examples with:
177
75
 
178
76
  ```bash
179
- npm run playground:basic # Basic chat completion
180
- npm run playground:streaming # Streaming response
181
- npm run playground:chat # Multi-turn conversation
182
- npm run playground:metadata # Custom metadata
183
- ```
184
-
185
- #### Step 6: Use in your own code
186
-
187
- After building, you can import from the local build:
188
-
189
- ```javascript
190
- const {
191
- initializeReveniumFromEnv,
192
- initializePerplexityFromEnv,
193
- createChatCompletion,
194
- } = require("./dist/cjs");
195
-
196
- // Your code here...
197
- ```
198
-
199
- ---
200
-
201
- ### Option 3: Add to Existing Project
202
-
203
- **Best for:** Integrating Perplexity with Revenium into an existing Node.js project.
204
-
205
- #### Step 1: Install the middleware
206
-
207
- ```bash
208
- npm install @revenium/perplexity
209
- ```
210
-
211
- #### Step 2: Add environment variables
212
-
213
- Add to your existing `.env` file:
214
-
215
- ```env
216
- # Perplexity API Configuration
217
- PERPLEXITY_API_KEY=your_perplexity_api_key
218
-
219
- # Revenium Metering Configuration
220
- REVENIUM_METERING_API_KEY=your_revenium_api_key
221
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
222
- ```
223
-
224
- #### Step 3: Initialize in your application
225
-
226
- **For CommonJS projects:**
227
-
228
- ```javascript
229
- require("dotenv").config();
230
- const {
231
- initializeReveniumFromEnv,
232
- initializePerplexityFromEnv,
233
- createChatCompletion,
234
- PERPLEXITY_MODELS,
235
- } = require("@revenium/perplexity");
236
-
237
- // Initialize once at app startup
238
- initializeReveniumFromEnv();
239
- initializePerplexityFromEnv();
240
-
241
- // Use anywhere in your app
242
- async function askPerplexity(question) {
243
- const result = await createChatCompletion({
244
- messages: [{ role: "user", content: question }],
245
- model: PERPLEXITY_MODELS.SONAR_PRO,
246
- });
247
- return result.content;
248
- }
249
- ```
250
-
251
- **For ES Modules projects:**
252
-
253
- ```javascript
254
- import "dotenv/config";
255
- import {
256
- initializeReveniumFromEnv,
257
- initializePerplexityFromEnv,
258
- createChatCompletion,
259
- PERPLEXITY_MODELS,
260
- } from "@revenium/perplexity";
261
-
262
- // Initialize once at app startup
263
- initializeReveniumFromEnv();
264
- initializePerplexityFromEnv();
265
-
266
- // Use anywhere in your app
267
- export async function askPerplexity(question) {
268
- const result = await createChatCompletion({
269
- messages: [{ role: "user", content: question }],
270
- model: PERPLEXITY_MODELS.SONAR_PRO,
271
- });
272
- return result.content;
273
- }
274
- ```
275
-
276
- **For TypeScript projects:**
277
-
278
- ```typescript
279
- import "dotenv/config";
280
- import {
281
- initializeReveniumFromEnv,
282
- initializePerplexityFromEnv,
283
- createChatCompletion,
284
- PERPLEXITY_MODELS,
285
- type ChatCompletionResult,
286
- } from "@revenium/perplexity";
287
-
288
- // Initialize once at app startup
289
- initializeReveniumFromEnv();
290
- initializePerplexityFromEnv();
291
-
292
- // Use anywhere in your app
293
- export async function askPerplexity(question: string): Promise<string> {
294
- const result: ChatCompletionResult = await createChatCompletion({
295
- messages: [{ role: "user", content: question }],
296
- model: PERPLEXITY_MODELS.SONAR_PRO,
297
- });
298
- return result.content;
299
- }
77
+ npm install
78
+ npm run example:getting-started # Start here!
79
+ npm run example:basic
80
+ npm run example:stream
81
+ npm run example:metadata
82
+ npm run example:advanced
300
83
  ```
301
84
 
302
85
  ---
303
86
 
304
- ## Quick Start
305
-
306
- ### 1. Set up environment variables
307
-
308
- Create a `.env` file in your project root:
309
-
310
- ```env
311
- # Perplexity API Configuration
312
- PERPLEXITY_API_KEY=your_perplexity_api_key
313
-
314
- # Revenium Metering Configuration
315
- REVENIUM_METERING_API_KEY=your_revenium_api_key
316
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
317
- ```
318
-
319
- ### 2. Initialize and use
320
-
321
- ```typescript
322
- import {
323
- initializeReveniumFromEnv,
324
- initializePerplexityFromEnv,
325
- createChatCompletion,
326
- PERPLEXITY_MODELS,
327
- } from "@revenium/perplexity";
328
-
329
- // Initialize configurations
330
- initializeReveniumFromEnv();
331
- initializePerplexityFromEnv();
332
-
333
- // Create a chat completion
334
- const result = await createChatCompletion({
335
- messages: [{ role: "user", content: "What is the capital of France?" }],
336
- model: PERPLEXITY_MODELS.SONAR_PRO,
337
- });
338
-
339
- console.log(result.content);
340
- // Output: "The capital of France is Paris."
341
- ```
342
-
343
- ## API Reference
344
-
345
- ### Configuration
346
-
347
- #### `initializeReveniumFromEnv()`
348
-
349
- Initialize Revenium configuration from environment variables.
350
-
351
- ```typescript
352
- const config = initializeReveniumFromEnv();
353
- ```
354
-
355
- #### `initializePerplexityFromEnv()`
356
-
357
- Initialize Perplexity configuration from environment variables.
358
-
359
- ```typescript
360
- const config = initializePerplexityFromEnv();
361
- ```
362
-
363
- #### `initializeRevenium(config)`
364
-
365
- Initialize Revenium with custom configuration.
366
-
367
- ```typescript
368
- initializeRevenium({
369
- meteringApiKey: "your_api_key",
370
- meteringBaseUrl: "https://api.revenium.io/meter",
371
- teamId: "your_team_id", // Optional
372
- });
373
- ```
374
-
375
- #### `initializePerplexity(config)`
376
-
377
- Initialize Perplexity with custom configuration.
378
-
379
- ```typescript
380
- initializePerplexity({
381
- apiKey: "your_perplexity_api_key",
382
- baseUrl: "https://api.perplexity.ai", // Optional
383
- });
384
- ```
385
-
386
- ### Chat Completions
387
-
388
- #### `createChatCompletion(params)`
389
-
390
- Create a chat completion with automatic metering.
391
-
392
- ```typescript
393
- const result = await createChatCompletion({
394
- messages: [
395
- { role: "system", content: "You are a helpful assistant." },
396
- { role: "user", content: "Hello!" },
397
- ],
398
- model: PERPLEXITY_MODELS.SONAR_PRO,
399
- maxTokens: 100,
400
- temperature: 0.7,
401
- usageMetadata: {
402
- // Optional
403
- subscriber: { id: "user-123" },
404
- organizationId: "org-456",
405
- productId: "product-789",
406
- },
407
- });
408
-
409
- console.log(result.content);
410
- console.log(result.usage);
411
- console.log(result.transactionId);
412
- ```
413
-
414
- **Parameters:**
415
-
416
- - `messages` - Array of message objects with `role` and `content`
417
- - `model` - Perplexity model to use (see [Available Models](https://github.com/revenium/revenium-middleware-perplexity-node#available-models))
418
- - `maxTokens` - Maximum tokens to generate (optional)
419
- - `temperature` - Sampling temperature 0-2 (optional)
420
- - `topP` - Nucleus sampling parameter (optional)
421
- - `presencePenalty` - Presence penalty -2 to 2 (optional)
422
- - `frequencyPenalty` - Frequency penalty -2 to 2 (optional)
423
- - `usageMetadata` - Custom metadata for tracking (optional)
424
-
425
- **Returns:**
426
-
427
- ```typescript
428
- {
429
- content: string;
430
- role: string;
431
- finishReason: string | null;
432
- usage: {
433
- promptTokens: number;
434
- completionTokens: number;
435
- totalTokens: number;
436
- }
437
- model: string;
438
- transactionId: string;
439
- rawResponse: PerplexityResponse;
440
- }
441
- ```
87
+ ## What Gets Tracked
442
88
 
443
- #### `createStreamingChatCompletion(params)`
89
+ The middleware automatically captures comprehensive usage data:
444
90
 
445
- Create a streaming chat completion.
91
+ ### **Usage Metrics**
446
92
 
447
- ```typescript
448
- const result = await createStreamingChatCompletion({
449
- messages: [{ role: "user", content: "Count from 1 to 5" }],
450
- model: PERPLEXITY_MODELS.SONAR_PRO,
451
- });
93
+ - **Token Counts** - Input tokens, output tokens, total tokens
94
+ - **Model Information** - Model name, provider (Perplexity)
95
+ - **Request Timing** - Request duration, response time
96
+ - **Cost Calculation** - Estimated costs based on current pricing
452
97
 
453
- for await (const chunk of result.stream) {
454
- const content = chunk.choices[0]?.delta?.content || "";
455
- process.stdout.write(content);
456
- }
457
- ```
98
+ ### **Business Context (Optional)**
458
99
 
459
- **Returns:**
100
+ - **User Tracking** - Subscriber ID, email, credentials
101
+ - **Organization Data** - Organization ID, subscription ID, product ID
102
+ - **Task Classification** - Task type, agent identifier, trace ID
103
+ - **Quality Metrics** - Response quality scores, task identifiers
460
104
 
461
- ```typescript
462
- {
463
- stream: AsyncGenerator<PerplexityStreamChunk>;
464
- transactionId: string;
465
- model: string;
466
- }
467
- ```
105
+ ### **Technical Details**
468
106
 
469
- ### Available Models
107
+ - **API Endpoints** - Chat completions
108
+ - **Request Types** - Streaming vs non-streaming
109
+ - **Error Tracking** - Failed requests, error types, retry attempts
110
+ - **Environment Info** - Development vs production usage
470
111
 
471
- ```typescript
472
- import { PERPLEXITY_MODELS } from "@revenium/perplexity";
112
+ ## API Overview
473
113
 
474
- // Online Models (with internet access)
475
- PERPLEXITY_MODELS.SONAR; // "sonar"
476
- PERPLEXITY_MODELS.SONAR_PRO; // "sonar-pro"
477
- PERPLEXITY_MODELS.SONAR_REASONING; // "sonar-reasoning"
114
+ The middleware provides a Go-aligned API with the following main functions:
478
115
 
479
- // Chat Models (offline)
480
- PERPLEXITY_MODELS.LLAMA_3_1_SONAR_SMALL_128K_CHAT; // "llama-3.1-sonar-small-128k-chat"
481
- PERPLEXITY_MODELS.LLAMA_3_1_SONAR_LARGE_128K_CHAT; // "llama-3.1-sonar-large-128k-chat"
482
- PERPLEXITY_MODELS.LLAMA_3_1_SONAR_HUGE_128K_CHAT; // "llama-3.1-sonar-huge-128k-chat"
483
- ```
116
+ - **`Initialize(config?)`** - Initialize the middleware (from environment or explicit config)
117
+ - **`GetClient()`** - Get the global Revenium client instance
118
+ - **`Configure(config)`** - Alias for `Initialize()` for programmatic configuration
119
+ - **`IsInitialized()`** - Check if the middleware is initialized
120
+ - **`Reset()`** - Reset the global client (useful for testing)
484
121
 
485
- ### Utility Functions
122
+ **For complete API documentation and usage examples, see [`examples/README.md`](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/README.md).**
486
123
 
487
- #### `disableRevenium()` / `enableRevenium()`
124
+ ## Metadata Fields
488
125
 
489
- Temporarily disable or enable Revenium metering.
126
+ The middleware supports the following optional metadata fields for tracking:
490
127
 
491
- ```typescript
492
- import { disableRevenium, enableRevenium } from "@revenium/perplexity";
128
+ | Field | Type | Description |
129
+ | ----------------------- | ------ | ---------------------------------------------------------- |
130
+ | `traceId` | string | Unique identifier for session or conversation tracking |
131
+ | `taskType` | string | Type of AI task being performed (e.g., "chat", "research") |
132
+ | `agent` | string | AI agent or bot identifier |
133
+ | `organizationId` | string | Organization or company identifier |
134
+ | `productId` | string | Your product or feature identifier |
135
+ | `subscriptionId` | string | Subscription plan identifier |
136
+ | `responseQualityScore` | number | Custom quality rating (0.0-1.0) |
137
+ | `subscriber.id` | string | Unique user identifier |
138
+ | `subscriber.email` | string | User email address |
139
+ | `subscriber.credential` | object | Authentication credential (`name` and `value` fields) |
493
140
 
494
- disableRevenium(); // Stop sending metering data
495
- // ... make API calls ...
496
- enableRevenium(); // Resume sending metering data
497
- ```
141
+ **All metadata fields are optional.** For complete metadata documentation and usage examples, see:
498
142
 
499
- #### `generateTransactionId()`
143
+ - [`examples/README.md`](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/README.md) - All usage examples
144
+ - [Revenium API Reference](https://revenium.readme.io/reference/meter_ai_completion) - Complete API documentation
500
145
 
501
- Generate a unique transaction ID.
146
+ ## Configuration Options
502
147
 
503
- ```typescript
504
- import { generateTransactionId } from "@revenium/perplexity";
148
+ ### Environment Variables
505
149
 
506
- const txnId = generateTransactionId();
507
- ```
150
+ For a complete list of all available environment variables with examples, see [`.env.example`](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/.env.example).
508
151
 
509
152
  ## Examples
510
153
 
511
- ### Basic Chat Completion
154
+ The package includes comprehensive examples in the [`examples/`](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/) directory.
512
155
 
513
- ```typescript
514
- import {
515
- initializeReveniumFromEnv,
516
- initializePerplexityFromEnv,
517
- createChatCompletion,
518
- PERPLEXITY_MODELS,
519
- } from "@revenium/perplexity";
520
156
 
521
- initializeReveniumFromEnv();
522
- initializePerplexityFromEnv();
523
-
524
- const result = await createChatCompletion({
525
- messages: [{ role: "user", content: "What is the capital of France?" }],
526
- model: PERPLEXITY_MODELS.SONAR_PRO,
527
- });
528
-
529
- console.log(result.content);
530
- ```
531
-
532
- ### Streaming Response
533
-
534
- ```typescript
535
- const result = await createStreamingChatCompletion({
536
- messages: [{ role: "user", content: "Write a short poem about AI" }],
537
- model: PERPLEXITY_MODELS.SONAR_PRO,
538
- });
539
-
540
- for await (const chunk of result.stream) {
541
- const content = chunk.choices[0]?.delta?.content || "";
542
- process.stdout.write(content);
543
- }
544
- ```
545
-
546
- ### Multi-turn Conversation
547
-
548
- ```typescript
549
- const messages = [
550
- { role: "system", content: "You are a helpful assistant." },
551
- { role: "user", content: "What is the capital of France?" },
552
- ];
553
-
554
- const response1 = await createChatCompletion({
555
- messages,
556
- model: PERPLEXITY_MODELS.SONAR_PRO,
557
- });
558
-
559
- messages.push({ role: "assistant", content: response1.content });
560
- messages.push({ role: "user", content: "What is its population?" });
561
-
562
- const response2 = await createChatCompletion({
563
- messages,
564
- model: PERPLEXITY_MODELS.SONAR_PRO,
565
- });
566
- ```
157
+ ## Project Structure
567
158
 
568
- ### Custom Metadata
569
-
570
- ```typescript
571
- const result = await createChatCompletion({
572
- messages: [{ role: "user", content: "Hello!" }],
573
- model: PERPLEXITY_MODELS.SONAR_PRO,
574
- usageMetadata: {
575
- subscriber: {
576
- id: "user-123",
577
- email: "user@example.com",
578
- },
579
- organizationId: "org-456",
580
- productId: "premium-plan",
581
- traceId: "trace-abc-123",
582
- },
583
- });
584
159
  ```
585
-
586
- ## What Gets Tracked
587
-
588
- The middleware automatically captures:
589
-
590
- - **Token Usage**: Prompt and completion tokens for accurate billing
591
- - **Request Duration**: Total time for each API call
592
- - **Model Information**: Which Perplexity model was used
593
- - **Operation Type**: Chat completion, streaming, etc.
594
- - **Error Tracking**: Failed requests and error details
595
- - **Streaming Metrics**: Time to first token for streaming responses
596
- - **Custom Metadata**: Business context you provide
597
-
598
- ## Advanced Usage
599
-
600
- ### Streaming Responses
601
-
602
- ```typescript
603
- import {
604
- initializeReveniumFromEnv,
605
- initializePerplexityFromEnv,
606
- createStreamingChatCompletion,
607
- PERPLEXITY_MODELS,
608
- } from "@revenium/perplexity";
609
-
610
- initializeReveniumFromEnv();
611
- initializePerplexityFromEnv();
612
-
613
- const result = await createStreamingChatCompletion({
614
- messages: [{ role: "user", content: "Count from 1 to 5" }],
615
- model: PERPLEXITY_MODELS.SONAR_PRO,
616
- usageMetadata: {
617
- subscriber: { id: "user-123" },
618
- taskType: "counting-demo",
619
- },
620
- });
621
-
622
- for await (const chunk of result.stream) {
623
- const content = chunk.choices[0]?.delta?.content || "";
624
- process.stdout.write(content);
625
- }
160
+ revenium-middleware-perplexity-node/
161
+ ├── src/
162
+ │ ├── core/
163
+ │ │ ├── config/ # Configuration management
164
+ │ │ ├── tracking/ # Metering and tracking
165
+ │ │ └── wrapper/ # Perplexity API wrapper
166
+ │ ├── types/ # TypeScript type definitions
167
+ │ ├── utils/ # Utility functions
168
+ │ └── index.ts # Main entry point
169
+ ├── examples/ # TypeScript examples
170
+ ├── .env.example # Example environment variables
171
+ ├── package.json
172
+ ├── tsconfig.json
173
+ └── README.md
626
174
  ```
627
175
 
628
- ### Custom Metadata Tracking
629
-
630
- Add business context to your AI usage:
631
-
632
- ```typescript
633
- const customMetadata = {
634
- subscriber: {
635
- id: "user-789",
636
- email: "user@company.com",
637
- credential: {
638
- name: "premium-user",
639
- value: "tier-1",
640
- },
641
- },
642
- organizationId: "org-456",
643
- productId: "premium-plan",
644
- taskType: "RESEARCH",
645
- agent: "ResearchBot",
646
- traceId: "session-123",
647
- responseQualityScore: 9.2,
648
- };
649
-
650
- const result = await createChatCompletion({
651
- messages: [{ role: "user", content: "Research AI trends" }],
652
- model: PERPLEXITY_MODELS.SONAR_PRO,
653
- usageMetadata: customMetadata,
654
- });
655
- ```
176
+ ## How It Works
656
177
 
657
- ### Usage Metadata Interface
658
-
659
- All metadata fields are optional:
660
-
661
- ```typescript
662
- interface UsageMetadata {
663
- traceId?: string; // Session or conversation ID
664
- taskType?: string; // Type of AI task
665
- organizationId?: string; // Organization/company ID
666
- subscriptionId?: string; // Billing plan ID
667
- productId?: string; // Your product/feature ID
668
- agent?: string; // AI agent identifier
669
- responseQualityScore?: number; // Quality score (0-1)
670
- subscriber?: {
671
- id?: string; // User ID from your system
672
- email?: string; // User's email address
673
- credential?: {
674
- name?: string; // Credential name
675
- value?: string; // Credential value
676
- };
677
- };
678
- }
679
- ```
178
+ 1. **Initialize**: Call `Initialize()` to set up the middleware with your configuration
179
+ 2. **Get Client**: Call `GetClient()` to get a wrapped Perplexity client instance
180
+ 3. **Make Requests**: Use the client normally - all requests are automatically tracked
181
+ 4. **Async Tracking**: Usage data is sent to Revenium in the background (fire-and-forget)
182
+ 5. **Transparent Response**: Original Perplexity responses are returned unchanged
680
183
 
681
- ## Configuration Options
184
+ The middleware never blocks your application - if Revenium tracking fails, your Perplexity requests continue normally.
682
185
 
683
- ### Environment Variables
186
+ **Supported APIs:**
684
187
 
685
- | Variable | Required | Default | Description |
686
- | ---------------------------- | -------- | ------------------------------- | --------------------------------- |
687
- | `PERPLEXITY_API_KEY` | Yes | - | Your Perplexity API key |
688
- | `REVENIUM_METERING_API_KEY` | Yes | - | Your Revenium API key |
689
- | `REVENIUM_METERING_BASE_URL` | Yes | - | Revenium metering API base URL |
690
- | `PERPLEXITY_API_BASE_URL` | No | `https://api.perplexity.ai` | Perplexity API base URL |
691
- | `DEBUG` | No | `false` | Enable debug logging |
692
-
693
- ### Manual Configuration
694
-
695
- ```typescript
696
- import {
697
- initializeRevenium,
698
- initializePerplexity,
699
- createChatCompletion,
700
- } from "@revenium/perplexity";
701
-
702
- // Manual configuration
703
- initializeRevenium({
704
- meteringApiKey: "hak_your_revenium_key",
705
- meteringBaseUrl: "https://api.revenium.io/meter/v2",
706
- });
707
-
708
- initializePerplexity({
709
- apiKey: "pplx_your_perplexity_key",
710
- baseUrl: "https://api.perplexity.ai",
711
- });
712
- ```
188
+ - Chat Completions API (`client.chat().completions().create()`)
189
+ - Streaming API (`client.chat().completions().createStreaming()`)
713
190
 
714
191
  ## Troubleshooting
715
192
 
716
193
  ### Common Issues
717
194
 
718
- #### "Missing API Key" Error
719
-
720
- ```bash
721
- # Make sure you've set the API keys
722
- export PERPLEXITY_API_KEY="pplx_your_actual_api_key"
723
- export REVENIUM_METERING_API_KEY="hak_your_actual_revenium_key"
724
-
725
- # Verify they're set
726
- echo $PERPLEXITY_API_KEY
727
- echo $REVENIUM_METERING_API_KEY
728
- ```
729
-
730
- #### "Requests not being tracked"
731
-
732
- ```bash
733
- # Verify Revenium configuration
734
- export REVENIUM_METERING_API_KEY="hak_your_actual_revenium_key"
735
- export REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter/v2"
736
-
737
- # Enable debug logging to see what's happening
738
- export DEBUG="true"
739
- ```
195
+ **No tracking data appears:**
740
196
 
741
- #### TypeScript errors with usageMetadata
197
+ 1. Verify environment variables are set correctly in `.env`
198
+ 2. Enable debug logging by setting `REVENIUM_DEBUG=true` in `.env`
199
+ 3. Check console for `[Revenium]` log messages
200
+ 4. Verify your `REVENIUM_METERING_API_KEY` is valid
742
201
 
743
- - Ensure you're importing from `@revenium/perplexity`
744
- - Check that your TypeScript version is 5.0+
745
- - Verify you're using the latest version: `npm update @revenium/perplexity`
202
+ **Client not initialized error:**
746
203
 
747
- #### Build/Import Errors
204
+ - Make sure you call `Initialize()` before `GetClient()`
205
+ - Check that your `.env` file is in the project root
206
+ - Verify `REVENIUM_METERING_API_KEY` is set
748
207
 
749
- ```bash
750
- # Clean and reinstall
751
- rm -rf node_modules
752
- npm install
208
+ **Perplexity API errors:**
753
209
 
754
- # For TypeScript projects
755
- npm run build
756
- ```
210
+ - Verify `PERPLEXITY_API_KEY` is set correctly
211
+ - Check that your API key starts with `pplx-`
212
+ - Ensure you're using a valid model name
757
213
 
758
214
  ### Debug Mode
759
215
 
760
- Enable debug logging to troubleshoot issues:
216
+ Enable detailed logging by adding to your `.env`:
761
217
 
762
- ```bash
763
- export DEBUG="true"
764
- node your-script.js
218
+ ```env
219
+ REVENIUM_DEBUG=true
765
220
  ```
766
221
 
767
- This will show:
222
+ ### Getting Help
768
223
 
769
- - Initialization details
770
- - Configuration loading
771
- - API call information
772
- - Error details
224
+ If issues persist:
773
225
 
774
- ## Project Structure
226
+ 1. Enable debug logging (`REVENIUM_DEBUG=true`)
227
+ 2. Check the [`examples/`](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/) directory for working examples
228
+ 3. Review [`examples/README.md`](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/README.md) for detailed setup instructions
229
+ 4. Contact support@revenium.io with debug logs
775
230
 
776
- ```
777
- revenium-middleware-perplexity-node/
778
- ├── src/
779
- │ ├── core/
780
- │ │ ├── config/ # Configuration management
781
- │ │ ├── tracking/ # Metering and tracking
782
- │ │ └── wrapper/ # Perplexity API wrapper
783
- │ ├── types/ # TypeScript type definitions
784
- │ ├── utils/ # Utility functions
785
- │ └── index.ts # Main entry point
786
- ├── examples/ # TypeScript examples
787
- ├── playground/ # JavaScript examples
788
- └── dist/
789
- ├── cjs/ # CommonJS build
790
- ├── esm/ # ES Modules build
791
- └── types/ # TypeScript definitions
792
- ```
231
+ ## Supported Models
793
232
 
794
- ## Running Examples
233
+ This middleware works with any Perplexity model. For the complete model list, see the [Perplexity Models Documentation](https://docs.perplexity.ai/getting-started/models).
795
234
 
796
- ### TypeScript Examples
235
+ ### API Support Matrix
797
236
 
798
- ```bash
799
- npm run example:basic # Basic chat completion
800
- npm run example:streaming # Streaming response
801
- npm run example:chat # Multi-turn conversation
802
- npm run example:metadata # Custom metadata
803
- ```
237
+ The following table shows what has been tested and verified with working examples:
804
238
 
805
- ### JavaScript Playground
239
+ | Feature | Chat Completions | Streaming |
240
+ | --------------------- | ---------------- | --------- |
241
+ | **Basic Usage** | Yes | Yes |
242
+ | **Metadata Tracking** | Yes | Yes |
243
+ | **Token Counting** | Yes | Yes |
806
244
 
807
- ```bash
808
- npm run playground:basic # Basic chat completion
809
- npm run playground:streaming # Streaming response
810
- npm run playground:chat # Multi-turn conversation
811
- npm run playground:metadata # Custom metadata
812
- ```
245
+ **Note:** "Yes" = Tested with working examples in [`examples/`](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/) directory
813
246
 
814
- ## How It Works
815
-
816
- 1. **Initialization**: When you call `initializePerplexityFromEnv()` and `initializeReveniumFromEnv()`, the middleware sets up configurations
817
- 2. **Request Wrapping**: All Perplexity API calls go through the middleware wrapper
818
- 3. **Usage Extraction**: Token counts, model info, and timing data are captured from responses
819
- 4. **Async Tracking**: Usage data is sent to Revenium in the background (fire-and-forget)
820
- 5. **Transparent Response**: Original Perplexity responses are returned unchanged
821
-
822
- The middleware never blocks your application - if Revenium tracking fails, your Perplexity requests continue normally.
823
247
 
824
248
  ## Requirements
825
249
 
826
- - Node.js 16+
250
+ - Node.js 20+
827
251
  - TypeScript 5.0+ (for TypeScript projects)
828
252
  - Revenium API key
829
253
  - Perplexity API key