@revenium/perplexity 1.0.10 → 1.0.11

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 (255) hide show
  1. package/.env.example +2 -2
  2. package/README.md +603 -566
  3. package/examples/basic.ts +17 -0
  4. package/examples/chat-completions.ts +23 -0
  5. package/examples/enhanced.ts +21 -0
  6. package/examples/streaming.ts +25 -0
  7. package/package.json +45 -61
  8. package/playground/basic.js +7 -16
  9. package/playground/enhanced.js +9 -21
  10. package/playground/streaming.js +10 -25
  11. package/src/index.ts +1 -35
  12. package/src/interfaces/chatCompletionRequest.ts +9 -0
  13. package/src/interfaces/credential.ts +4 -0
  14. package/src/interfaces/meteringRequest.ts +14 -0
  15. package/src/{types/metering.ts → interfaces/meteringResponse.ts} +3 -3
  16. package/src/interfaces/operation.ts +4 -0
  17. package/src/{types → interfaces}/subscriber.ts +1 -1
  18. package/src/interfaces/tokenCounts.ts +7 -0
  19. package/src/{types → interfaces}/usageMetadata.ts +1 -1
  20. package/src/middleware.ts +151 -0
  21. package/src/models/Logger.ts +5 -5
  22. package/src/models/Metering.ts +86 -0
  23. package/src/utils/calculateDurationMs.ts +1 -1
  24. package/src/utils/constants/constants.ts +9 -16
  25. package/src/utils/constants/logLevels.ts +1 -0
  26. package/src/utils/constants/messages.ts +8 -32
  27. package/src/utils/constants/models.ts +20 -0
  28. package/src/utils/extractTokenCount.ts +26 -0
  29. package/src/utils/generateTransactionId.ts +1 -1
  30. package/src/utils/index.ts +39 -12
  31. package/src/utils/loadEnv.ts +8 -0
  32. package/src/utils/safeExtract.ts +60 -11
  33. package/tsconfig.json +10 -18
  34. package/dist/index.d.ts +0 -8
  35. package/dist/index.d.ts.map +0 -1
  36. package/dist/index.js +0 -40
  37. package/dist/index.js.map +0 -1
  38. package/dist/models/Exception/ApiResponseError.d.ts +0 -6
  39. package/dist/models/Exception/ApiResponseError.d.ts.map +0 -1
  40. package/dist/models/Exception/ApiResponseError.js +0 -13
  41. package/dist/models/Exception/ApiResponseError.js.map +0 -1
  42. package/dist/models/Exception/ConfigurationError.d.ts +0 -4
  43. package/dist/models/Exception/ConfigurationError.d.ts.map +0 -1
  44. package/dist/models/Exception/ConfigurationError.js +0 -11
  45. package/dist/models/Exception/ConfigurationError.js.map +0 -1
  46. package/dist/models/Exception/MeteringError.d.ts +0 -5
  47. package/dist/models/Exception/MeteringError.d.ts.map +0 -1
  48. package/dist/models/Exception/MeteringError.js +0 -12
  49. package/dist/models/Exception/MeteringError.js.map +0 -1
  50. package/dist/models/Exception/MiddlewareActivationError.d.ts +0 -4
  51. package/dist/models/Exception/MiddlewareActivationError.d.ts.map +0 -1
  52. package/dist/models/Exception/MiddlewareActivationError.js +0 -11
  53. package/dist/models/Exception/MiddlewareActivationError.js.map +0 -1
  54. package/dist/models/Exception/StreamTrackingError.d.ts +0 -4
  55. package/dist/models/Exception/StreamTrackingError.d.ts.map +0 -1
  56. package/dist/models/Exception/StreamTrackingError.js +0 -11
  57. package/dist/models/Exception/StreamTrackingError.js.map +0 -1
  58. package/dist/models/Exception/TokenCountingError.d.ts +0 -4
  59. package/dist/models/Exception/TokenCountingError.d.ts.map +0 -1
  60. package/dist/models/Exception/TokenCountingError.js +0 -11
  61. package/dist/models/Exception/TokenCountingError.js.map +0 -1
  62. package/dist/models/Exception/index.d.ts +0 -7
  63. package/dist/models/Exception/index.d.ts.map +0 -1
  64. package/dist/models/Exception/index.js +0 -23
  65. package/dist/models/Exception/index.js.map +0 -1
  66. package/dist/models/Logger.d.ts +0 -10
  67. package/dist/models/Logger.d.ts.map +0 -1
  68. package/dist/models/Logger.js +0 -36
  69. package/dist/models/Logger.js.map +0 -1
  70. package/dist/models/index.d.ts +0 -3
  71. package/dist/models/index.d.ts.map +0 -1
  72. package/dist/models/index.js +0 -19
  73. package/dist/models/index.js.map +0 -1
  74. package/dist/perplexity-ai/client.d.ts +0 -31
  75. package/dist/perplexity-ai/client.d.ts.map +0 -1
  76. package/dist/perplexity-ai/client.js +0 -75
  77. package/dist/perplexity-ai/client.js.map +0 -1
  78. package/dist/perplexity-ai/index.d.ts +0 -3
  79. package/dist/perplexity-ai/index.d.ts.map +0 -1
  80. package/dist/perplexity-ai/index.js +0 -19
  81. package/dist/perplexity-ai/index.js.map +0 -1
  82. package/dist/perplexity-ai/middleware.d.ts +0 -2
  83. package/dist/perplexity-ai/middleware.d.ts.map +0 -1
  84. package/dist/perplexity-ai/middleware.js +0 -195
  85. package/dist/perplexity-ai/middleware.js.map +0 -1
  86. package/dist/types/context.d.ts +0 -9
  87. package/dist/types/context.d.ts.map +0 -1
  88. package/dist/types/context.js +0 -3
  89. package/dist/types/context.js.map +0 -1
  90. package/dist/types/index.d.ts +0 -12
  91. package/dist/types/index.d.ts.map +0 -1
  92. package/dist/types/index.js +0 -28
  93. package/dist/types/index.js.map +0 -1
  94. package/dist/types/metering.d.ts +0 -28
  95. package/dist/types/metering.d.ts.map +0 -1
  96. package/dist/types/metering.js +0 -3
  97. package/dist/types/metering.js.map +0 -1
  98. package/dist/types/modelInfo.d.ts +0 -6
  99. package/dist/types/modelInfo.d.ts.map +0 -1
  100. package/dist/types/modelInfo.js +0 -3
  101. package/dist/types/modelInfo.js.map +0 -1
  102. package/dist/types/operation.d.ts +0 -5
  103. package/dist/types/operation.d.ts.map +0 -1
  104. package/dist/types/operation.js +0 -9
  105. package/dist/types/operation.js.map +0 -1
  106. package/dist/types/perplexityConfig.d.ts +0 -5
  107. package/dist/types/perplexityConfig.d.ts.map +0 -1
  108. package/dist/types/perplexityConfig.js +0 -3
  109. package/dist/types/perplexityConfig.js.map +0 -1
  110. package/dist/types/provider.d.ts +0 -4
  111. package/dist/types/provider.d.ts.map +0 -1
  112. package/dist/types/provider.js +0 -8
  113. package/dist/types/provider.js.map +0 -1
  114. package/dist/types/reveniumConfig.d.ts +0 -6
  115. package/dist/types/reveniumConfig.d.ts.map +0 -1
  116. package/dist/types/reveniumConfig.js +0 -3
  117. package/dist/types/reveniumConfig.js.map +0 -1
  118. package/dist/types/streamTracker.d.ts +0 -9
  119. package/dist/types/streamTracker.d.ts.map +0 -1
  120. package/dist/types/streamTracker.js +0 -3
  121. package/dist/types/streamTracker.js.map +0 -1
  122. package/dist/types/subscriber.d.ts +0 -9
  123. package/dist/types/subscriber.d.ts.map +0 -1
  124. package/dist/types/subscriber.js +0 -3
  125. package/dist/types/subscriber.js.map +0 -1
  126. package/dist/types/tokenCounts.d.ts +0 -6
  127. package/dist/types/tokenCounts.d.ts.map +0 -1
  128. package/dist/types/tokenCounts.js +0 -3
  129. package/dist/types/tokenCounts.js.map +0 -1
  130. package/dist/types/usageData.d.ts +0 -16
  131. package/dist/types/usageData.d.ts.map +0 -1
  132. package/dist/types/usageData.js +0 -3
  133. package/dist/types/usageData.js.map +0 -1
  134. package/dist/types/usageMetadata.d.ts +0 -14
  135. package/dist/types/usageMetadata.d.ts.map +0 -1
  136. package/dist/types/usageMetadata.js +0 -3
  137. package/dist/types/usageMetadata.js.map +0 -1
  138. package/dist/utils/activeMiddleware.d.ts +0 -2
  139. package/dist/utils/activeMiddleware.d.ts.map +0 -1
  140. package/dist/utils/activeMiddleware.js +0 -24
  141. package/dist/utils/activeMiddleware.js.map +0 -1
  142. package/dist/utils/askConsole.d.ts +0 -2
  143. package/dist/utils/askConsole.d.ts.map +0 -1
  144. package/dist/utils/askConsole.js +0 -20
  145. package/dist/utils/askConsole.js.map +0 -1
  146. package/dist/utils/calculateDurationMs.d.ts +0 -2
  147. package/dist/utils/calculateDurationMs.d.ts.map +0 -1
  148. package/dist/utils/calculateDurationMs.js +0 -7
  149. package/dist/utils/calculateDurationMs.js.map +0 -1
  150. package/dist/utils/constants/constants.d.ts +0 -9
  151. package/dist/utils/constants/constants.d.ts.map +0 -1
  152. package/dist/utils/constants/constants.js +0 -19
  153. package/dist/utils/constants/constants.js.map +0 -1
  154. package/dist/utils/constants/messages.d.ts +0 -19
  155. package/dist/utils/constants/messages.d.ts.map +0 -1
  156. package/dist/utils/constants/messages.js +0 -22
  157. package/dist/utils/constants/messages.js.map +0 -1
  158. package/dist/utils/createMeteringRequest.d.ts +0 -3
  159. package/dist/utils/createMeteringRequest.d.ts.map +0 -1
  160. package/dist/utils/createMeteringRequest.js +0 -10
  161. package/dist/utils/createMeteringRequest.js.map +0 -1
  162. package/dist/utils/createPerplexityMetadata.d.ts +0 -3
  163. package/dist/utils/createPerplexityMetadata.d.ts.map +0 -1
  164. package/dist/utils/createPerplexityMetadata.js +0 -12
  165. package/dist/utils/createPerplexityMetadata.js.map +0 -1
  166. package/dist/utils/extractModelName.d.ts +0 -2
  167. package/dist/utils/extractModelName.d.ts.map +0 -1
  168. package/dist/utils/extractModelName.js +0 -15
  169. package/dist/utils/extractModelName.js.map +0 -1
  170. package/dist/utils/extractPerplexityTokenCounts.d.ts +0 -3
  171. package/dist/utils/extractPerplexityTokenCounts.d.ts.map +0 -1
  172. package/dist/utils/extractPerplexityTokenCounts.js +0 -17
  173. package/dist/utils/extractPerplexityTokenCounts.js.map +0 -1
  174. package/dist/utils/extractStopReason.d.ts +0 -2
  175. package/dist/utils/extractStopReason.d.ts.map +0 -1
  176. package/dist/utils/extractStopReason.js +0 -14
  177. package/dist/utils/extractStopReason.js.map +0 -1
  178. package/dist/utils/extractUsageMetadata.d.ts +0 -3
  179. package/dist/utils/extractUsageMetadata.d.ts.map +0 -1
  180. package/dist/utils/extractUsageMetadata.js +0 -15
  181. package/dist/utils/extractUsageMetadata.js.map +0 -1
  182. package/dist/utils/formatTimestamp.d.ts +0 -2
  183. package/dist/utils/formatTimestamp.d.ts.map +0 -1
  184. package/dist/utils/formatTimestamp.js +0 -7
  185. package/dist/utils/formatTimestamp.js.map +0 -1
  186. package/dist/utils/generateTransactionId.d.ts +0 -2
  187. package/dist/utils/generateTransactionId.d.ts.map +0 -1
  188. package/dist/utils/generateTransactionId.js +0 -8
  189. package/dist/utils/generateTransactionId.js.map +0 -1
  190. package/dist/utils/getEnv.d.ts +0 -4
  191. package/dist/utils/getEnv.d.ts.map +0 -1
  192. package/dist/utils/getEnv.js +0 -16
  193. package/dist/utils/getEnv.js.map +0 -1
  194. package/dist/utils/index.d.ts +0 -13
  195. package/dist/utils/index.d.ts.map +0 -1
  196. package/dist/utils/index.js +0 -29
  197. package/dist/utils/index.js.map +0 -1
  198. package/dist/utils/safeExtract.d.ts +0 -2
  199. package/dist/utils/safeExtract.d.ts.map +0 -1
  200. package/dist/utils/safeExtract.js +0 -22
  201. package/dist/utils/safeExtract.js.map +0 -1
  202. package/dist/utils/sendMeteringData.d.ts +0 -3
  203. package/dist/utils/sendMeteringData.d.ts.map +0 -1
  204. package/dist/utils/sendMeteringData.js +0 -35
  205. package/dist/utils/sendMeteringData.js.map +0 -1
  206. package/dist/utils/verifyLogVerbose.d.ts +0 -2
  207. package/dist/utils/verifyLogVerbose.d.ts.map +0 -1
  208. package/dist/utils/verifyLogVerbose.js +0 -10
  209. package/dist/utils/verifyLogVerbose.js.map +0 -1
  210. package/examples/basic-client-example.ts +0 -36
  211. package/examples/metadata-example.ts +0 -97
  212. package/examples/multiple-models-example.ts +0 -65
  213. package/examples/openai-client-example.ts +0 -76
  214. package/examples/perplexity_basic_example.ts +0 -24
  215. package/examples/perplexity_middleware_example.ts +0 -222
  216. package/examples/run-all-examples.ts +0 -118
  217. package/examples/simple-test.ts +0 -278
  218. package/examples/streaming-example.ts +0 -46
  219. package/playground/custom-config.js +0 -82
  220. package/playground/metadata.js +0 -94
  221. package/playground/multiple-models.js +0 -62
  222. package/playground/openai-client.js +0 -73
  223. package/src/models/Exception/ApiResponseError.ts +0 -6
  224. package/src/models/Exception/ConfigurationError.ts +0 -6
  225. package/src/models/Exception/MeteringError.ts +0 -6
  226. package/src/models/Exception/MiddlewareActivationError.ts +0 -6
  227. package/src/models/Exception/StreamTrackingError.ts +0 -6
  228. package/src/models/Exception/TokenCountingError.ts +0 -6
  229. package/src/models/Exception/index.ts +0 -6
  230. package/src/models/index.ts +0 -2
  231. package/src/perplexity-ai/client.ts +0 -100
  232. package/src/perplexity-ai/index.ts +0 -2
  233. package/src/perplexity-ai/middleware.ts +0 -297
  234. package/src/types/context.ts +0 -9
  235. package/src/types/index.ts +0 -11
  236. package/src/types/modelInfo.ts +0 -5
  237. package/src/types/operation.ts +0 -4
  238. package/src/types/perplexityConfig.ts +0 -4
  239. package/src/types/provider.ts +0 -3
  240. package/src/types/reveniumConfig.ts +0 -5
  241. package/src/types/streamTracker.ts +0 -9
  242. package/src/types/tokenCounts.ts +0 -5
  243. package/src/types/usageData.ts +0 -16
  244. package/src/utils/activeMiddleware.ts +0 -34
  245. package/src/utils/askConsole.ts +0 -15
  246. package/src/utils/createMeteringRequest.ts +0 -16
  247. package/src/utils/createPerplexityMetadata.ts +0 -11
  248. package/src/utils/extractModelName.ts +0 -14
  249. package/src/utils/extractPerplexityTokenCounts.ts +0 -16
  250. package/src/utils/extractStopReason.ts +0 -13
  251. package/src/utils/extractUsageMetadata.ts +0 -15
  252. package/src/utils/getEnv.ts +0 -16
  253. package/src/utils/sendMeteringData.ts +0 -46
  254. package/src/utils/verifyLogVerbose.ts +0 -7
  255. /package/src/utils/{formatTimestamp.ts → formatTimeStamp.ts} +0 -0
