npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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.

npm version Node.js Documentation Website License: MIT

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/perplexity

Note: 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 -y

Step 2: Install Dependencies

# Install Revenium middleware
npm install @revenium/perplexity

# For TypeScript projects (optional)
npm install -D typescript tsx @types/node

Step 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 File

Copy 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=false

Replace 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 keys

Run 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 features

Or 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.ts

For 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:


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 Overview

  • Initialize(config?) - Initialize the middleware (from environment or explicit config)
  • GetClient() - Get the global Revenium client instance
  • Configure(config) - Alias for Initialize() for programmatic configuration
  • IsInitialized() - Check if the middleware is initialized
  • Reset() - 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.md

How It Works

  1. Initialize: Call Initialize() to set up the middleware with your configuration
  2. Get Client: Call GetClient() to get a wrapped Perplexity client instance
  3. Make Requests: Use the client normally - all requests are automatically tracked
  4. Async Tracking: Usage data is sent to Revenium in the background (fire-and-forget)
  5. 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:

  1. Verify environment variables are set correctly in .env
  2. Enable debug logging by setting REVENIUM_DEBUG=true in .env
  3. Check console for [Revenium] log messages
  4. Verify your REVENIUM_METERING_API_KEY is valid

Client not initialized error:

  • Make sure you call Initialize() before GetClient()
  • Check that your .env file is in the project root
  • Verify REVENIUM_METERING_API_KEY is set

Perplexity API errors:

  • Verify PERPLEXITY_API_KEY is 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 clean script uses rm -rf which may not work in Windows CMD
  • Use PowerShell or Git Bash instead
  • Or manually delete the dist folder before building
  • Alternatively, install rimraf globally: npm install -g rimraf and update the script to use rimraf dist

Debug Mode

Enable detailed logging by adding to your .env:

REVENIUM_DEBUG=true

Getting Help

If issues persist:

  1. Enable debug logging (REVENIUM_DEBUG=true)
  2. Check the examples/ directory for working examples
  3. Review examples/README.md for detailed setup instructions
  4. 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

See CODE_OF_CONDUCT.md

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:


Built by Revenium