@revenium/perplexity 2.0.4 → 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 (205) hide show
  1. package/CHANGELOG.md +32 -33
  2. package/README.md +120 -101
  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 -59
  39. package/dist/cjs/index.js.map +1 -1
  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 -1
  43. package/dist/cjs/types/index.js.map +1 -1
  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 -39
  91. package/dist/esm/index.js.map +1 -1
  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 -2
  95. package/dist/esm/types/index.js.map +1 -1
  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 -1
  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 -129
  147. package/dist/types/types/index.d.ts.map +1 -1
  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 +124 -220
  161. package/examples/advanced.ts +123 -0
  162. package/examples/basic.ts +32 -37
  163. package/examples/getting_started.ts +26 -49
  164. package/examples/metadata.ts +51 -48
  165. package/examples/stream.ts +53 -0
  166. package/package.json +9 -10
  167. package/dist/cjs/constants.js +0 -70
  168. package/dist/cjs/constants.js.map +0 -1
  169. package/dist/cjs/core/config/perplexity-config.js +0 -45
  170. package/dist/cjs/core/config/perplexity-config.js.map +0 -1
  171. package/dist/cjs/core/config/revenium-config.js +0 -80
  172. package/dist/cjs/core/config/revenium-config.js.map +0 -1
  173. package/dist/cjs/core/tracking/metering.js +0 -211
  174. package/dist/cjs/core/tracking/metering.js.map +0 -1
  175. package/dist/cjs/core/wrapper/perplexity-client.js +0 -187
  176. package/dist/cjs/core/wrapper/perplexity-client.js.map +0 -1
  177. package/dist/cjs/utils/logger.js +0 -23
  178. package/dist/cjs/utils/logger.js.map +0 -1
  179. package/dist/esm/constants.js +0 -67
  180. package/dist/esm/constants.js.map +0 -1
  181. package/dist/esm/core/config/perplexity-config.js +0 -40
  182. package/dist/esm/core/config/perplexity-config.js.map +0 -1
  183. package/dist/esm/core/config/revenium-config.js +0 -72
  184. package/dist/esm/core/config/revenium-config.js.map +0 -1
  185. package/dist/esm/core/tracking/metering.js +0 -206
  186. package/dist/esm/core/tracking/metering.js.map +0 -1
  187. package/dist/esm/core/wrapper/perplexity-client.js +0 -180
  188. package/dist/esm/core/wrapper/perplexity-client.js.map +0 -1
  189. package/dist/esm/utils/logger.js +0 -20
  190. package/dist/esm/utils/logger.js.map +0 -1
  191. package/dist/types/constants.d.ts +0 -67
  192. package/dist/types/constants.d.ts.map +0 -1
  193. package/dist/types/core/config/perplexity-config.d.ts +0 -24
  194. package/dist/types/core/config/perplexity-config.d.ts.map +0 -1
  195. package/dist/types/core/config/revenium-config.d.ts +0 -37
  196. package/dist/types/core/config/revenium-config.d.ts.map +0 -1
  197. package/dist/types/core/tracking/metering.d.ts +0 -31
  198. package/dist/types/core/tracking/metering.d.ts.map +0 -1
  199. package/dist/types/core/wrapper/perplexity-client.d.ts +0 -32
  200. package/dist/types/core/wrapper/perplexity-client.d.ts.map +0 -1
  201. package/dist/types/utils/logger.d.ts +0 -10
  202. package/dist/types/utils/logger.d.ts.map +0 -1
  203. package/examples/advanced-features.ts +0 -148
  204. package/examples/chat.ts +0 -73
  205. package/examples/streaming.ts +0 -50
package/CHANGELOG.md CHANGED
@@ -7,59 +7,60 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
- ## [2.0.4] - 2025-11-07
11
-
12
- ### Changed
13
- - Aligned package.json files array with template standards (use dist/ and examples/ wildcards)
14
- - Updated documentation badge format to match template standards
15
- - Improved README header with consistent badge styling
16
-
17
- ### Fixed
18
- - Removed dist/ build artifacts from version control
19
- - Added dist/ to .gitignore to prevent future commits of build artifacts
20
- - Updated API URL to api.revenium.ai in examples/README.md
10
+ ## [2.0.5] - 2025-11-09
21
11
 
