@revenium/perplexity
v2.0.8
Published
NodeJS middleware for Perplexity AI API with Revenium metering
Downloads
122
Readme
Revenium Middleware for Perplexity
A lightweight, production-ready middleware that adds Revenium metering and tracking to Perplexity AI API calls.
Features
- Automatic Metering - Tracks all API calls with detailed usage metrics
- Streaming Support - Full support for streaming responses
- TypeScript First - Built with TypeScript, includes full type definitions
- Multi-Format - Supports both ESM and CommonJS
- Custom Metadata - Add custom tracking metadata to any request
- Production Ready - Battle-tested and optimized for production use
Getting Started
Quick Start
npm install @revenium/perplexityNote: The dotenv package is optional. The middleware automatically loads .env files via Initialize().
For complete setup instructions, TypeScript patterns, and usage examples, see examples/README.md.
Step-by-Step Guide
The following guide walks you through creating a new project from scratch:
Step 1: Create Your Project
# Create project directory
mkdir my-perplexity-project
cd my-perplexity-project
# Initialize npm project
npm init -yStep 2: Install Dependencies
# Install Revenium middleware
npm install @revenium/perplexity
# For TypeScript projects (optional)
npm install -D typescript tsx @types/nodeStep 3: Setup Environment Variables
Create a .env file in your project root:
# Create .env file
echo. > .env # On Windows (CMD)
touch .env # On Mac/Linux
# OR
# PowerShell
New-Item -Path .env -ItemType FileCopy and paste the following into .env:
# Perplexity Configuration
PERPLEXITY_API_KEY=pplx_your_perplexity_api_key
# Revenium Configuration
REVENIUM_METERING_API_KEY=hak_your_revenium_api_key
# Optional: For development/testing (defaults to https://api.revenium.ai)
# REVENIUM_METERING_BASE_URL=https://api.revenium.ai
# Optional: Perplexity API base URL (defaults to https://api.perplexity.ai)
# PERPLEXITY_API_BASE_URL=https://api.perplexity.ai
# Optional: Enable debug logging
# REVENIUM_DEBUG=falseReplace the placeholder values with your actual keys!
For a complete list of all available environment variables, see the Configuration Options section below.
Step 4: Implement in Your Code
Use the examples as reference for implementing the middleware in your project. See examples/README.md for complete implementation examples including:
- How to initialize the middleware with your configuration
- Making API calls with automatic metering
- Handling streaming responses
- Adding custom metadata to track business context
Note for ESM projects: If you get a "Cannot use import statement outside a module" error, make sure your package.json includes "type": "module":
{
"name": "my-perplexity-project",
"version": "1.0.0",
"type": "module",
"dependencies": {
"@revenium/perplexity": "^2.0.0"
}
}Running Examples from Cloned Repository
If you've cloned this repository from GitHub and want to run the included examples to see how the middleware works (without modifying the middleware source code):
Setup
# Install dependencies
npm install
# Build the package
npm run build
# Configure environment variables
cp .env.example .env # On Mac/Linux
copy .env.example .env # On Windows (CMD)
# OR PowerShell
Copy-Item .env.example .env
# Edit .env with your API keysRun Examples
Using npm scripts:
npm run example:getting-started # Getting started example
npm run example:basic # Basic chat completion
npm run example:stream # Streaming response
npm run example:metadata # Custom metadata
npm run example:advanced # Advanced featuresOr use npx tsx directly:
npx tsx examples/getting_started.ts
npx tsx examples/basic.ts
npx tsx examples/stream.ts
npx tsx examples/metadata.ts
npx tsx examples/advanced.tsFor detailed information about each example, see examples/README.md.
Local Development and Contributing
For information on modifying the middleware source code, development workflow, and contributing to the project, see:
- DEVELOPMENT.md - Complete development guide, build system, and testing
- CONTRIBUTING.md - Contribution guidelines and process
What Gets Tracked
The middleware automatically captures comprehensive usage data:
Usage Metrics
- Token Counts - Input tokens, output tokens, total tokens
- Model Information - Model name, provider (Perplexity)
- Request Timing - Request duration, response time
- Cost Calculation - Estimated costs based on current pricing
Business Context (Optional)
- User Tracking - Subscriber ID, email, credentials
- Organization Data - Organization ID, subscription ID, product ID
- Task Classification - Task type, agent identifier, trace ID
- Quality Metrics - Response quality scores, task identifiers
Technical Details
- API Endpoints - Chat completions
- Request Types - Streaming vs non-streaming
- Error Tracking - Failed requests, error types, retry attempts
- Environment Info - Development vs production usage
Metadata Fields
The following table shows all fields this middleware sends to the Revenium API:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| Core Fields | | | |
| model | string | Yes | Perplexity model name (e.g., "sonar-pro") |
| provider | string | Yes | Always "Perplexity" |
| inputTokenCount | integer | Yes | Number of input tokens consumed |
| outputTokenCount | integer | Yes | Number of output tokens generated |
| totalTokenCount | integer | Yes | Total tokens (input + output) |
| requestDuration | integer | Yes | Request duration in milliseconds |
| Timing | | | |
| requestTime | string | Auto | ISO 8601 timestamp when request started |
| responseTime | string | Auto | ISO 8601 timestamp when response completed |
| completionStartTime | string | Auto | ISO 8601 timestamp when completion started |
| timeToFirstToken | integer | Streaming | Time to first token in ms (streaming only) |
| Request Details | | | |
| transactionId | string | Auto | Unique transaction identifier |
| operationType | string | Auto | Always "CHAT" for chat completions |
| stopReason | string | Auto | Completion finish reason ("END", "STOP", etc.) |
| isStreamed | boolean | Auto | Whether response was streamed |
| costType | string | Auto | Always "AI" |
| modelSource | string | Auto | Always "PERPLEXITY" |
| middlewareSource | string | Auto | Always "revenium-perplexity-node" |
| Cost Information | | | |
| inputTokenCost | number | Optional | Cost for input tokens (if provided by Perplexity) |
| outputTokenCost | number | Optional | Cost for output tokens (if provided by Perplexity) |
| totalCost | number | Optional | Total cost (if provided by Perplexity) |
| Business Context | | | |
| organizationId | string | Optional | Your organization identifier |
| productId | string | Optional | Your product identifier |
| subscriptionId | string | Optional | Your subscription identifier |
| taskType | string | Optional | Type of AI task (e.g., "chat", "research") |
| traceId | string | Optional | Session or conversation tracking ID |
| agent | string | Optional | AI agent or bot identifier |
| responseQualityScore | number | Optional | Custom quality rating (0.0-1.0) |
| subscriber.id | string | Optional | User identifier |
| subscriber.email | string | Optional | User email address |
| subscriber.credential | object | Optional | Authentication credential (name, value) |
Notes:
- Required fields are always sent with every request
- Auto fields are automatically populated by the middleware
- Optional fields are only sent if you provide them via
usageMetadata - Streaming fields are only sent for streaming requests
Reference:
- API Reference - Complete metadata field documentation
API Overview
Initialize(config?)- Initialize the middleware (from environment or explicit config)GetClient()- Get the global Revenium client instanceConfigure(config)- Alias forInitialize()for programmatic configurationIsInitialized()- Check if the middleware is initializedReset()- Reset the global client (useful for testing)
For complete API documentation and usage examples, see examples/README.md.
Configuration Options
Environment Variables
For a complete list of all available environment variables with examples, see .env.example.
Examples
The package includes comprehensive examples in the examples/ directory.
Project Structure
revenium-middleware-perplexity-node/
├── src/
│ ├── core/
│ │ ├── client/ # Client manager (Initialize/GetClient)
│ │ ├── config/ # Configuration management
│ │ ├── middleware/ # Perplexity API middleware wrapper
│ │ ├── providers/ # Provider detection
│ │ └── tracking/ # Metering and tracking
│ ├── types/ # TypeScript type definitions
│ ├── utils/ # Utility functions
│ └── index.ts # Main entry point
├── examples/ # TypeScript examples
├── package.json
├── tsconfig.json
└── README.mdHow It Works
- Initialize: Call
Initialize()to set up the middleware with your configuration - Get Client: Call
GetClient()to get a wrapped Perplexity client instance - Make Requests: Use the client normally - all requests are automatically tracked
- Async Tracking: Usage data is sent to Revenium in the background (fire-and-forget)
- Transparent Response: Original Perplexity responses are returned unchanged
The middleware never blocks your application - if Revenium tracking fails, your Perplexity requests continue normally.
Supported APIs:
- Chat Completions API (
client.chat().completions().create()) - Streaming API (
client.chat().completions().createStreaming())
Troubleshooting
Common Issues
No tracking data appears:
- Verify environment variables are set correctly in
.env - Enable debug logging by setting
REVENIUM_DEBUG=truein.env - Check console for
[Revenium]log messages - Verify your
REVENIUM_METERING_API_KEYis valid
Client not initialized error:
- Make sure you call
Initialize()beforeGetClient() - Check that your
.envfile is in the project root - Verify
REVENIUM_METERING_API_KEYis set
Perplexity API errors:
- Verify
PERPLEXITY_API_KEYis set correctly - Check that your API key starts with
pplx- - Ensure you're using a valid model name
Windows-specific issues:
If you're developing on Windows and encounter build errors with npm run clean:
- The
cleanscript usesrm -rfwhich may not work in Windows CMD - Use PowerShell or Git Bash instead
- Or manually delete the
distfolder before building - Alternatively, install
rimrafglobally:npm install -g rimrafand update the script to userimraf dist
Debug Mode
Enable detailed logging by adding to your .env:
REVENIUM_DEBUG=trueGetting Help
If issues persist:
- Enable debug logging (
REVENIUM_DEBUG=true) - Check the
examples/directory for working examples - Review
examples/README.mdfor detailed setup instructions - Contact [email protected] with debug logs
Supported Models
This middleware works with any Perplexity model. For the complete model list, see the Perplexity Models Documentation.
API Support Matrix
The following table shows what has been tested and verified with working examples:
| Feature | Chat Completions | Streaming | | --------------------- | ---------------- | --------- | | Basic Usage | Yes | Yes | | Metadata Tracking | Yes | Yes | | Token Counting | Yes | Yes |
Note: "Yes" = Tested with working examples in examples/ directory
Requirements
- Node.js 20+
- TypeScript 5.0+ (for TypeScript projects)
- Revenium API key
- Perplexity API key
Documentation
For detailed documentation, visit docs.revenium.io
Contributing
See CONTRIBUTING.md
Code of Conduct
Security
See SECURITY.md
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For issues, feature requests, or contributions:
- GitHub Repository: revenium/revenium-middleware-perplexity-node
- Issues: Report bugs or request features
- Documentation: docs.revenium.io
- Contact: Reach out to the Revenium team for additional support
Built by Revenium