package/README.md CHANGED
@@ -1,566 +1,603 @@
1
- # Revenium Middleware for Perplexity AI (Node.js)
2
-
3
- [![npm version](https://img.shields.io/npm/v/@revenium/perplexity.svg)](https://www.npmjs.com/package/@revenium/perplexity)
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-revenium.io-blue)](https://docs.revenium.io)
6
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
-
8
- Automatically track and meter your Perplexity AI API usage with Revenium. This middleware provides seamless integration with Perplexity AI SDK, requiring minimal code changes.
9
-
10
- ## 🚀 Getting Started
11
-
12
- You have **3 options** to start using Revenium middleware for Perplexity AI:
13
-
14
- ### Option 1: Create Project from Scratch
15
-
16
- Perfect for new projects. We'll guide you step-by-step from `mkdir` to running tests.
17
- [👉 Go to Step-by-Step Guide](#option-1-create-project-from-scratch)
18
-
19
- ### Option 2: Clone Our Repository
20
-
21
- Quick testing with pre-built examples and playground scripts.
22
- [👉 Go to Clone Guide](#option-2-clone-repository)
23
-
24
- ### Option 3: Add to Existing Project
25
-
26
- Already have a project? Just install and replace imports.
27
- [👉 Go to Quick Integration](#option-3-existing-project-integration)
28
-
29
- ---
30
-
31
- ## Option 1: Create Project from Scratch
32
-
33
- ### Step 1: Create Project Directory
34
-
35
- ```bash
36
- # Create and navigate to your project
37
- mkdir my-perplexity-ai-project
38
- cd my-perplexity-ai-project
39
-
40
- # Initialize Node.js project
41
- npm init -y
42
- ```
43
-
44
- ### Step 2: Install Dependencies
45
-
46
- ```bash
47
- npm install @revenium/perplexity
48
- ```
49
-
50
- ### Step 3: Setup Environment Variables
51
-
52
- Create a `.env` file in your project root:
53
-
54
- ```bash
55
- # Create .env file
56
- echo. > .env # On Windows (CMD TERMINAL)
57
- touch .env # On Mac/Linux (CMD TERMINAL)
58
- # OR
59
- #PowerShell
60
- New-Item -Path .env -ItemType File
61
- ```
62
-
63
- Copy and paste the following into `.env`:
64
-
65
- ```env
66
- # Perplexity AI Configuration
67
- PERPLEXITY_API_KEY=your_perplexity_api_key_here
68
-
69
- # Revenium Configuration
70
- REVENIUM_METERING_API_KEY=your_revenium_api_key_here
71
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
72
-
73
- # Optional: Enable debug logging
74
- REVENIUM_LOG_LEVEL=INFO
75
- ```
76
-
77
- ### Step 4: Create Your First Test
78
-
79
- Create `test-perplexity.js`:
80
-
81
- ```javascript
82
- // test-perplexity.js
83
- import { createPerplexityClient } from "@revenium/perplexity";
84
-
85
- const client = createPerplexityClient();
86
-
87
- try {
88
- const result = await client.createChatCompletion({
89
- model: "sonar-pro",
90
- messages: [
91
- {
92
- role: "user",
93
- content: "What is the universe?",
94
- },
95
- ],
96
- });
97
-
98
- const text = result.choices[0]?.message?.content;
99
- console.log("*** RESPONSE ***");
100
- console.log(text);
101
- console.log("✅ Basic Perplexity AI example successful!");
102
- } catch (error) {
103
- console.error(" Perplexity basic example failed:", error);
104
- process.exit(1);
105
- }
106
- ```
107
-
108
- ### Step 5: Update package.json
109
-
110
- Add test scripts and module type to your `package.json`:
111
-
112
- ```json
113
- {
114
- "name": "my-perplexity-ai-project",
115
- "version": "1.0.0",
116
- "type": "module",
117
- "scripts": {
118
- "test-perplexity": "node test-perplexity.js"
119
- },
120
- "dependencies": {
121
- "@revenium/perplexity": "^1.0.0"
122
- }
123
- }
124
- ```
125
-
126
- **⚠️ Important**: If you get this error when running tests:
127
-
128
- ```
129
- SyntaxError: Cannot use import statement outside a module
130
- ```
131
-
132
- Make sure your `package.json` includes `"type": "module"` as shown below.
133
-
134
- ```json
135
- {
136
- "type": "module"
137
- }
138
- ```
139
-
140
- ### Step 6: Run Your Tests
141
-
142
- ```bash
143
- # Test Perplexity AI SDK
144
- npm run test-perplexity
145
- ```
146
-
147
- ### Step 7: Create Advanced Examples
148
-
149
- Create an `examples` directory and add these files:
150
-
151
- ```bash
152
- mkdir examples
153
- ```
154
-
155
- #### Streaming Example
156
-
157
- Create `examples/streaming-perplexity.js`:
158
-
159
- ```javascript
160
- // examples/streaming-perplexity.js
161
- import { createPerplexityClient } from "@revenium/perplexity";
162
-
163
- const client = createPerplexityClient();
164
-
165
- try {
166
- const stream = await client.createStreamingChatCompletion({
167
- model: "sonar-pro",
168
- messages: [
169
- {
170
- role: "user",
171
- content: "What is artificial intelligence?",
172
- },
173
- ],
174
- });
175
-
176
- console.log("*** STREAMING RESPONSE ***");
177
- let fullText = "";
178
-
179
- for await (const chunk of stream) {
180
- const content = chunk.choices[0]?.delta?.content;
181
- if (content) {
182
- process.stdout.write(content);
183
- fullText += content;
184
- }
185
- }
186
-
187
- console.log("\n✅ Streaming with metering successful!");
188
- console.log(`📊 Total response length: ${fullText.length} characters`);
189
- } catch (error) {
190
- console.error("❌ Perplexity streaming example failed:", error);
191
- process.exit(1);
192
- }
193
- ```
194
-
195
- #### Metadata Example
196
-
197
- Create `examples/metadata-perplexity.js`:
198
-
199
- ```javascript
200
- // examples/metadata-perplexity.js
201
- import { createPerplexityClient } from "@revenium/perplexity";
202
-
203
- const client = createPerplexityClient();
204
-
205
- try {
206
- const result = await client.createChatCompletion({
207
- model: "sonar-pro",
208
- messages: [
209
- {
210
- role: "user",
211
- content: "Analyze this quarterly report",
212
- },
213
- ],
214
- usageMetadata: {
215
- // User tracking
216
- traceId: "conv-28a7e9d4",
217
- taskType: "document-analysis",
218
- subscriberEmail: "user@example.com",
219
- subscriberId: "user-123",
220
- subscriberCredentialName: "api-key-1",
221
-
222
- // Business context
223
- organizationId: "acme-corp",
224
- subscriptionId: "premium-plan",
225
- productId: "business-intelligence",
226
- agent: "analysis-assistant",
227
- responseQualityScore: 0.95,
228
- },
229
- });
230
-
231
- console.log("*** METADATA RESPONSE ***");
232
- console.log("Response:", result.choices[0]?.message?.content);
233
- console.log(" Metadata tracking with metering successful!");
234
- } catch (error) {
235
- console.error(" Perplexity metadata example failed:", error);
236
- process.exit(1);
237
- }
238
- ```
239
-
240
- ### Step 8: Update package.json
241
-
242
- ```json
243
- {
244
- "name": "my-perplexity-ai-project",
245
- "version": "1.0.0",
246
- "type": "module",
247
- "scripts": {
248
- "test-perplexity": "node test-perplexity.js",
249
- "test-perplexity-stream": "node examples/streaming-perplexity.js",
250
- "test-perplexity-metadata": "node examples/metadata-perplexity.js"
251
- },
252
- "dependencies": {
253
- "@revenium/perplexity": "^1.0.0"
254
- }
255
- }
256
- ```
257
-
258
- ### Step 9: Test Advanced Examples
259
-
260
- ```bash
261
- # Test streaming
262
- npm run test-perplexity-stream
263
-
264
- # Test metadata
265
- npm run test-perplexity-metadata
266
- ```
267
-
268
- ---
269
-
270
- ## Option 2: Clone Repository
271
-
272
- Perfect for testing with pre-built examples:
273
-
274
- ```bash
275
- # Clone the repository
276
- git clone git@github.com:revenium/revenium-middleware-perplexity-node.git
277
- cd revenium-middleware-perplexity-node
278
-
279
- # Install dependencies
280
- npm install
281
-
282
- # Create your .env file
283
- cp .env.example .env
284
- # Edit .env with your API keys
285
- ```
286
-
287
- ### Configure Environment Variables
288
-
289
- Edit your `.env` file:
290
-
291
- ```env
292
- # For Perplexity AI SDK
293
- PERPLEXITY_API_KEY=your_perplexity_api_key_here
294
- REVENIUM_METERING_API_KEY=your_revenium_api_key_here
295
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
296
-
297
- ```
298
-
299
- ### Run Perplexity AI Examples
300
-
301
- ```bash
302
- # Perplexity AI examples
303
- npm run p-basic # Basic chat completion
304
- npm run p-streaming # Streaming response
305
- npm run p-metadata # Rich metadata tracking
306
-
307
- # Playground examples
308
- # Required build first
309
- npm run build
310
- # Then run any of the following
311
- npm run p-perplexity-basic
312
- npm run p-perplexity-streaming
313
- npm run p-perplexity-metadata
314
- ```
315
-
316
- ---
317
-
318
- ## Option 3: Existing Project Integration
319
-
320
- Already have a project? Just install and replace imports:
321
-
322
- ### Step 1. Install the Package
323
-
324
- ```bash
325
- npm install @revenium/perplexity
326
- ```
327
-
328
- ### Step 2. Add Environment Variables
329
-
330
- Add to your existing `.env` file:
331
-
332
- ```env
333
- PERPLEXITY_API_KEY=your_perplexity_api_key_here
334
- REVENIUM_METERING_API_KEY=your_revenium_api_key_here
335
- REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
336
- # Optional: Enable debug logging
337
- REVENIUM_LOG_LEVEL=INFO
338
- ```
339
-
340
- ### Step 3. Replace Your Imports
341
-
342
- **Before:**
343
-
344
- ```javascript
345
- import { OpenAI } from "openai";
346
- ```
347
-
348
- **After:**
349
-
350
- ```javascript
351
- import { createPerplexityClient } from "@revenium/perplexity";
352
- ```
353
-
354
- **Or Use OpenAI Client (Alternative):**
355
-
356
- ```javascript
357
- import { OpenAI } from "openai";
358
- import "@revenium/perplexity"; // Import middleware to activate tracking
359
- ```
360
-
361
- ### Step 4. Update Your Code
362
-
363
- **Revenium Client Example**
364
-
365
- ```javascript
366
- import { createPerplexityClient } from "@revenium/perplexity";
367
-
368
- // Initialize (API key from environment variable)
369
- const client = createPerplexityClient();
370
-
371
- // Make your request - metering happens automatically!
372
- const result = await client.createChatCompletion({
373
- model: "sonar-pro",
374
- messages: [{ role: "user", content: "What is artificial intelligence?" }],
375
- });
376
- console.log(result.choices[0]?.message?.content);
377
- ```
378
-
379
- **OpenAI Client Example**
380
-
381
- ```javascript
382
- import { OpenAI } from "openai";
383
- import "@revenium/perplexity"; // Import middleware for automatic tracking
384
-
385
- // Initialize OpenAI client for Perplexity
386
- const client = new OpenAI({
387
- apiKey: process.env.PERPLEXITY_API_KEY,
388
- baseURL: "https://api.perplexity.ai",
389
- });
390
-
391
- // Make your request - metering happens automatically!
392
- const result = await client.chat.completions.create({
393
- model: "sonar-pro",
394
- messages: [{ role: "user", content: "What is artificial intelligence?" }],
395
- });
396
- console.log(result.choices[0]?.message?.content);
397
- ```
398
-
399
- ## 🔧 Advanced Usage
400
-
401
- ### Streaming Responses
402
-
403
- **Revenium Client Streaming**
404
-
405
- ```javascript
406
- const stream = await client.createStreamingChatCompletion({
407
- model: "sonar-pro",
408
- messages: [{ role: "user", content: "Write a story about AI" }],
409
- });
410
-
411
- for await (const chunk of stream) {
412
- const content = chunk.choices[0]?.delta?.content;
413
- if (content) process.stdout.write(content);
414
- }
415
- ```
416
-
417
- **OpenAI Client Streaming**
418
-
419
- ```javascript
420
- import { OpenAI } from "openai";
421
- import "@revenium/perplexity";
422
-
423
- const client = new OpenAI({
424
- apiKey: process.env.PERPLEXITY_API_KEY,
425
- baseURL: "https://api.perplexity.ai",
426
- });
427
-
428
- const stream = await client.chat.completions.create({
429
- model: "sonar-pro",
430
- messages: [{ role: "user", content: "Write a story about AI" }],
431
- stream: true,
432
- });
433
-
434
- for await (const chunk of stream) {
435
- const content = chunk.choices[0]?.delta?.content;
436
- if (content) process.stdout.write(content);
437
- }
438
- ```
439
-
440
- ### Rich Metadata Tracking
441
-
442
- ```javascript
443
- import { createPerplexityClient } from "@revenium/perplexity";
444
-
445
- const client = createPerplexityClient();
446
-
447
- const response = await client.createChatCompletion({
448
- model: "sonar-pro",
449
- messages: [
450
- {
451
- role: "user",
452
- content: "Analyze this quarterly report",
453
- },
454
- ],
455
- usageMetadata: {
456
- // User tracking
457
- traceId: "conv-28a7e9d4",
458
- taskType: "document-analysis",
459
- subscriberEmail: "user@example.com",
460
- subscriberId: "user-123",
461
- subscriberCredentialName: "api-key-1",
462
-
463
- // Business context
464
- organizationId: "acme-corp",
465
- subscriptionId: "premium-plan",
466
- productId: "business-intelligence",
467
- agent: "analysis-assistant",
468
- responseQualityScore: 0.95,
469
- },
470
- });
471
- ```
472
-
473
- ## 📊 What Gets Tracked
474
-
475
- - **Token Usage**: Input and output tokens for accurate billing
476
- - **Request Duration**: Total time for each API call
477
- - **Model Information**: Which model was used
478
- - **Operation Type**: Chat completion, streaming
479
- - **Error Tracking**: Failed requests and error details
480
- - **Streaming Metrics**: Time to first token for streaming responses
481
- - **Custom Metadata**: Rich business context and user tracking
482
-
483
- ## 🔗 Supported Models
484
-
485
- ### Chat Models
486
-
487
- - **sonar-pro** (Latest and most capable)
488
- - **sonar-small** (Fast and efficient)
489
- - **sonar-medium** (Balanced performance)
490
-
491
- _Note: Model availability depends on your Perplexity AI account and API access level._
492
-
493
- ## 🛠️ Configuration Options
494
-
495
- ### Environment Variables
496
-
497
- | Variable | Required | Description |
498
- | ---------------------------- | -------- | --------------------------------------------------------------- |
499
- | `PERPLEXITY_API_KEY` | | Your Perplexity API key |
500
- | `REVENIUM_METERING_API_KEY` | ✅ | Your Revenium API key |
501
- | `PERPLEXITY_BASE_URL` | ❌ | Custom Perplexity base URL (default: https://api.perplexity.ai) |
502
- | `REVENIUM_METERING_BASE_URL` | ❌ | Revenium base URL (default: https://api.revenium.io/meter/v2) |
503
- | `REVENIUM_LOG_LEVEL` | ❌ | Log level: DEBUG, INFO, WARNING, ERROR |
504
-
505
- ### Manual Configuration
506
-
507
- ```javascript
508
- // Revenium client with custom configuration
509
- const client = createPerplexityClient(
510
- "your-api-key",
511
- "https://api.perplexity.ai"
512
- );
513
-
514
- // OpenAI client with custom base URL
515
- const openaiClient = new OpenAI({
516
- apiKey: "your-api-key",
517
- baseURL: "https://custom-perplexity-endpoint.com",
518
- });
519
- ```
520
-
521
- ## 🚨 Troubleshooting
522
-
523
- ### Common Issues
524
-
525
- **"Missing API Key" Error**
526
-
527
- ```bash
528
- export PERPLEXITY_API_KEY="your-actual-api-key"
529
- echo $PERPLEXITY_API_KEY # Verify it's set
530
- ```
531
-
532
- **"Requests not being tracked"**
533
-
534
- ```bash
535
- export REVENIUM_METERING_API_KEY="your-actual-revenium-key"
536
- export REVENIUM_LOG_LEVEL="DEBUG" # Enable debug logging
537
- ```
538
-
539
- **Module Import Errors**
540
-
541
- ```json
542
- {
543
- "type": "module"
544
- }
545
- ```
546
-
547
- ## 📋 Requirements
548
-
549
- - Node.js 18+
550
- - Perplexity API key
551
- - Revenium API key
552
-
553
- ## 📄 License
554
-
555
- MIT License - see the [LICENSE](LICENSE) file for details.
556
-
557
- ## 🤝 Support
558
-
559
- - 📖 [Documentation](https://docs.revenium.io)
560
- - 💬 [Community Support](https://community.revenium.io)
561
- - 📧 [Email Support](mailto:support@revenium.io)
562
- - 🐛 [Report Issues](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
563
-
564
- ---
565
-
566
- **Built with ❤️ by Revenium**
1
+ # Revenium Middleware for Perplexity AI (Node.js)
2
+
3
+ [![npm version](https://badge.fury.io/js/%40revenium%2Fperplexity.svg)](https://badge.fury.io/js/%40revenium%2Fperplexity)
4
+ [![Node Versions](https://img.shields.io/node/v/@revenium/perplexity.svg)](https://www.npmjs.com/package/@revenium/perplexity)
5
+ [![Documentation](https://img.shields.io/badge/docs-available-brightgreen.svg)](https://docs.revenium.io)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ Automatically track and meter your Perplexity AI API usage with Revenium. This middleware provides seamless integration with Perplexity AI SDK, requiring minimal code changes.
9
+
10
+ ## 🚀 Getting Started
11
+
12
+ You have 3 options to start using Revenium middleware for Perplexity AI:
13
+
14
+ | Option | Description | Best For |
15
+ | ----------------------------------------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
16
+ | **Option 1: Create Project from Scratch** | Perfect for new projects. We'll guide you step-by-step from mkdir to running tests. | 👉 [Go to Step-by-Step Guide](#option-1-create-project-from-scratch) |
17
+ | **Option 2: Clone Our Repository** | Quick testing with pre-built examples and playground scripts. | 👉 [Go to Clone Guide](#option-2-clone-repository) |
18
+ | **Option 3: Add to Existing Project** | Already have a project? Just install and replace imports. | 👉 [Go to Quick Integration](#option-3-existing-project-integration) |
19
+
20
+ ---
21
+
22
+ ## Option 1: Create Project from Scratch
23
+
24
+ ### Step 1: Create Project Directory
25
+
26
+ ```bash
27
+ # Create and navigate to your project
28
+ mkdir my-perplexity-ai-project
29
+ cd my-perplexity-ai-project
30
+
31
+ # Initialize Node.js project
32
+ npm init -y
33
+ ```
34
+
35
+ ### Step 2: Install Dependencies
36
+
37
+ ```bash
38
+ npm install @revenium/perplexity
39
+ ```
40
+
41
+ ### Step 3: Setup Environment Variables
42
+
43
+ Create a `.env` file in your project root:
44
+
45
+ ```bash
46
+ # Create .env file
47
+ echo. > .env # On Windows (CMD TERMINAL)
48
+ touch .env # On Mac/Linux (CMD TERMINAL)
49
+ # OR
50
+ #PowerShell
51
+ New-Item -Path .env -ItemType File
52
+ ```
53
+
54
+ Copy and paste the following into `.env`:
55
+
56
+ ```bash
57
+ # Perplexity AI Configuration
58
+ PERPLEXITY_API_KEY=your_perplexity_api_key_here
59
+
60
+ # Revenium Configuration
61
+ REVENIUM_METERING_API_KEY=your_revenium_api_key_here
62
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
63
+
64
+ ```
65
+
66
+ ### Step 4: Create Your First Test
67
+
68
+ Create `test-perplexity.js`:
69
+
70
+ ```javascript
71
+ // test-perplexity.js
72
+ import { createPerplexityClient } from "@revenium/perplexity";
73
+
74
+ const client = createPerplexityClient();
75
+
76
+ try {
77
+ const result = await client.createChatCompletion({
78
+ model: "sonar-pro",
79
+ messages: [
80
+ {
81
+ role: "user",
82
+ content: "What is the universe?",
83
+ },
84
+ ],
85
+ });
86
+
87
+ const text = result.choices[0]?.message?.content;
88
+ console.log("*** RESPONSE ***");
89
+ console.log(text);
90
+ console.log("✅ Basic Perplexity AI example successful!");
91
+ } catch (error) {
92
+ console.error("❌ Perplexity basic example failed:", error);
93
+ process.exit(1);
94
+ }
95
+ ```
96
+
97
+ ### Step 5: Update package.json
98
+
99
+ Add test scripts and module type to your `package.json`:
100
+
101
+ ```json
102
+ {
103
+ "name": "my-perplexity-ai-project",
104
+ "version": "1.0.0",
105
+ "type": "module",
106
+ "scripts": {
107
+ "test-perplexity": "node test-perplexity.js"
108
+ },
109
+ "dependencies": {
110
+ "@revenium/perplexity": "^1.0.0"
111
+ }
112
+ }
113
+ ```
114
+
115
+ ⚠️ **Important**: If you get this error when running tests:
116
+
117
+ ```
118
+ SyntaxError: Cannot use import statement outside a module
119
+ ```
120
+
121
+ Make sure your `package.json` includes `"type": "module"` as shown below.
122
+
123
+ ```json
124
+ {
125
+ "type": "module"
126
+ }
127
+ ```
128
+
129
+ ### Step 6: Run Your Tests
130
+
131
+ ```bash
132
+ # Test Perplexity AI SDK
133
+ npm run test-perplexity
134
+ ```
135
+
136
+ ### Step 7: Create Advanced Examples
137
+
138
+ Create an examples directory and add these files:
139
+
140
+ ```bash
141
+ mkdir examples
142
+ ```
143
+
144
+ #### Streaming Example
145
+
146
+ Create `examples/streaming-perplexity.js`:
147
+
148
+ ```javascript
149
+ // examples/streaming-perplexity.js
150
+ import { createPerplexityClient } from "@revenium/perplexity";
151
+
152
+ const client = createPerplexityClient();
153
+
154
+ try {
155
+ const stream = await client.createStreamingChatCompletion({
156
+ model: "sonar-pro",
157
+ messages: [
158
+ {
159
+ role: "user",
160
+ content: "What is artificial intelligence?",
161
+ },
162
+ ],
163
+ });
164
+
165
+ console.log("*** STREAMING RESPONSE ***");
166
+ let fullText = "";
167
+
168
+ for await (const chunk of stream) {
169
+ const content = chunk.choices[0]?.delta?.content;
170
+ if (content) {
171
+ process.stdout.write(content);
172
+ fullText += content;
173
+ }
174
+ }
175
+
176
+ console.log("\n✅ Streaming with metering successful!");
177
+ console.log(`📊 Total response length: ${fullText.length} characters`);
178
+ } catch (error) {
179
+ console.error("❌ Perplexity streaming example failed:", error);
180
+ process.exit(1);
181
+ }
182
+ ```
183
+
184
+ #### Metadata Example
185
+
186
+ Create `examples/metadata-perplexity.js`:
187
+
188
+ ```javascript
189
+ // examples/metadata-perplexity.js
190
+ import { createPerplexityClient } from "@revenium/perplexity";
191
+
192
+ const client = createPerplexityClient();
193
+
194
+ try {
195
+ const result = await client.createChatCompletion({
196
+ model: "sonar-pro",
197
+ messages: [
198
+ {
199
+ role: "user",
200
+ content: "Analyze this quarterly report",
201
+ },
202
+ ],
203
+ usageMetadata: {
204
+ // User tracking
205
+ traceId: "conv-28a7e9d4",
206
+ taskType: "document-analysis",
207
+ subscriberEmail: "user@example.com",
208
+ subscriberId: "user-123",
209
+ subscriberCredentialName: "api-key-1",
210
+
211
+ // Business context
212
+ organizationId: "acme-corp",
213
+ subscriptionId: "premium-plan",
214
+ productId: "business-intelligence",
215
+ agent: "analysis-assistant",
216
+ responseQualityScore: 0.95,
217
+ },
218
+ });
219
+
220
+ console.log("*** METADATA RESPONSE ***");
221
+ console.log("Response:", result.choices[0]?.message?.content);
222
+ console.log("✅ Metadata tracking with metering successful!");
223
+ } catch (error) {
224
+ console.error("❌ Perplexity metadata example failed:", error);
225
+ process.exit(1);
226
+ }
227
+ ```
228
+
229
+ ### Step 8: Update package.json
230
+
231
+ ```json
232
+ {
233
+ "name": "my-perplexity-ai-project",
234
+ "version": "1.0.0",
235
+ "type": "module",
236
+ "scripts": {
237
+ "test-perplexity": "node test-perplexity.js",
238
+ "test-perplexity-stream": "node examples/streaming-perplexity.js",
239
+ "test-perplexity-metadata": "node examples/metadata-perplexity.js"
240
+ },
241
+ "dependencies": {
242
+ "@revenium/perplexity": "^1.0.0"
243
+ }
244
+ }
245
+ ```
246
+
247
+ ### Step 9: Test Advanced Examples
248
+
249
+ ```bash
250
+ # Test streaming
251
+ npm run test-perplexity-stream
252
+
253
+ # Test metadata
254
+ npm run test-perplexity-metadata
255
+ ```
256
+
257
+ ---
258
+
259
+ ## Option 2: Clone Repository
260
+
261
+ Perfect for testing with pre-built examples:
262
+
263
+ ```bash
264
+ # Clone the repository
265
+ git clone git@github.com:revenium/revenium-middleware-perplexity-node.git
266
+ cd revenium-middleware-perplexity-node
267
+
268
+ # Install dependencies
269
+ npm install
270
+
271
+ # Create your .env file
272
+ cp .env.example .env
273
+ # Edit .env with your API keys
274
+ ```
275
+
276
+ ### Configure Environment Variables
277
+
278
+ Edit your `.env` file:
279
+
280
+ ```bash
281
+ # For Perplexity AI SDK
282
+ PERPLEXITY_API_KEY=your_perplexity_api_key_here
283
+ REVENIUM_METERING_API_KEY=your_revenium_api_key_here
284
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
285
+ ```
286
+
287
+ ### Run Perplexity AI Examples
288
+
289
+ ```bash
290
+ # Perplexity AI examples
291
+ npm run p-basic # Basic chat completion
292
+ npm run p-streaming # Streaming response
293
+ npm run p-metadata # Rich metadata tracking
294
+
295
+ # Playground examples
296
+ # Required build first
297
+ npm run build
298
+ # Then run any of the following
299
+ npm run p-perplexity-basic
300
+ npm run p-perplexity-streaming
301
+ npm run p-perplexity-metadata
302
+ ```
303
+
304
+ ---
305
+
306
+ ## Option 3: Existing Project Integration
307
+
308
+ Already have a project? Just install and replace imports:
309
+
310
+ ### Step 1. Install the Package
311
+
312
+ ```bash
313
+ npm install @revenium/perplexity
314
+ ```
315
+
316
+ ### Step 2. Add Environment Variables
317
+
318
+ Add to your existing `.env` file:
319
+
320
+ ```bash
321
+ PERPLEXITY_API_KEY=your_perplexity_api_key_here
322
+ REVENIUM_METERING_API_KEY=your_revenium_api_key_here
323
+ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter
324
+ # Optional: Enable debug logging
325
+ REVENIUM_LOG_LEVEL=INFO
326
+ ```
327
+
328
+ ### Step 3. Replace Your Imports
329
+
330
+ **Before:**
331
+
332
+ ```javascript
333
+ import { OpenAI } from "openai";
334
+ ```
335
+
336
+ **After:**
337
+
338
+ ```javascript
339
+ import { createPerplexityClient } from "@revenium/perplexity";
340
+ ```
341
+
342
+ **Or Use OpenAI Client (Alternative):**
343
+
344
+ ```javascript
345
+ import { OpenAI } from "openai";
346
+ import "@revenium/perplexity"; // Import middleware to activate tracking
347
+ ```
348
+
349
+ ### Step 4. Update Your Code
350
+
351
+ #### Revenium Client Example
352
+
353
+ ```javascript
354
+ import { createPerplexityClient } from "@revenium/perplexity";
355
+
356
+ // Initialize (API key from environment variable)
357
+ const client = createPerplexityClient();
358
+
359
+ // Make your request - metering happens automatically!
360
+ const result = await client.createChatCompletion({
361
+ model: "sonar-pro",
362
+ messages: [{ role: "user", content: "What is artificial intelligence?" }],
363
+ });
364
+ console.log(result.choices[0]?.message?.content);
365
+ ```
366
+
367
+ #### OpenAI Client Example
368
+
369
+ ```javascript
370
+ import { OpenAI } from "openai";
371
+ import "@revenium/perplexity"; // Import middleware for automatic tracking
372
+
373
+ // Initialize OpenAI client for Perplexity
374
+ const client = new OpenAI({
375
+ apiKey: process.env.PERPLEXITY_API_KEY,
376
+ baseURL: "https://api.perplexity.ai",
377
+ });
378
+
379
+ // Make your request - metering happens automatically!
380
+ const result = await client.chat.completions.create({
381
+ model: "sonar-pro",
382
+ messages: [{ role: "user", content: "What is artificial intelligence?" }],
383
+ });
384
+ console.log(result.choices[0]?.message?.content);
385
+ ```
386
+
387
+ ---
388
+
389
+ ## 🔧 Advanced Usage
390
+
391
+ ### Streaming Responses
392
+
393
+ #### Revenium Client Streaming
394
+
395
+ ```javascript
396
+ const stream = await client.createStreamingChatCompletion({
397
+ model: "sonar-pro",
398
+ messages: [{ role: "user", content: "Write a story about AI" }],
399
+ });
400
+
401
+ for await (const chunk of stream) {
402
+ const content = chunk.choices[0]?.delta?.content;
403
+ if (content) process.stdout.write(content);
404
+ }
405
+ ```
406
+
407
+ #### OpenAI Client Streaming
408
+
409
+ ```javascript
410
+ import { OpenAI } from "openai";
411
+ import "@revenium/perplexity";
412
+
413
+ const client = new OpenAI({
414
+ apiKey: process.env.PERPLEXITY_API_KEY,
415
+ baseURL: "https://api.perplexity.ai",
416
+ });
417
+
418
+ const stream = await client.chat.completions.create({
419
+ model: "sonar-pro",
420
+ messages: [{ role: "user", content: "Write a story about AI" }],
421
+ stream: true,
422
+ });
423
+
424
+ for await (const chunk of stream) {
425
+ const content = chunk.choices[0]?.delta?.content;
426
+ if (content) process.stdout.write(content);
427
+ }
428
+ ```
429
+
430
+ ### Rich Metadata Tracking
431
+
432
+ ```javascript
433
+ import { createPerplexityClient } from "@revenium/perplexity";
434
+
435
+ const client = createPerplexityClient();
436
+
437
+ const response = await client.createChatCompletion({
438
+ model: "sonar-pro",
439
+ messages: [
440
+ {
441
+ role: "user",
442
+ content: "Analyze this quarterly report",
443
+ },
444
+ ],
445
+ usageMetadata: {
446
+ // User tracking
447
+ traceId: "conv-28a7e9d4",
448
+ taskType: "document-analysis",
449
+ subscriberEmail: "user@example.com",
450
+ subscriberId: "user-123",
451
+ subscriberCredentialName: "api-key-1",
452
+
453
+ // Business context
454
+ organizationId: "acme-corp",
455
+ subscriptionId: "premium-plan",
456
+ productId: "business-intelligence",
457
+ agent: "analysis-assistant",
458
+ responseQualityScore: 0.95,
459
+ },
460
+ });
461
+ ```
462
+
463
+ ---
464
+
465
+ ## 📊 What Gets Tracked
466
+
467
+ - **Token Usage**: Input and output tokens for accurate billing
468
+ - **Request Duration**: Total time for each API call
469
+ - **Model Information**: Which model was used
470
+ - **Operation Type**: Chat completion, streaming
471
+ - **Error Tracking**: Failed requests and error details
472
+ - **Streaming Metrics**: Time to first token for streaming responses
473
+ - **Custom Metadata**: Rich business context and user tracking
474
+
475
+ ---
476
+
477
+ ## 🔗 Supported Models
478
+
479
+ ### Chat Models
480
+
481
+ - **sonar-pro** (Latest and most capable)
482
+ - **sonar-small** (Fast and efficient)
483
+ - **sonar-medium** (Balanced performance)
484
+
485
+ _Note: Model availability depends on your Perplexity AI account and API access level._
486
+
487
+ ---
488
+
489
+ ## 🛠️ Configuration Options
490
+
491
+ ### Environment Variables
492
+
493
+ | Variable | Required | Description |
494
+ | ---------------------------- | -------- | --------------------------------------------------------------- |
495
+ | `PERPLEXITY_API_KEY` | ✅ | Your Perplexity API key |
496
+ | `REVENIUM_METERING_API_KEY` | ✅ | Your Revenium API key |
497
+ | `PERPLEXITY_BASE_URL` | | Custom Perplexity base URL (default: https://api.perplexity.ai) |
498
+ | `REVENIUM_METERING_BASE_URL` | | Revenium base URL (default: https://api.revenium.io/meter/v2) |
499
+ | `REVENIUM_LOG_LEVEL` | | Log level: DEBUG, INFO, WARNING, ERROR |
500
+
501
+ ### Manual Configuration
502
+
503
+ ```javascript
504
+ // Revenium client with custom configuration
505
+ const client = createPerplexityClient(
506
+ "your-api-key",
507
+ "https://api.perplexity.ai"
508
+ );
509
+
510
+ // OpenAI client with custom base URL
511
+ const openaiClient = new OpenAI({
512
+ apiKey: "your-api-key",
513
+ baseURL: "https://custom-perplexity-endpoint.com",
514
+ });
515
+ ```
516
+
517
+ ---
518
+
519
+ ## 🚨 Troubleshooting
520
+
521
+ ### Common Issues
522
+
523
+ **"Missing API Key" Error**
524
+
525
+ ```bash
526
+ export PERPLEXITY_API_KEY="your-actual-api-key"
527
+ echo $PERPLEXITY_API_KEY # Verify it's set
528
+ ```
529
+
530
+ **"Requests not being tracked"**
531
+
532
+ ```bash
533
+ export REVENIUM_METERING_API_KEY="your-actual-revenium-key"
534
+ export REVENIUM_LOG_LEVEL="DEBUG" # Enable debug logging
535
+ ```
536
+
537
+ **Module Import Errors**
538
+
539
+ ```json
540
+ {
541
+ "type": "module"
542
+ }
543
+ ```
544
+
545
+ ### Debug Mode
546
+
547
+ Enable detailed logging to troubleshoot issues:
548
+
549
+ ```bash
550
+ export REVENIUM_LOG_LEVEL="DEBUG"
551
+ export REVENIUM_VERBOSE_STARTUP="true"
552
+ node your-script.js
553
+ ```
554
+
555
+ This will show:
556
+
557
+ - Request/response details
558
+ - Token counting information
559
+ - Metering data being sent
560
+ - Error details
561
+ - Middleware activation status
562
+
563
+ ---
564
+
565
+ ## 📚 Examples Repository
566
+
567
+ Check out our comprehensive examples:
568
+
569
+ - **Basic Usage**: Simple chat completions
570
+ - **Streaming**: Real-time response streaming
571
+ - **Metadata**: Rich tracking examples
572
+ - **Error Handling**: Robust error management
573
+ - **Advanced Patterns**: Complex use cases
574
+ - **Configuration**: Different setup options
575
+
576
+ All examples are in the `/examples` and `/playground` directories.
577
+
578
+ ---
579
+
580
+ ## 📋 Requirements
581
+
582
+ - Node.js 18+
583
+ - Perplexity API key
584
+ - Revenium API key
585
+
586
+ ---
587
+
588
+ ## 📄 License
589
+
590
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
591
+
592
+ ---
593
+
594
+ ## 🤝 Support
595
+
596
+ - 📖 [Documentation](https://docs.revenium.io)
597
+ - 💬 [Community Support](https://community.revenium.io)
598
+ - 📧 [Email Support](mailto:support@revenium.io)
599
+ - 🐛 [Report Issues](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
600
+
601
+ ---
602
+
603
+ **Built with ❤️ by Revenium**