22
12
  ### Added
23
-
24
- - New `getting_started.ts` example for quick onboarding
25
- - New `advanced-features.ts` example with streaming and metadata
26
- - Comprehensive metadata fields documentation
27
- - Support for new Perplexity models (sonar-reasoning-pro, sonar-deep-research)
13
+ - New `Initialize()` and `GetClient()` pattern for cleaner client initialization
14
+ - `Configure()` function for explicit configuration without environment variables
15
+ - `IsInitialized()` and `Reset()` utility functions for better state management
16
+ - Automatic `.env` file loading via dotenv for simplified configuration
17
+ - Modular architecture with organized `core/` directory structure
18
+ - Enhanced examples: `basic.ts`, `metadata.ts`, `advanced.ts`, `stream.ts`
19
+ - Export `PERPLEXITY_MODELS` constants (SONAR_PRO, SONAR, SONAR_REASONING)
20
+ - Export `PerplexityModel` type for type-safe model references
21
+ - Support for all 7 AI operation types (CHAT, GENERATE, EMBED, CLASSIFY, SUMMARIZE, TRANSLATE, OTHER)
28
22
 
29
23
  ### Changed
30
-
31
- - Updated model definitions to current Perplexity API
32
- - Improved example scripts in package.json
24
+ - Improved API compliance with Revenium specification for provider naming and metadata
25
+ - Enhanced token counting accuracy with proper handling of cache tokens
26
+ - Email addresses now masked in debug logs for PII protection
27
+ - Quality scores use 0.0-1.0 scale per API specification
28
+ - Removed hardcoded model lists - middleware accepts any model name
33
29
 
34
30
  ### Fixed
31
+ - ESM support by removing CommonJS type restriction and adding explicit `.js` extensions
32
+ - API key validation now enforced in `Configure()` function
33
+ - Base URL validation relaxed to accept default endpoints
34
+ - npm script references corrected in documentation
35
+ - Environment variable examples updated for clarity
35
36
 
36
- - Corrected metadata field names throughout documentation
37
- - Added TypeScript support for subscriptionId and responseQualityScore fields
38
- - Removed hardcoded credentials from all documentation examples
39
- - Corrected Revenium platform URLs (app.revenium.ai)
40
-
41
- ## [2.0.3] - 2025-10-21
37
+ ## [2.0.4] - 2025-10-21
42
38
 
43
39
  ### Changed
44
40
 
45
41
  - Enhanced package.json with examples in files array
46
42
  - Added community health files (CODE_OF_CONDUCT.md, CONTRIBUTING.md, SECURITY.md)
47
- - Updated .gitignore with security report patterns (including package-lock.json)
48
- - Added CHANGELOG.md for version tracking
43
+ - Updated .gitignore with security report patterns
49
44
  - Added engines field for Node.js version requirements
50
45
 
51
- ## [2.0.2] - 2025-10-17
46
+ ## [2.0.3] - 2025-10-17
52
47
 
53
48
  ### Changed
54
49
 
55
50
  - Documentation improvements with absolute path references
56
51
 
57
- ## [2.0.1] - 2025-10-09
52
+ ## [2.0.2] - 2025-10-09
58
53
 
59
54
  ### Changed
60
55
 
61
56
  - Internal updates and improvements
62
57
 
58
+ ## [2.0.1] - 2025-10-09
59
+
60
+ ### Changed
61
+
62
+ - Bug fixes and stability improvements
63
+
63
64
  ## [2.0.0] - 2025-10-09
64
65
 
65
66
  ### Added
@@ -68,12 +69,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
68
69
  - Dual package exports (ESM + CommonJS) support
