@revenium/perplexity
Version:
NodeJS middleware for perplexity's AI API
522 lines (392 loc) ⢠13.5 kB
Markdown
# Revenium Middleware for Perplexity AI (Node.js)
[](https://badge.fury.io/js/%40revenium%2Fperplexity)
[](https://www.npmjs.com/package/@revenium/perplexity)
[](https://docs.revenium.io)
[](https://opensource.org/licenses/MIT)
Automatically track and meter your Perplexity AI API usage with Revenium. This middleware provides seamless integration with Perplexity AI SDK, requiring minimal code changes.
## š Getting Started
You have 3 options to start using Revenium middleware for Perplexity AI:
| Option | Description | Best For |
| ----------------------------------------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| **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) |
| **Option 2: Clone Our Repository** | Quick testing with pre-built examples and playground scripts. | š [Go to Clone Guide](#option-2-clone-repository) |
| **Option 3: Add to Existing Project** | Already have a project? Just install and replace imports. | š [Go to Quick Integration](#option-3-existing-project-integration) |
## Option 1: Create Project from Scratch
### Step 1: Create Project Directory
```bash
# Create and navigate to your project
mkdir my-perplexity-ai-project
cd my-perplexity-ai-project
# Initialize Node.js project
npm init -y
```
### Step 2: Install Dependencies
```bash
npm install @revenium/perplexity
```
### Step 3: Setup Environment Variables
Create a `.env` file in your project root:
```bash
# Create .env file
echo. > .env # On Windows (CMD TERMINAL)
touch .env # On Mac/Linux (CMD TERMINAL)
# OR
#PowerShell
New-Item -Path .env -ItemType File
```
Copy and paste the following into `.env`:
```bash
# Perplexity AI Configuration
PERPLEXITY_API_KEY="your_perplexity_api_key_here"
# Revenium Configuration
REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
```
### Step 4: Create Your First Test
Create `test-perplexity.js`:
```javascript
// test-perplexity.js
import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
const basicExample = async () => {
try {
const middleware = new PerplexityReveniumMiddleware();
const model = middleware.getGenerativeModel("sonar-pro");
const result = await model.createChatCompletion({
messages: [
{
role: "user",
content: "What is the universe?",
},
],
});
const text = result.choices[0]?.message?.content;
console.log("*** RESPONSE ***");
console.log(text);
console.log("ā
Basic Perplexity AI example successful!");
} catch (error) {
console.error("ā Perplexity basic example failed:", error);
process.exit(1);
}
};
basicExample();
```
### Step 5: Update package.json
Add test scripts and module type to your `package.json`:
```json
{
"name": "my-perplexity-ai-project",
"version": "1.0.0",
"type": "module",
"scripts": {
"test-perplexity": "node test-perplexity.js"
},
"dependencies": {
"@revenium/perplexity": "^1.0.0"
}
}
```
ā ļø **Important**: If you get this error when running tests:
```
SyntaxError: Cannot use import statement outside a module
```
Make sure your `package.json` includes `"type": "module"` as shown below.
```json
{
"type": "module"
}
```
### Step 6: Run Your Tests
```bash
# Test Perplexity AI SDK
npm run test-perplexity
```
### Step 7: Create Advanced Examples
Create an examples directory and add these files:
```bash
mkdir examples
```
#### Streaming Example
Create `examples/streaming-perplexity.js`:
```javascript
// examples/streaming-perplexity.js
import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
const streamingExample = async () => {
try {
const middleware = new PerplexityReveniumMiddleware();
const model = middleware.getGenerativeModel("sonar-pro");
const stream = await model.createChatCompletionStream({
messages: [
{
role: "user",
content: "What is artificial intelligence?",
},
],
});
console.log("*** STREAMING RESPONSE ***");
let fullText = "";
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) {
process.stdout.write(content);
fullText += content;
}
}
console.log("\nā
Streaming with metering successful!");
console.log(`š Total response length: ${fullText.length} characters`);
} catch (error) {
console.error("ā Perplexity streaming example failed:", error);
process.exit(1);
}
};
streamingExample();
```
#### METADATA Example
Create `examples/metadata-perplexity.js`:
```javascript
// examples/metadata-perplexity.js
import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
const metadataExample = async () => {
try {
const middleware = new PerplexityReveniumMiddleware();
const model = middleware.getGenerativeModel("sonar-pro");
const result = await model.createChatCompletion({
model: "sonar-pro",
messages: [{ role: "user", content: "What is the capital of France?" }],
usageMetadata: {
taskType: "test",
subscriberEmail: "test@revenium.ai",
subscriberId: "123456",
subscriberCredentialName: "apiKey",
subscriberCredential: "keyValue",
organizationId: "123456",
subscriptionId: "123456",
productId: "free-trial",
agent: "perplexity",
responseQualityScore: 100,
transactionId: "123456",
timeToFirstToken: 1000,
requestTime: new Date(),
completionStartTime: new Date(),
operationType: "CHAT",
inputTokenCount: 10,
outputTokenCount: 10,
reasoningTokenCount: 20,
cacheCreationTokenCount: 0,
cacheReadTokenCount: 0,
totalTokenCount: 40,
responseTime: new Date(),
requestDuration: 1000,
stopReason: "END",
},
});
console.log("[BASIC REQUEST]", result.choices[0].message);
} catch (error) {
console.error("ā Perplexity streaming example failed:", error);
process.exit(1);
}
};
metadataExample();
```
### Step 8: Update package.json
```json
{
"name": "my-perplexity-ai-project",
"version": "1.0.0",
"type": "module",
"scripts": {
"test-perplexity": "node test-perplexity.js",
"test-perplexity-stream": "node examples/streaming-perplexity.js",
"test-perplexity-metadata": "node examples/metadata-perplexity.js"
},
"dependencies": {
"@revenium/perplexity": "^1.0.0"
}
}
```
### Step 9: Test Advanced Examples
```bash
# Test streaming
npm run test-perplexity-stream
# Test metadata
npm run test-perplexity-metadata
```
## Option 2: Clone Repository
Perfect for testing with pre-built examples:
```bash
# Clone the repository
git clone git@github.com:revenium/revenium-middleware-perplexity-node.git
cd revenium-middleware-perplexity-node
# Install dependencies
npm install
npm install @revenium/perplexity
# Create your .env file
cp .env.example .env
# Edit .env with your API keys
```
### Configure Environment Variables
Edit your `.env` file:
```bash
# For Perplexity AI SDK
PERPLEXITY_API_KEY="your_perplexity_api_key_here"
REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
```
### Run Perplexity AI Examples
```bash
# Perplexity AI examples
## Change type to commonjs in package.json
"type": "commonjs",
# Then run any of the following
npm run e-basic # Basic chat completion
npm run e-streaming # Streaming response
npm run e-enhanced # Enhanced request
npm run e-chat-completions # Chat completions
npm run e-metadata # Metadata request
# Playground examples
# Required build first
npm run build
## Change type to module in package.json
"type": "module",
# Then run any of the following
npm run p-basic
npm run p-streaming
npm run p-enhanced
npm run p-metadata
```
## Option 3: Existing Project Integration
Already have a project? Just install and replace imports:
### Step 1. Install the Package
```bash
npm install @revenium/perplexity
```
### Step 2. Add Environment Variables
Add to your existing `.env` file:
```bash
PERPLEXITY_API_KEY="your_perplexity_api_key_here"
REVENIUM_METERING_API_KEY="your_revenium_api_key_here"
REVENIUM_METERING_BASE_URL="https://api.revenium.io/meter"
```
### Step 3. Replace Your Imports
**Before:**
```javascript
import { OpenAI } from "openai";
```
**After:**
```javascript
import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
```
### Step 4. Update Your Code
#### Revenium Client Example
```javascript
import { PerplexityReveniumMiddleware } from "@revenium/perplexity";
// Initialize (API key from environment variable)
const middleware = new PerplexityReveniumMiddleware();
const model = middleware.getGenerativeModel("sonar-pro");
const result = await model.createChatCompletion({
messages: [
{
role: "user",
content: "Hello world",
},
],
});
console.log("[BASIC EXAMPLE]", result.choices[0].message.content);
```
## š§ Advanced Usage
### Streaming Responses
#### Revenium Client Streaming
```javascript
const stream = await model.createChatCompletionStream({
messages: [
{
role: "user",
content: "Hello world",
},
],
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
```
## š What Gets Tracked
- **Token Usage**: Input and output tokens for accurate billing
- **Request Duration**: Total time for each API call
- **Model Information**: Which model was used
- **Operation Type**: Chat completion, streaming
- **Error Tracking**: Failed requests and error details
- **Streaming Metrics**: Time to first token for streaming responses
- **Custom Metadata**: Rich business context and user tracking
## š Supported Models
### Chat Models
- **sonar-pro** (Latest and most capable)
- **sonar-small** (Fast and efficient)
- **sonar-medium** (Balanced performance)
_Note: Model availability depends on your Perplexity AI account and API access level._
## š ļø Configuration Options
### Environment Variables
| Variable | Required | Description |
| ---------------------------- | -------- | ---------------------------------------------------------- |
| `PERPLEXITY_API_KEY` | ā
| Your Perplexity API key |
| `REVENIUM_METERING_API_KEY` | ā
| Your Revenium API key |
| `REVENIUM_METERING_BASE_URL` | ā | Revenium base URL (default: https://api.revenium.io/meter) |
## šØ Troubleshooting
### Common Issues
**"Missing API Key" Error**
```bash
export PERPLEXITY_API_KEY="your-actual-api-key"
echo $PERPLEXITY_API_KEY # Verify it's set
```
**"Requests not being tracked"**
```bash
export REVENIUM_METERING_API_KEY="your-actual-revenium-key"
```
**Module Import Errors**
```json
{
"type": "module"
}
```
```json
{
"type": "commonjs"
}
```
This will show:
- Request/response details
- Token counting information
- Metering data being sent
- Error details
- Middleware activation status
## š Examples Repository
Check out our comprehensive examples:
- **Basic Usage**: Simple chat completions
- **Streaming**: Real-time response streaming
- **Metadata**: Rich tracking examples
- **Error Handling**: Robust error management
- **Advanced Patterns**: Complex use cases
- **Configuration**: Different setup options
All examples are in the `/examples` and `/playground` directories.
## š Requirements
- Node.js 18+
- Perplexity API key
- Revenium API key
## š License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## š¤ Support
- š [Documentation](https://docs.revenium.com)
- š¬ [Community Support](https://community.revenium.com)
- š§ [Email Support](mailto:support@revenium.com)
- š [Report Issues](https://github.com/revenium/revenium-middleware-perplexity-node/issues)
**Built with ā¤ļø by Revenium**