@revenium/perplexity 2.0.2 → 2.0.3
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.
- package/CHANGELOG.md +60 -0
- package/LICENSE +21 -21
- package/README.md +866 -625
- package/examples/README.md +323 -0
- package/examples/basic.ts +55 -0
- package/examples/chat.ts +87 -0
- package/examples/metadata.ts +72 -0
- package/examples/streaming.ts +61 -0
- package/package.json +76 -69
- package/dist/cjs/core/config/perplexity-config.js.map +0 -1
- package/dist/cjs/core/config/revenium-config.js.map +0 -1
- package/dist/cjs/core/tracking/metering.js.map +0 -1
- package/dist/cjs/core/wrapper/perplexity-client.js.map +0 -1
- package/dist/cjs/index.js.map +0 -1
- package/dist/cjs/types/index.js.map +0 -1
- package/dist/cjs/utils/logger.js.map +0 -1
- package/dist/esm/core/config/perplexity-config.js.map +0 -1
- package/dist/esm/core/config/revenium-config.js.map +0 -1
- package/dist/esm/core/tracking/metering.js.map +0 -1
- package/dist/esm/core/wrapper/perplexity-client.js.map +0 -1
- package/dist/esm/index.js.map +0 -1
- package/dist/esm/types/index.js.map +0 -1
- package/dist/esm/utils/logger.js.map +0 -1
- package/dist/types/core/config/perplexity-config.d.ts.map +0 -1
- package/dist/types/core/config/revenium-config.d.ts.map +0 -1
- package/dist/types/core/tracking/metering.d.ts.map +0 -1
- package/dist/types/core/wrapper/perplexity-client.d.ts.map +0 -1
- package/dist/types/index.d.ts.map +0 -1
- package/dist/types/types/index.d.ts.map +0 -1
- package/dist/types/utils/logger.d.ts.map +0 -1
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
# Revenium Perplexity AI Middleware Examples
|
|
2
|
+
|
|
3
|
+
Comprehensive examples demonstrating how to use the @revenium/perplexity middleware with automatic usage tracking and metering.
|
|
4
|
+
|
|
5
|
+
## TypeScript-First Approach
|
|
6
|
+
|
|
7
|
+
These examples are written in TypeScript to showcase type-safe development patterns. You can use them in both TypeScript and JavaScript projects:
|
|
8
|
+
|
|
9
|
+
- **TypeScript projects**: Run examples directly with `tsx` or `ts-node`
|
|
10
|
+
- **JavaScript projects**: See playground/ directory for JavaScript versions
|
|
11
|
+
|
|
12
|
+
**For npm users:** These examples are included in your `node_modules/@revenium/perplexity/examples/` directory after installation.
|
|
13
|
+
|
|
14
|
+
**For GitHub users:** Clone the repository to run examples directly with the included npm scripts.
|
|
15
|
+
|
|
16
|
+
## Quick Start
|
|
17
|
+
|
|
18
|
+
### 1. Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install @revenium/perplexity dotenv
|
|
22
|
+
npm install --save-dev tsx # For TypeScript projects
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### 2. Environment Setup
|
|
26
|
+
|
|
27
|
+
Create a `.env` file in your project root:
|
|
28
|
+
|
|
29
|
+
```env
|
|
30
|
+
# Required: Your Perplexity API key
|
|
31
|
+
PERPLEXITY_API_KEY=pplx_your_perplexity_key
|
|
32
|
+
|
|
33
|
+
# Required: Revenium metering API key
|
|
34
|
+
REVENIUM_METERING_API_KEY=hak_your_revenium_key
|
|
35
|
+
REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter/v2
|
|
36
|
+
|
|
37
|
+
# Optional: Perplexity base URL (defaults to https://api.perplexity.ai)
|
|
38
|
+
PERPLEXITY_API_BASE_URL=https://api.perplexity.ai
|
|
39
|
+
|
|
40
|
+
# Optional: Enable debug logging
|
|
41
|
+
DEBUG=true
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### 3. Run Examples
|
|
45
|
+
|
|
46
|
+
From the repository:
|
|
47
|
+
```bash
|
|
48
|
+
npm run example:basic # Basic chat completion
|
|
49
|
+
npm run example:streaming # Streaming responses
|
|
50
|
+
npm run example:chat # Multi-turn conversations
|
|
51
|
+
npm run example:metadata # Custom usage metadata
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Or run all examples:
|
|
55
|
+
```bash
|
|
56
|
+
npm test
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Getting Started - Step by Step
|
|
60
|
+
|
|
61
|
+
### Step 1: Create Your First Test
|
|
62
|
+
|
|
63
|
+
**TypeScript:**
|
|
64
|
+
```typescript
|
|
65
|
+
// test-perplexity.ts
|
|
66
|
+
import { config } from "dotenv";
|
|
67
|
+
import {
|
|
68
|
+
initializeReveniumFromEnv,
|
|
69
|
+
initializePerplexityFromEnv,
|
|
70
|
+
createChatCompletion,
|
|
71
|
+
} from "@revenium/perplexity";
|
|
72
|
+
|
|
73
|
+
config(); // Load .env file
|
|
74
|
+
|
|
75
|
+
async function test() {
|
|
76
|
+
// Initialize configurations
|
|
77
|
+
initializeReveniumFromEnv();
|
|
78
|
+
initializePerplexityFromEnv();
|
|
79
|
+
|
|
80
|
+
// Create chat completion
|
|
81
|
+
const result = await createChatCompletion({
|
|
82
|
+
messages: [{ role: "user", content: "Hello!" }],
|
|
83
|
+
model: "sonar-pro",
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
console.log(result.choices[0].message.content);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
test();
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
**JavaScript (CommonJS):**
|
|
93
|
+
```javascript
|
|
94
|
+
// test-perplexity.js
|
|
95
|
+
require("dotenv").config();
|
|
96
|
+
const {
|
|
97
|
+
initializeReveniumFromEnv,
|
|
98
|
+
initializePerplexityFromEnv,
|
|
99
|
+
createChatCompletion
|
|
100
|
+
} = require("@revenium/perplexity");
|
|
101
|
+
|
|
102
|
+
async function test() {
|
|
103
|
+
initializeReveniumFromEnv();
|
|
104
|
+
initializePerplexityFromEnv();
|
|
105
|
+
|
|
106
|
+
const result = await createChatCompletion({
|
|
107
|
+
messages: [{ role: "user", content: "Hello!" }],
|
|
108
|
+
model: "sonar-pro",
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
console.log(result.choices[0].message.content);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
test();
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Step 2: Update package.json
|
|
118
|
+
|
|
119
|
+
Add scripts to run your tests:
|
|
120
|
+
|
|
121
|
+
```json
|
|
122
|
+
{
|
|
123
|
+
"scripts": {
|
|
124
|
+
"test:perplexity": "tsx test-perplexity.ts"
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Or for JavaScript:
|
|
130
|
+
```json
|
|
131
|
+
{
|
|
132
|
+
"scripts": {
|
|
133
|
+
"test:perplexity": "node test-perplexity.js"
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Step 3: Run Your Tests
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
npm run test:perplexity
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Step 4: Explore Advanced Features
|
|
145
|
+
|
|
146
|
+
Once basic integration works, explore the included examples:
|
|
147
|
+
- `basic.ts` - Simple chat completions
|
|
148
|
+
- `streaming.ts` - Real-time streaming responses
|
|
149
|
+
- `chat.ts` - Multi-turn conversations with context
|
|
150
|
+
- `metadata.ts` - Custom usage tracking and analytics
|
|
151
|
+
|
|
152
|
+
### Step 5: Project Structure
|
|
153
|
+
|
|
154
|
+
Recommended structure for your Perplexity AI project:
|
|
155
|
+
|
|
156
|
+
```
|
|
157
|
+
your-project/
|
|
158
|
+
├── .env # Your API keys (DON'T COMMIT!)
|
|
159
|
+
├── .env.example # Template for others
|
|
160
|
+
├── .gitignore # Include .env
|
|
161
|
+
├── package.json
|
|
162
|
+
├── src/
|
|
163
|
+
│ ├── perplexity/
|
|
164
|
+
│ │ ├── client.ts # Perplexity client setup
|
|
165
|
+
│ │ └── prompts.ts # Your prompts
|
|
166
|
+
│ └── index.ts
|
|
167
|
+
└── tests/
|
|
168
|
+
└── perplexity.test.ts
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Available Examples
|
|
172
|
+
|
|
173
|
+
### basic.ts - Start Here
|
|
174
|
+
|
|
175
|
+
Simple chat completion with automatic usage tracking.
|
|
176
|
+
|
|
177
|
+
**Features:**
|
|
178
|
+
- Basic configuration initialization
|
|
179
|
+
- Simple chat completion request
|
|
180
|
+
- Automatic metering to Revenium
|
|
181
|
+
|
|
182
|
+
**Run:**
|
|
183
|
+
```bash
|
|
184
|
+
npm run example:basic
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### streaming.ts
|
|
188
|
+
|
|
189
|
+
Real-time streaming responses with usage tracking.
|
|
190
|
+
|
|
191
|
+
**Features:**
|
|
192
|
+
- Streaming chat completions
|
|
193
|
+
- Real-time content delivery
|
|
194
|
+
- Automatic tracking when stream completes
|
|
195
|
+
|
|
196
|
+
**Run:**
|
|
197
|
+
```bash
|
|
198
|
+
npm run example:streaming
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### chat.ts
|
|
202
|
+
|
|
203
|
+
Multi-turn conversations with context.
|
|
204
|
+
|
|
205
|
+
**Features:**
|
|
206
|
+
- Conversation history management
|
|
207
|
+
- Context-aware responses
|
|
208
|
+
- Multi-message interactions
|
|
209
|
+
|
|
210
|
+
**Run:**
|
|
211
|
+
```bash
|
|
212
|
+
npm run example:chat
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
### metadata.ts
|
|
216
|
+
|
|
217
|
+
Custom usage metadata for advanced tracking.
|
|
218
|
+
|
|
219
|
+
**Features:**
|
|
220
|
+
- Custom subscriber information
|
|
221
|
+
- Organization and product tracking
|
|
222
|
+
- Quality scoring
|
|
223
|
+
- Business analytics integration
|
|
224
|
+
|
|
225
|
+
**Run:**
|
|
226
|
+
```bash
|
|
227
|
+
npm run example:metadata
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
## TypeScript Integration Patterns
|
|
231
|
+
|
|
232
|
+
### Pattern A: Direct Import (Recommended)
|
|
233
|
+
|
|
234
|
+
```typescript
|
|
235
|
+
import {
|
|
236
|
+
initializeReveniumFromEnv,
|
|
237
|
+
initializePerplexityFromEnv,
|
|
238
|
+
createChatCompletion
|
|
239
|
+
} from "@revenium/perplexity";
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### Pattern B: Manual Configuration
|
|
243
|
+
|
|
244
|
+
```typescript
|
|
245
|
+
import {
|
|
246
|
+
initializeRevenium,
|
|
247
|
+
initializePerplexity,
|
|
248
|
+
createChatCompletion
|
|
249
|
+
} from "@revenium/perplexity";
|
|
250
|
+
|
|
251
|
+
// Manual configuration
|
|
252
|
+
initializeRevenium({
|
|
253
|
+
apiKey: process.env.REVENIUM_METERING_API_KEY!,
|
|
254
|
+
baseUrl: "https://api.revenium.io/meter/v2"
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
initializePerplexity({
|
|
258
|
+
apiKey: process.env.PERPLEXITY_API_KEY!
|
|
259
|
+
});
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
### Pattern C: With Custom Metadata
|
|
263
|
+
|
|
264
|
+
```typescript
|
|
265
|
+
const result = await createChatCompletion({
|
|
266
|
+
messages: [{ role: "user", content: "Hello" }],
|
|
267
|
+
model: "sonar-pro",
|
|
268
|
+
usageMetadata: {
|
|
269
|
+
subscriberId: "user-123",
|
|
270
|
+
subscriberEmail: "user@example.com",
|
|
271
|
+
organizationId: "acme-corp",
|
|
272
|
+
productId: "chat-app"
|
|
273
|
+
}
|
|
274
|
+
});
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
## Troubleshooting
|
|
278
|
+
|
|
279
|
+
### Common Issues
|
|
280
|
+
|
|
281
|
+
1. **Module not found**: Ensure you've run `npm install @revenium/perplexity`
|
|
282
|
+
2. **Environment variables not loading**: Verify your `.env` file exists and `dotenv` is configured
|
|
283
|
+
3. **API key errors**: Check both Perplexity and Revenium API keys are valid
|
|
284
|
+
4. **TypeScript errors**: Ensure you have `tsx` or `ts-node` installed for TypeScript projects
|
|
285
|
+
|
|
286
|
+
### Debug Mode
|
|
287
|
+
|
|
288
|
+
Enable debug logging to troubleshoot issues:
|
|
289
|
+
|
|
290
|
+
```bash
|
|
291
|
+
DEBUG=true npm run example:basic
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
### Expected Output
|
|
295
|
+
|
|
296
|
+
When running examples successfully:
|
|
297
|
+
```
|
|
298
|
+
Basic Chat Completion Example
|
|
299
|
+
|
|
300
|
+
Initializing configurations...
|
|
301
|
+
Configurations initialized
|
|
302
|
+
|
|
303
|
+
Creating chat completion...
|
|
304
|
+
Chat completion created
|
|
305
|
+
|
|
306
|
+
Response: [AI response here]
|
|
307
|
+
Usage: { prompt_tokens: X, completion_tokens: Y, total_tokens: Z }
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
## JavaScript Playground
|
|
311
|
+
|
|
312
|
+
For JavaScript users, see the `playground/` directory for CommonJS versions of all examples:
|
|
313
|
+
|
|
314
|
+
- `playground/basic.js`
|
|
315
|
+
- `playground/streaming.js`
|
|
316
|
+
- `playground/chat.js`
|
|
317
|
+
- `playground/metadata.js`
|
|
318
|
+
|
|
319
|
+
## Support
|
|
320
|
+
|
|
321
|
+
- Documentation: https://docs.revenium.io
|
|
322
|
+
- GitHub Issues: https://github.com/revenium/revenium-middleware-perplexity-node/issues
|
|
323
|
+
- Email: support@revenium.io
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Basic Chat Completion Example
|
|
3
|
+
*
|
|
4
|
+
* This example demonstrates how to use the Perplexity middleware
|
|
5
|
+
* to create a simple chat completion with Revenium metering.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
initializeReveniumFromEnv,
|
|
10
|
+
initializePerplexityFromEnv,
|
|
11
|
+
createChatCompletion,
|
|
12
|
+
PERPLEXITY_MODELS,
|
|
13
|
+
} from "../src";
|
|
14
|
+
|
|
15
|
+
async function main() {
|
|
16
|
+
console.log("Basic Chat Completion Example\n");
|
|
17
|
+
|
|
18
|
+
// Initialize configurations from environment variables
|
|
19
|
+
console.log("Initializing configurations...");
|
|
20
|
+
initializeReveniumFromEnv();
|
|
21
|
+
initializePerplexityFromEnv();
|
|
22
|
+
console.log("Configurations initialized\n");
|
|
23
|
+
|
|
24
|
+
// Create a simple chat completion
|
|
25
|
+
console.log("Creating chat completion...");
|
|
26
|
+
const result = await createChatCompletion({
|
|
27
|
+
messages: [
|
|
28
|
+
{
|
|
29
|
+
role: "user",
|
|
30
|
+
content: "What is the capital of France? Answer in one sentence.",
|
|
31
|
+
},
|
|
32
|
+
],
|
|
33
|
+
model: PERPLEXITY_MODELS.SONAR_PRO,
|
|
34
|
+
maxTokens: 100,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
console.log("\nResponse:");
|
|
38
|
+
console.log("─────────────────────────────────────────");
|
|
39
|
+
console.log(`Content: ${result.content}`);
|
|
40
|
+
console.log(`Model: ${result.model}`);
|
|
41
|
+
console.log(`Transaction ID: ${result.transactionId}`);
|
|
42
|
+
console.log(`\nToken Usage:`);
|
|
43
|
+
console.log(` - Prompt Tokens: ${result.usage.promptTokens}`);
|
|
44
|
+
console.log(` - Completion Tokens: ${result.usage.completionTokens}`);
|
|
45
|
+
console.log(` - Total Tokens: ${result.usage.totalTokens}`);
|
|
46
|
+
console.log("─────────────────────────────────────────\n");
|
|
47
|
+
|
|
48
|
+
console.log("Example completed successfully!");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
main().catch((error) => {
|
|
52
|
+
console.error("Error:", error.message);
|
|
53
|
+
process.exit(1);
|
|
54
|
+
});
|
|
55
|
+
|
package/examples/chat.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-turn Chat Example
|
|
3
|
+
*
|
|
4
|
+
* This example demonstrates how to have a multi-turn conversation
|
|
5
|
+
* with the Perplexity middleware.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
initializeReveniumFromEnv,
|
|
10
|
+
initializePerplexityFromEnv,
|
|
11
|
+
createChatCompletion,
|
|
12
|
+
PERPLEXITY_MODELS,
|
|
13
|
+
type PerplexityMessage,
|
|
14
|
+
} from "../src";
|
|
15
|
+
|
|
16
|
+
async function main() {
|
|
17
|
+
console.log("Multi-turn Chat Example\n");
|
|
18
|
+
|
|
19
|
+
// Initialize configurations from environment variables
|
|
20
|
+
console.log("Initializing configurations...");
|
|
21
|
+
initializeReveniumFromEnv();
|
|
22
|
+
initializePerplexityFromEnv();
|
|
23
|
+
console.log("Configurations initialized\n");
|
|
24
|
+
|
|
25
|
+
// Start a conversation
|
|
26
|
+
const messages: PerplexityMessage[] = [
|
|
27
|
+
{
|
|
28
|
+
role: "system",
|
|
29
|
+
content: "You are a helpful assistant that provides concise answers.",
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
role: "user",
|
|
33
|
+
content: "What is the capital of France?",
|
|
34
|
+
},
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
console.log("Turn 1:");
|
|
38
|
+
console.log("User: What is the capital of France?");
|
|
39
|
+
|
|
40
|
+
const response1 = await createChatCompletion({
|
|
41
|
+
messages,
|
|
42
|
+
model: PERPLEXITY_MODELS.SONAR_PRO,
|
|
43
|
+
maxTokens: 100,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
console.log(`Assistant: ${response1.content}\n`);
|
|
47
|
+
|
|
48
|
+
// Continue the conversation
|
|
49
|
+
messages.push({
|
|
50
|
+
role: "assistant",
|
|
51
|
+
content: response1.content,
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
messages.push({
|
|
55
|
+
role: "user",
|
|
56
|
+
content: "What is its population?",
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
console.log("Turn 2:");
|
|
60
|
+
console.log("User: What is its population?");
|
|
61
|
+
|
|
62
|
+
const response2 = await createChatCompletion({
|
|
63
|
+
messages,
|
|
64
|
+
model: PERPLEXITY_MODELS.SONAR_PRO,
|
|
65
|
+
maxTokens: 100,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
console.log(`Assistant: ${response2.content}\n`);
|
|
69
|
+
|
|
70
|
+
console.log("Summary:");
|
|
71
|
+
console.log("─────────────────────────────────────────");
|
|
72
|
+
console.log(`Total turns: 2`);
|
|
73
|
+
console.log(`Transaction ID 1: ${response1.transactionId}`);
|
|
74
|
+
console.log(`Transaction ID 2: ${response2.transactionId}`);
|
|
75
|
+
console.log(
|
|
76
|
+
`Total tokens used: ${response1.usage.totalTokens + response2.usage.totalTokens}`
|
|
77
|
+
);
|
|
78
|
+
console.log("─────────────────────────────────────────\n");
|
|
79
|
+
|
|
80
|
+
console.log("Chat completed successfully!");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
main().catch((error) => {
|
|
84
|
+
console.error("Error:", error.message);
|
|
85
|
+
process.exit(1);
|
|
86
|
+
});
|
|
87
|
+
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Custom Metadata Example
|
|
3
|
+
*
|
|
4
|
+
* This example demonstrates how to pass custom metadata
|
|
5
|
+
* for tracking and metering purposes.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
initializeReveniumFromEnv,
|
|
10
|
+
initializePerplexityFromEnv,
|
|
11
|
+
createChatCompletion,
|
|
12
|
+
PERPLEXITY_MODELS,
|
|
13
|
+
} from "../src";
|
|
14
|
+
|
|
15
|
+
async function main() {
|
|
16
|
+
console.log("Custom Metadata Example\n");
|
|
17
|
+
|
|
18
|
+
// Initialize configurations from environment variables
|
|
19
|
+
console.log("Initializing configurations...");
|
|
20
|
+
const reveniumConfig = initializeReveniumFromEnv();
|
|
21
|
+
initializePerplexityFromEnv();
|
|
22
|
+
console.log("Configurations initialized\n");
|
|
23
|
+
|
|
24
|
+
// Create a chat completion with custom metadata
|
|
25
|
+
console.log("Creating chat completion with custom metadata...");
|
|
26
|
+
const result = await createChatCompletion({
|
|
27
|
+
messages: [
|
|
28
|
+
{
|
|
29
|
+
role: "user",
|
|
30
|
+
content: "What is 2 + 2?",
|
|
31
|
+
},
|
|
32
|
+
],
|
|
33
|
+
model: PERPLEXITY_MODELS.SONAR_PRO,
|
|
34
|
+
maxTokens: 50,
|
|
35
|
+
usageMetadata: {
|
|
36
|
+
subscriber: {
|
|
37
|
+
id: "user-123",
|
|
38
|
+
email: "user@example.com",
|
|
39
|
+
},
|
|
40
|
+
organizationId: "org-example",
|
|
41
|
+
productId: "product-premium",
|
|
42
|
+
traceId: "trace-abc-123",
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
console.log("\nResponse:");
|
|
47
|
+
console.log("─────────────────────────────────────────");
|
|
48
|
+
console.log(`Content: ${result.content}`);
|
|
49
|
+
console.log(`Model: ${result.model}`);
|
|
50
|
+
console.log(`Transaction ID: ${result.transactionId}`);
|
|
51
|
+
console.log(`\nToken Usage:`);
|
|
52
|
+
console.log(` - Prompt Tokens: ${result.usage.promptTokens}`);
|
|
53
|
+
console.log(` - Completion Tokens: ${result.usage.completionTokens}`);
|
|
54
|
+
console.log(` - Total Tokens: ${result.usage.totalTokens}`);
|
|
55
|
+
console.log("\nCustom Metadata:");
|
|
56
|
+
console.log(` - Subscriber ID: user-123`);
|
|
57
|
+
console.log(` - Organization ID: org-example`);
|
|
58
|
+
console.log(` - Product ID: product-premium`);
|
|
59
|
+
console.log(` - Trace ID: trace-abc-123`);
|
|
60
|
+
console.log("─────────────────────────────────────────\n");
|
|
61
|
+
|
|
62
|
+
console.log("Example completed successfully!");
|
|
63
|
+
console.log(
|
|
64
|
+
"Check your Revenium dashboard to see the metering data with custom metadata."
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
main().catch((error) => {
|
|
69
|
+
console.error("Error:", error.message);
|
|
70
|
+
process.exit(1);
|
|
71
|
+
});
|
|
72
|
+
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streaming Chat Completion Example
|
|
3
|
+
*
|
|
4
|
+
* This example demonstrates how to use streaming responses
|
|
5
|
+
* with the Perplexity middleware and Revenium metering.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
initializeReveniumFromEnv,
|
|
10
|
+
initializePerplexityFromEnv,
|
|
11
|
+
createStreamingChatCompletion,
|
|
12
|
+
PERPLEXITY_MODELS,
|
|
13
|
+
} from "../src";
|
|
14
|
+
|
|
15
|
+
async function main() {
|
|
16
|
+
console.log("Streaming Chat Completion Example\n");
|
|
17
|
+
|
|
18
|
+
// Initialize configurations from environment variables
|
|
19
|
+
console.log("Initializing configurations...");
|
|
20
|
+
initializeReveniumFromEnv();
|
|
21
|
+
initializePerplexityFromEnv();
|
|
22
|
+
console.log("Configurations initialized\n");
|
|
23
|
+
|
|
24
|
+
// Create a streaming chat completion
|
|
25
|
+
console.log("Creating streaming chat completion...");
|
|
26
|
+
const result = await createStreamingChatCompletion({
|
|
27
|
+
messages: [
|
|
28
|
+
{
|
|
29
|
+
role: "user",
|
|
30
|
+
content: "Count from 1 to 5 slowly, one number per line.",
|
|
31
|
+
},
|
|
32
|
+
],
|
|
33
|
+
model: PERPLEXITY_MODELS.SONAR_PRO,
|
|
34
|
+
maxTokens: 100,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
console.log("\nStreaming Response:");
|
|
38
|
+
console.log("─────────────────────────────────────────");
|
|
39
|
+
console.log(`Transaction ID: ${result.transactionId}`);
|
|
40
|
+
console.log(`Model: ${result.model}\n`);
|
|
41
|
+
|
|
42
|
+
// Process the stream
|
|
43
|
+
let fullContent = "";
|
|
44
|
+
for await (const chunk of result.stream) {
|
|
45
|
+
const content = chunk.choices[0]?.delta?.content || "";
|
|
46
|
+
if (content) {
|
|
47
|
+
process.stdout.write(content);
|
|
48
|
+
fullContent += content;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
console.log("\n─────────────────────────────────────────");
|
|
53
|
+
console.log(`\nFull Response: ${fullContent}`);
|
|
54
|
+
console.log("\nStreaming completed successfully!");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
main().catch((error) => {
|
|
58
|
+
console.error("Error:", error.message);
|
|
59
|
+
process.exit(1);
|
|
60
|
+
});
|
|
61
|
+
|