69
70
  - TypeScript declaration maps for better debugging
70
71
  - Enhanced build system with separate CJS, ESM, and types builds
71
- - New examples structure (basic.ts, chat.ts, streaming.ts, metadata.ts)
72
72
 
73
73
  ### Changed
74
74
 
75
75
  - Restructured src/ directory with core/config, core/tracking, core/wrapper
76
- - Updated examples to use new structure
77
76
  - Enhanced README with comprehensive documentation
78
77
 
79
78
  ## [1.0.0] - 2025-09-23
@@ -82,15 +81,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
82
81
 
83
82
  - Initial release of Perplexity AI middleware
84
83
  - Automatic token counting and usage tracking
85
- - Support for all Perplexity models
86
84
  - Streaming support with automatic tracking
87
85
  - Custom metadata integration
88
86
  - TypeScript support with full type safety
89
- - Multiple client options
90
87
  - Comprehensive error handling
91
88
  - Background processing for non-blocking tracking
92
89
  - Debug logging support
93
90
 
91
+ [2.0.5]: https://github.com/revenium/revenium-middleware-perplexity-node/releases/tag/v2.0.5
92
+ [2.0.4]: https://github.com/revenium/revenium-middleware-perplexity-node/releases/tag/v2.0.4
94
93
  [2.0.3]: https://github.com/revenium/revenium-middleware-perplexity-node/releases/tag/v2.0.3
95
94
  [2.0.2]: https://github.com/revenium/revenium-middleware-perplexity-node/releases/tag/v2.0.2
96
95
  [2.0.1]: https://github.com/revenium/revenium-middleware-perplexity-node/releases/tag/v2.0.1
package/README.md CHANGED
@@ -10,7 +10,6 @@ A lightweight, production-ready middleware that adds **Revenium metering and tra
10
10
 
11
11
  ## Features
12
12
 
13
- - **Zero Configuration** - Works out of the box with environment variables
14
13
  - **Automatic Metering** - Tracks all API calls with detailed usage metrics
15
14
  - **Streaming Support** - Full support for streaming responses
16
15
  - **TypeScript First** - Built with TypeScript, includes full type definitions
@@ -39,7 +38,7 @@ The following guide walks you through creating a new project from scratch:
39
38
  mkdir my-perplexity-project
40
39
  cd my-perplexity-project
41
40
 
42
- # Initialize Node.js project
41
+ # Initialize npm project
43
42
  npm init -y
44
43
  ```
45
44
 
@@ -55,7 +54,7 @@ npm install -D typescript tsx @types/node
55
54
 
56
55
  #### Step 3: Setup Environment Variables
57
56
 
58
- Create a `.env` file in your project root:
57
+ Create a `.env` file in your project root.
59
58
 
60
59
  ```bash
61
60
  # Copy the example file
@@ -70,132 +69,90 @@ See [`.env.example`](https://github.com/revenium/revenium-middleware-perplexity-
70
69
 
71
70
  #### Step 4: Follow the Examples
72
71
 
73
- See [examples/README.md](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/README.md) for complete examples and setup instructions.
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.
74
73
 
75
74
  **Cloned from GitHub?** Run examples with:
76
75
 
77
76
  ```bash
78
77
  npm install
78
+ npm run example:getting-started # Start here!
79
79
  npm run example:basic
80
- npm run example:streaming
81
- npm run example:chat
80
+ npm run example:stream
82
81
  npm run example:metadata
83
82
  npm run example:advanced
84
- npm run example:getting-started
85
83
  ```
86
84
 
87
- **Browse online:** [`examples/` directory](https://github.com/revenium/revenium-middleware-perplexity-node/tree/HEAD/examples)
88
-
89
85
  ---
90
86
 
91
87
  ## What Gets Tracked
92
88
 
93
- The middleware automatically captures:
94
-
95
- - **Token Usage**: Prompt and completion tokens for accurate billing
96
- - **Request Duration**: Total time for each API call
97
- - **Model Information**: Which Perplexity model was used
98
- - **Operation Type**: Chat completion, streaming, etc.
99
- - **Error Tracking**: Failed requests and error details
100
- - **Streaming Metrics**: Time to first token for streaming responses
101
- - **Custom Metadata**: Business context you provide
102
-
103
- ## Advanced Usage
104
-
105
- For advanced features including:
106
-
107
- - **Initialization Options** - Environment variables vs manual configuration
108
- - **Streaming Responses** - Real-time streaming with usage tracking
109
- - **Custom Metadata Tracking** - Add business context to your API calls
110
-
111
- See the **[Examples Guide](./examples/README.md)** for detailed documentation and working code examples.
112
-
113
- ### Metadata Fields Reference
89
+ The middleware automatically captures comprehensive usage data:
114
90
 
115
- The `usageMetadata` parameter supports the following fields for detailed tracking:
116
-
117
- | Field | Description | Use Case |
118
- | ----------------------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
119
- | `traceId` | Unique identifier for session or conversation tracking | Link multiple API calls together for debugging, user session analytics, or distributed tracing across services |
120
- | `taskType` | Type of AI task being performed | Categorize usage by workload (e.g., "search", "research", "qa") for cost analysis and optimization |
121
- | `subscriber.id` | Unique user identifier | Track individual user consumption for billing, rate limiting, or user analytics |
122
- | `subscriber.email` | User's email address | Associate usage with specific users for reporting and communication |
123
- | `subscriber.credential` | Object containing credential information | Track usage by API keys and credentials |
124
- | `subscriber.credential.name` | Authentication credential name | Track which API key or service account made the request |
125
- | `subscriber.credential.value` | Authentication credential value | Associate usage with specific credentials for security auditing |
126
- | `organizationId` | Organization or company identifier | Multi-tenant cost allocation, usage quotas per organization |
127
- | `subscriptionId` | Subscription plan identifier | Track usage against subscription limits, identify plan upgrade opportunities |
128
- | `productId` | Your product or feature identifier | Attribute AI costs to specific features in your application (e.g., "search-bot", "research-assistant") |
129
- | `agent` | AI agent or bot identifier | Distinguish between multiple AI agents or automation workflows in your system |
130
- | `responseQualityScore` | Custom quality rating (0.0-1.0) | Track user satisfaction or automated quality metrics for model performance analysis |
131
-
132
- For complete API documentation and additional details, see the [Revenium API Reference](https://revenium.readme.io/reference/meter_ai_completion).
133
-
134
- ## Troubleshooting
135
-
136
- ### Common Issues
91
+ ### **Usage Metrics**
137
92
 
138
- #### "Missing API Key" Error
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
139
97
 
140
- ```bash
141
- # Verify your .env file exists and has the required keys
142
- cat .env
98
+ ### **Business Context (Optional)**
143
99
 
144
- # Or use .env.example as a template
145
- cp .env.example .env
146
- # Then edit .env with your actual keys
147
- ```
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
148
104
 
149
- #### "Requests not being tracked"
105
+ ### **Technical Details**
150
106
 
151
- ```bash
152
- # Enable debug logging to see what's happening
153
- export DEBUG="true"
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
154
111
 
155
- # Check your .env file has correct values
156
- cat .env | grep REVENIUM
112
+ ## API Overview
157
113
 
158
- # Verify initialization is called before making requests
159
- ```
114
+ The middleware provides a Go-aligned API with the following main functions:
160
115
 
161
- #### TypeScript errors with usageMetadata
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)
162
121
 
163
- - Ensure you're importing from `@revenium/perplexity`
164
- - Check that your TypeScript version is 5.0+
165
- - Verify you're using the latest version: `npm update @revenium/perplexity`
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).**
166
123
 
167
- #### Build/Import Errors
124
+ ## Metadata Fields
168
125
 
169
- ```bash
170
- # Clean and reinstall
171
- rm -rf node_modules
172
- npm install
126
+ The middleware supports the following optional metadata fields for tracking:
173
127
 
174
- # For TypeScript projects
175
- npm run build
176
- ```
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) |
177
140
 
178
- ### Debug Mode
141
+ **All metadata fields are optional.** For complete metadata documentation and usage examples, see:
179
142
 
180
- **SECURITY WARNING: Never enable DEBUG mode in production!**
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
181
145
 
182
- Debug mode is intended for local development only. While sensitive fields (PII, credentials) are automatically redacted from debug logs, debug mode should only be enabled in development environments with test data.
146
+ ## Configuration Options
183
147
 
184
- Enable debug logging to troubleshoot issues:
148
+ ### Environment Variables
185
149
 
186
- ```bash
187
- export DEBUG="true"
188
- node your-script.js
189
- ```
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).
190
151
 
191
- This will show:
152
+ ## Examples
192
153
 
193
- - Initialization details
194
- - Configuration loading
195
- - API call information (with PII/credentials redacted)
196
- - Error details
154
+ The package includes comprehensive examples in the [`examples/`](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/) directory.
197
155
 
198
- **Production environments must NEVER set DEBUG=true.**
199
156
 
200
157
  ## Project Structure
201
158
 
@@ -210,22 +167,84 @@ revenium-middleware-perplexity-node/
210
167
  │ ├── utils/ # Utility functions
211
168
  │ └── index.ts # Main entry point
212
169
  ├── examples/ # TypeScript examples
213
- └── dist/
214
- ├── cjs/ # CommonJS build
215
- ├── esm/ # ES Modules build
216
- └── types/ # TypeScript definitions
170
+ ├── .env.example # Example environment variables
171
+ ├── package.json
172
+ ├── tsconfig.json
173
+ └── README.md
217
174
  ```
218
175
 
219
176
  ## How It Works
220
177
 
221
- 1. **Initialization**: When you call `initializePerplexityFromEnv()` and `initializeReveniumFromEnv()`, the middleware sets up configurations
222
- 2. **Request Wrapping**: All Perplexity API calls go through the middleware wrapper
223
- 3. **Usage Extraction**: Token counts, model info, and timing data are captured from responses
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
224
181
  4. **Async Tracking**: Usage data is sent to Revenium in the background (fire-and-forget)
225
182
  5. **Transparent Response**: Original Perplexity responses are returned unchanged
226
183
 
227
184
  The middleware never blocks your application - if Revenium tracking fails, your Perplexity requests continue normally.
228
185
 
186
+ **Supported APIs:**
187
+
188
+ - Chat Completions API (`client.chat().completions().create()`)
189
+ - Streaming API (`client.chat().completions().createStreaming()`)
190
+
191
+ ## Troubleshooting
192
+
193
+ ### Common Issues
194
+
195
+ **No tracking data appears:**
196
+
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
201
+
202
+ **Client not initialized error:**
203
+
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
207
+
208
+ **Perplexity API errors:**
209
+
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
213
+
214
+ ### Debug Mode
215
+
216
+ Enable detailed logging by adding to your `.env`:
217
+
218
+ ```env
219
+ REVENIUM_DEBUG=true
220
+ ```
221
+
222
+ ### Getting Help
223
+
224
+ If issues persist:
225
+
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
230
+
231
+ ## Supported Models
232
+
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).
234
+
235
+ ### API Support Matrix
236
+
237
+ The following table shows what has been tested and verified with working examples:
238
+
239
+ | Feature | Chat Completions | Streaming |
240
+ | --------------------- | ---------------- | --------- |
241
+ | **Basic Usage** | Yes | Yes |
242
+ | **Metadata Tracking** | Yes | Yes |
243
+ | **Token Counting** | Yes | Yes |
244
+
245
+ **Note:** "Yes" = Tested with working examples in [`examples/`](https://github.com/revenium/revenium-middleware-perplexity-node/blob/HEAD/examples/) directory
246
+
247
+
229
248
  ## Requirements
230
249
 
231
250
  - Node.js 20+
package/SECURITY.md ADDED
@@ -0,0 +1,34 @@
1
+ # Security Policy
2
+
3
+ ## Reporting a Vulnerability
4
+
5
+ If you discover a security vulnerability in this package, please report it to us.
6
+
7
+ **DO NOT** create a public GitHub issue for security vulnerabilities.
8
+
9
+ ### How to Report
10
+
11
+ Email: support@revenium.io
12
+
13
+ Please include:
14
+ - Package name and version
15
+ - Description of the vulnerability
16
+ - Steps to reproduce (if applicable)
17
+ - Potential impact
18
+ - Suggested fix (if available)
19
+
20
+ We will review and respond to security reports in a timely manner.
21
+
22
+ ## Security Best Practices
23
+
24
+ When using this middleware:
25
+
26
+ 1. **API Keys**: Never commit API keys to version control
27
+ 2. **Environment Variables**: Use environment variables for sensitive configuration
28
+ 3. **PII Handling**: Ensure no PII is sent to Revenium unless explicitly configured for billing purposes
29
+ 4. **Network Security**: Always use HTTPS connections
30
+ 5. **Updates**: Keep the package updated to the latest version
31
+
32
+ ## Additional Resources
33
+
34
+ - [Revenium Documentation](https://docs.revenium.io)
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ /**
3
+ * Perplexity Model Constants
4
+ *
5
+ * Official model names for Perplexity AI.
6
+ * Use these constants instead of hardcoding model strings.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { PERPLEXITY_MODELS } from "@revenium/perplexity";
11
+ *
12
+ * const response = await client.chat().completions().create({
13
+ * model: PERPLEXITY_MODELS.SONAR_PRO,
14
+ * messages: [{ role: "user", content: "Hello!" }]
15
+ * });
16
+ * ```
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.PERPLEXITY_MODELS = void 0;
20
+ /**
21
+ * Available Perplexity AI models
22
+ * @see https://docs.perplexity.ai/docs/model-cards
23
+ */
24
+ exports.PERPLEXITY_MODELS = {
25
+ /**
26
+ * Sonar Pro - Most capable model for complex queries
27
+ */
28
+ SONAR_PRO: "sonar-pro",
29
+ /**
30
+ * Sonar - Standard model for most use cases
31
+ */
32
+ SONAR: "sonar",
33
+ /**
34
+ * Sonar Reasoning - Specialized for reasoning tasks
35
+ */
36
+ SONAR_REASONING: "sonar-reasoning",
37
+ };
38
+ //# sourceMappingURL=models.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"models.js","sourceRoot":"","sources":["../../../src/constants/models.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH;;;GAGG;AACU,QAAA,iBAAiB,GAAG;IAC/B;;OAEG;IACH,SAAS,EAAE,WAAoB;IAE/B;;OAEG;IACH,KAAK,EAAE,OAAgB;IAEvB;;OAEG;IACH,eAAe,EAAE,iBAA0B;CACnC,CAAC"}
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ /**
3
+ * Client module exports
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Configure = exports.Reset = exports.IsInitialized = exports.GetClient = exports.Initialize = void 0;
7
+ var manager_js_1 = require("./manager.js");
8
+ Object.defineProperty(exports, "Initialize", { enumerable: true, get: function () { return manager_js_1.Initialize; } });
9
+ Object.defineProperty(exports, "GetClient", { enumerable: true, get: function () { return manager_js_1.GetClient; } });
10
+ Object.defineProperty(exports, "IsInitialized", { enumerable: true, get: function () { return manager_js_1.IsInitialized; } });
11
+ Object.defineProperty(exports, "Reset", { enumerable: true, get: function () { return manager_js_1.Reset; } });
12
+ Object.defineProperty(exports, "Configure", { enumerable: true, get: function () { return manager_js_1.Configure; } });
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/core/client/index.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AAEH,2CAAsF;AAA7E,wGAAA,UAAU,OAAA;AAAE,uGAAA,SAAS,OAAA;AAAE,2GAAA,aAAa,OAAA;AAAE,mGAAA,KAAK,OAAA;AAAE,uGAAA,SAAS,OAAA"}
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ /**
3
+ * Client Manager - singleton pattern
4
+ *
5
+ * Provides Initialize/GetClient pattern.
6
+ * Manages singleton instance of ReveniumPerplexity client.
7
+ *
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.Initialize = Initialize;
11
+ exports.Configure = Configure;
12
+ exports.GetClient = GetClient;
13
+ exports.IsInitialized = IsInitialized;
14
+ exports.Reset = Reset;
15
+ const revenium_client_js_1 = require("../middleware/revenium-client.js");
16
+ const manager_js_1 = require("../config/manager.js");
17
+ const validator_js_1 = require("../config/validator.js");
18
+ /**
19
+ * Singleton instance of ReveniumPerplexity client
20
+ */
21
+ let clientInstance = null;
22
+ const logger = (0, manager_js_1.getLogger)();
23
+ /**
24
+ * Initialize Revenium Perplexity client from environment variables
25
+ *
26
+ * Loads configuration from environment:
27
+ * - REVENIUM_METERING_API_KEY (required)
28
+ * - PERPLEXITY_API_KEY (required)
29
+ * @throws {Error} If required environment variables are missing
30
+ */
31
+ function Initialize() {
32
+ logger.debug("Initializing Revenium Perplexity client");
33
+ const config = (0, manager_js_1.initializeConfig)();
34
+ Configure(config);
35
+ logger.debug("Revenium Perplexity client initialized successfully");
36
+ }
37
+ /**
38
+ * Configure Revenium Perplexity client with custom configuration
39
+ *
40
+ * @param config - Configuration object
41
+ * @throws {Error} If required configuration fields are missing
42
+ *
43
+ */
44
+ function Configure(config) {
45
+ logger.debug("Configuring Revenium Perplexity client");
46
+ // Validate configuration (including API key formats)
47
+ (0, validator_js_1.validateConfig)(config);
48
+ const fullConfig = {
49
+ ...config,
50
+ reveniumBaseUrl: config.reveniumBaseUrl || "https://api.revenium.ai",
51
+ perplexityBaseUrl: config.perplexityBaseUrl || "https://api.perplexity.ai",
52
+ debug: config.debug ?? false,
53
+ };
54
+ clientInstance = new revenium_client_js_1.ReveniumPerplexity(fullConfig);
55
+ if (fullConfig.debug) {
56
+ logger.debug("Revenium Perplexity client initialized successfully");
57
+ }
58
+ }
59
+ /**
60
+ * Get the singleton ReveniumPerplexity client instance
61
+ *
62
+ * @returns {ReveniumPerplexity} The client instance
63
+ * @throws {Error} If client has not been initialized
64
+ *
65
+ */
66
+ function GetClient() {
67
+ if (!clientInstance) {
68
+ throw new Error("Revenium Perplexity client not initialized. Call Initialize() or Configure() first.");
69
+ }
70
+ return clientInstance;
71
+ }
72
+ /**
73
+ * Check if client has been initialized
74
+ * @returns {boolean} True if client is initialized
75
+ */
76
+ function IsInitialized() {
77
+ return clientInstance !== null;
78
+ }
79
+ /**
80
+ * Reset the client instance (useful for testing)
81
+ */
82
+ function Reset() {
83
+ clientInstance = null;
84
+ }
85
+ //# sourceMappingURL=manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manager.js","sourceRoot":"","sources":["../../../../src/core/client/manager.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAsBH,gCAOC;AASD,8BAkBC;AASD,8BAOC;AAMD,sCAEC;AAKD,sBAEC;AArFD,yEAAsE;AAEtE,qDAAmE;AACnE,yDAAwD;AAExD;;GAEG;AACH,IAAI,cAAc,GAA8B,IAAI,CAAC;AACrD,MAAM,MAAM,GAAG,IAAA,sBAAS,GAAE,CAAC;AAG3B;;;;;;;GAOG;AACH,SAAgB,UAAU;IACxB,MAAM,CAAC,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAExD,MAAM,MAAM,GAAG,IAAA,6BAAgB,GAAE,CAAC;IAClC,SAAS,CAAC,MAAM,CAAC,CAAC;IAElB,MAAM,CAAC,KAAK,CAAC,qDAAqD,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,SAAS,CAAC,MAAsB;IAC9C,MAAM,CAAC,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAEvD,qDAAqD;IACrD,IAAA,6BAAc,EAAC,MAAM,CAAC,CAAC;IAEvB,MAAM,UAAU,GAAmB;QACjC,GAAG,MAAM;QACT,eAAe,EAAE,MAAM,CAAC,eAAe,IAAI,yBAAyB;QACpE,iBAAiB,EAAE,MAAM,CAAC,iBAAiB,IAAI,2BAA2B;QAC1E,KAAK,EAAE,MAAM,CAAC,KAAK,IAAI,KAAK;KAC7B,CAAC;IAEF,cAAc,GAAG,IAAI,uCAAkB,CAAC,UAAU,CAAC,CAAC;IAEpD,IAAI,UAAU,CAAC,KAAK,EAAE,CAAC;QACrB,MAAM,CAAC,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACtE,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,SAAS;IACvB,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CACb,qFAAqF,CACtF,CAAC;IACJ,CAAC;IACD,OAAO,cAAc,CAAC;AACxB,CAAC;AAED;;;GAGG;AACH,SAAgB,aAAa;IAC3B,OAAO,cAAc,KAAK,IAAI,CAAC;AACjC,CAAC;AAED;;GAEG;AACH,SAAgB,KAAK;IACnB,cAAc,GAAG,IAAI,CAAC;AACxB,CAAC"}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /**
3
+ * Configuration module - Main exports
4
+ *
5
+ * This module provides a clean interface for configuration management.
6
+ * Aligned with OpenAI modular implementation.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.defaultLogger = exports.initializeConfig = exports.getLogger = exports.setConfig = exports.getConfig = exports.validateConfig = exports.loadConfigFromEnv = void 0;
10
+ // Re-export all configuration functionality
11
+ var loader_js_1 = require("./loader.js");
12
+ Object.defineProperty(exports, "loadConfigFromEnv", { enumerable: true, get: function () { return loader_js_1.loadConfigFromEnv; } });
13
+ var validator_js_1 = require("./validator.js");
14
+ Object.defineProperty(exports, "validateConfig", { enumerable: true, get: function () { return validator_js_1.validateConfig; } });
15
+ var manager_js_1 = require("./manager.js");
16
+ Object.defineProperty(exports, "getConfig", { enumerable: true, get: function () { return manager_js_1.getConfig; } });
17
+ Object.defineProperty(exports, "setConfig", { enumerable: true, get: function () { return manager_js_1.setConfig; } });
18
+ Object.defineProperty(exports, "getLogger", { enumerable: true, get: function () { return manager_js_1.getLogger; } });
19
+ Object.defineProperty(exports, "initializeConfig", { enumerable: true, get: function () { return manager_js_1.initializeConfig; } });
20
+ Object.defineProperty(exports, "defaultLogger", { enumerable: true, get: function () { return manager_js_1.defaultLogger; } });
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/core/config/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,4CAA4C;AAC5C,yCAAgD;AAAvC,8GAAA,iBAAiB,OAAA;AAE1B,+CAAgD;AAAvC,8GAAA,cAAc,OAAA;AAEvB,2CAMsB;AALpB,uGAAA,SAAS,OAAA;AACT,uGAAA,SAAS,OAAA;AACT,uGAAA,SAAS,OAAA;AACT,8GAAA,gBAAgB,OAAA;AAChB,2GAAA,aAAa,OAAA"}