@revenium/perplexity 1.0.6 → 1.0.7

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/README.md CHANGED
@@ -31,9 +31,15 @@ import { createPerplexityClient } from "@revenium/perplexity";
31
31
  config();
32
32
 
33
33
  async function example() {
34
- // Create client instance
34
+ // Create client instance (uses environment variables by default)
35
35
  const client = createPerplexityClient();
36
36
 
37
+ // Or create with custom API key and base URL
38
+ const customClient = createPerplexityClient(
39
+ "your-api-key",
40
+ "https://api.perplexity.ai"
41
+ );
42
+
37
43
  // Make a chat completion
38
44
  const response = await client.createChatCompletion({
39
45
  model: "sonar-pro",
@@ -97,8 +103,11 @@ REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter/v2
97
103
  # Optional: Perplexity base URL (defaults to https://api.perplexity.ai)
98
104
  PERPLEXITY_BASE_URL=https://api.perplexity.ai
99
105
 
100
- # Optional: Enable verbose logging
106
+ # Optional: Enable verbose logging for debugging
101
107
  REVENIUM_VERBOSE_STARTUP=true
108
+
109
+ # Optional: Set log level (DEBUG, INFO, WARNING, ERROR)
110
+ REVENIUM_LOG_LEVEL=INFO
102
111
  ```
103
112
 
104
113
  ## šŸ“š Examples
@@ -152,14 +161,22 @@ const stream = await client.createStreamingChatCompletion({
152
161
  content: "Write a creative story about AI",
153
162
  },
154
163
  ],
164
+ // Optional: Include usage metadata for tracking
165
+ usageMetadata: {
166
+ traceId: "story-generation-001",
167
+ taskType: "creative-writing",
168
+ subscriberEmail: "user@example.com",
169
+ },
155
170
  });
156
171
 
172
+ console.log("šŸ“ Streaming response:");
157
173
  for await (const chunk of stream) {
158
174
  const content = chunk.choices[0]?.delta?.content;
159
175
  if (content) {
160
176
  process.stdout.write(content);
161
177
  }
162
178
  }
179
+ console.log("\nāœ… Streaming completed!");
163
180
  ```
164
181
 
165
182
  ## šŸ“Š Usage Metadata
@@ -247,14 +264,33 @@ npm run run-all-examples
247
264
 
248
265
  ### PerplexityClient
249
266
 
250
- #### `createPerplexityClient(apiKey?: string)`
267
+ #### `createPerplexityClient(apiKey?: string, baseUrl?: string)`
251
268
 
252
269
  Creates a new Perplexity client instance.
253
270
 
271
+ **Parameters:**
272
+
273
+ - `apiKey` (optional): Your Perplexity API key. If not provided, uses `PERPLEXITY_API_KEY` environment variable.
274
+ - `baseUrl` (optional): Custom base URL for Perplexity API. If not provided, uses `PERPLEXITY_BASE_URL` environment variable or defaults to `https://api.perplexity.ai`.
275
+
254
276
  ```typescript
277
+ // Using environment variables
255
278
  const client = createPerplexityClient();
256
- // or
279
+
280
+ // With custom API key
257
281
  const client = createPerplexityClient("your-api-key");
282
+
283
+ // With custom API key and base URL
284
+ const client = createPerplexityClient(
285
+ "your-api-key",
286
+ "https://api.perplexity.ai"
287
+ );
288
+
289
+ // With custom base URL only (uses env var for API key)
290
+ const client = createPerplexityClient(
291
+ undefined,
292
+ "https://custom-perplexity-endpoint.com"
293
+ );
258
294
  ```
259
295
 
260
296
  #### `client.createChatCompletion(params)`
@@ -310,16 +346,74 @@ interface UsageMetadata {
310
346
  }
311
347
  ```
312
348
 
349
+ ## šŸ”§ Configuration Options
350
+
351
+ ### Client Configuration
352
+
353
+ The `createPerplexityClient` function accepts two optional parameters:
354
+
355
+ ```typescript
356
+ // All default configuration (uses environment variables)
357
+ const client = createPerplexityClient();
358
+
359
+ // Custom API key only
360
+ const client = createPerplexityClient("your-custom-api-key");
361
+
362
+ // Custom API key and base URL
363
+ const client = createPerplexityClient(
364
+ "your-custom-api-key",
365
+ "https://custom-perplexity-endpoint.com"
366
+ );
367
+
368
+ // Custom base URL only (API key from environment)
369
+ const client = createPerplexityClient(
370
+ undefined,
371
+ "https://custom-perplexity-endpoint.com"
372
+ );
373
+ ```
374
+
375
+ ### Environment Variable Priority
376
+
377
+ The client follows this priority order for configuration:
378
+
379
+ 1. **API Key**: Function parameter → `PERPLEXITY_API_KEY` environment variable
380
+ 2. **Base URL**: Function parameter → `PERPLEXITY_BASE_URL` environment variable → Default (`https://api.perplexity.ai`)
381
+
313
382
  ## šŸ”§ Integration Tips
314
383
 
315
384
  ### Express.js
316
385
 
317
386
  Load environment variables first, create a separate Perplexity module, and use the patched instance everywhere.
318
387
 
388
+ ```typescript
389
+ // perplexity.js
390
+ import { config } from "dotenv";
391
+ import { createPerplexityClient } from "@revenium/perplexity";
392
+
393
+ config();
394
+ export const perplexityClient = createPerplexityClient();
395
+ ```
396
+
319
397
  ### Next.js
320
398
 
321
399
  Use global variables to prevent re-initialization, works with both Pages and App Router.
322
400
 
401
+ ```typescript
402
+ // lib/perplexity.ts
403
+ import { createPerplexityClient } from "@revenium/perplexity";
404
+
405
+ declare global {
406
+ var perplexityClient: ReturnType<typeof createPerplexityClient> | undefined;
407
+ }
408
+
409
+ export const perplexityClient =
410
+ globalThis.perplexityClient ?? createPerplexityClient();
411
+
412
+ if (process.env.NODE_ENV !== "production") {
413
+ globalThis.perplexityClient = perplexityClient;
414
+ }
415
+ ```
416
+
323
417
  ### Serverless
324
418
 
325
419
  Implement singleton pattern for cold starts, handle CORS for browser clients.
@@ -335,6 +429,8 @@ Validate environment variables at startup, add health checks for orchestration.
335
429
  1. **Middleware not activating**: Ensure you're importing the package before creating client instances
336
430
  2. **Environment variables**: Verify all required environment variables are set
337
431
  3. **API keys**: Check that both Perplexity and Revenium API keys are valid
432
+ 4. **Custom base URL**: If using a custom base URL, ensure it's accessible and compatible with Perplexity API
433
+ 5. **Module imports**: Make sure you're using the correct import: `import { createPerplexityClient } from "@revenium/perplexity"`
338
434
 
339
435
  ### Debug Mode
340
436
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenium/perplexity",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "NodeJS middleware for perplexity's AI API",
5
5
  "homepage": "https://github.com/revenium/revenium-middleware-perplexity-node#readme",
6
6
  "bugs": {
@@ -1,6 +1,6 @@
1
1
  import { createPerplexityClient } from "@revenium/perplexity";
2
2
 
3
- const basicExampl = async () => {
3
+ const basicExample = async () => {
4
4
  console.log("\nšŸ¤– Perplexity AI - Basic Client Example");
5
5
  console.log("=".repeat(50));
6
6
 
@@ -28,4 +28,4 @@ const basicExampl = async () => {
28
28
  }
29
29
  };
30
30
 
31
- basicExampl();
31
+ basicExample();
@@ -0,0 +1,82 @@
1
+ import { createPerplexityClient } from "@revenium/perplexity";
2
+
3
+ async function customConfigExample() {
4
+ console.log("\nāš™ļø Perplexity AI - Custom Configuration Example");
5
+ console.log("=".repeat(50));
6
+
7
+ try {
8
+ // Example 1: Using environment variables (default)
9
+ console.log("\n1ļøāƒ£ Using environment variables:");
10
+ const defaultClient = createPerplexityClient();
11
+
12
+ const response1 = await defaultClient.createChatCompletion({
13
+ model: "sonar-pro",
14
+ messages: [
15
+ {
16
+ role: "user",
17
+ content: "Hello from default configuration!",
18
+ },
19
+ ],
20
+ });
21
+ console.log("āœ… Default config response:", response1.choices[0]?.message?.content?.substring(0, 50) + "...");
22
+
23
+ // Example 2: Custom API key only
24
+ console.log("\n2ļøāƒ£ Using custom API key:");
25
+ const customKeyClient = createPerplexityClient(process.env.PERPLEXITY_API_KEY);
26
+
27
+ const response2 = await customKeyClient.createChatCompletion({
28
+ model: "sonar-pro",
29
+ messages: [
30
+ {
31
+ role: "user",
32
+ content: "Hello from custom API key configuration!",
33
+ },
34
+ ],
35
+ });
36
+ console.log("āœ… Custom key response:", response2.choices[0]?.message?.content?.substring(0, 50) + "...");
37
+
38
+ // Example 3: Custom API key and base URL
39
+ console.log("\n3ļøāƒ£ Using custom API key and base URL:");
40
+ const fullCustomClient = createPerplexityClient(
41
+ process.env.PERPLEXITY_API_KEY,
42
+ "https://api.perplexity.ai"
43
+ );
44
+
45
+ const response3 = await fullCustomClient.createChatCompletion({
46
+ model: "sonar-pro",
47
+ messages: [
48
+ {
49
+ role: "user",
50
+ content: "Hello from fully custom configuration!",
51
+ },
52
+ ],
53
+ });
54
+ console.log("āœ… Full custom response:", response3.choices[0]?.message?.content?.substring(0, 50) + "...");
55
+
56
+ // Example 4: Custom base URL only (API key from env)
57
+ console.log("\n4ļøāƒ£ Using custom base URL only:");
58
+ const customUrlClient = createPerplexityClient(
59
+ undefined,
60
+ "https://api.perplexity.ai"
61
+ );
62
+
63
+ const response4 = await customUrlClient.createChatCompletion({
64
+ model: "sonar-pro",
65
+ messages: [
66
+ {
67
+ role: "user",
68
+ content: "Hello from custom URL configuration!",
69
+ },
70
+ ],
71
+ });
72
+ console.log("āœ… Custom URL response:", response4.choices[0]?.message?.content?.substring(0, 50) + "...");
73
+
74
+ console.log("\nšŸŽ‰ All configuration examples completed successfully!");
75
+ console.log("šŸ“Š All requests tracked by middleware regardless of configuration");
76
+
77
+ } catch (error) {
78
+ console.error("āŒ Error:", error);
79
+ }
80
+ }
81
+
82
+ customConfigExample();
@@ -0,0 +1,94 @@
1
+ import { createPerplexityClient } from "@revenium/perplexity";
2
+
3
+ async function metadataExample() {
4
+ console.log("\nšŸ“Š Perplexity AI - Metadata Tracking Example");
5
+ console.log("=".repeat(50));
6
+
7
+ try {
8
+ // Create client instance
9
+ const client = createPerplexityClient();
10
+
11
+ // Example 1: Basic metadata
12
+ console.log("\n1ļøāƒ£ Basic metadata tracking:");
13
+ const basicResponse = await client.createChatCompletion({
14
+ model: "sonar-pro",
15
+ messages: [
16
+ {
17
+ role: "user",
18
+ content: "Analyze this quarterly report for key insights",
19
+ },
20
+ ],
21
+ usageMetadata: {
22
+ traceId: "conv-28a7e9d4",
23
+ taskType: "document-analysis",
24
+ subscriberEmail: "user@example.com",
25
+ organizationId: "acme-corp",
26
+ subscriptionId: "premium-plan",
27
+ },
28
+ });
29
+
30
+ console.log(
31
+ "āœ… Response:",
32
+ basicResponse.choices[0]?.message?.content?.substring(0, 100) + "..."
33
+ );
34
+
35
+ // Example 2: Advanced metadata
36
+ console.log("\n2ļøāƒ£ Advanced metadata tracking:");
37
+ const advancedResponse = await client.createChatCompletion({
38
+ model: "sonar-pro",
39
+ messages: [
40
+ {
41
+ role: "user",
42
+ content: "What are the latest developments in AI?",
43
+ },
44
+ ],
45
+ usageMetadata: {
46
+ traceId: "conv-advanced-123",
47
+ taskType: "research",
48
+ subscriberId: "user-12345",
49
+ subscriberCredentialName: "api-key-1",
50
+ productId: "business-intelligence",
51
+ agent: "research-assistant-v2",
52
+ responseQualityScore: 0.95,
53
+ },
54
+ });
55
+
56
+ console.log(
57
+ "āœ… Response:",
58
+ advancedResponse.choices[0]?.message?.content?.substring(0, 100) + "..."
59
+ );
60
+
61
+ // Example 3: Streaming with metadata
62
+ console.log("\n3ļøāƒ£ Streaming with metadata:");
63
+ const stream = await client.createStreamingChatCompletion({
64
+ model: "sonar-pro",
65
+ messages: [
66
+ {
67
+ role: "user",
68
+ content: "Write a creative story about AI",
69
+ },
70
+ ],
71
+ usageMetadata: {
72
+ traceId: "conv-streaming-456",
73
+ taskType: "creative-writing",
74
+ organizationId: "creative-studio",
75
+ agent: "story-generator",
76
+ },
77
+ });
78
+
79
+ console.log("šŸ“ Streaming response with metadata:");
80
+ for await (const chunk of stream) {
81
+ const content = chunk.choices[0]?.delta?.content;
82
+ if (content) {
83
+ process.stdout.write(content);
84
+ }
85
+ }
86
+
87
+ console.log("\n\nšŸŽ‰ All metadata examples completed successfully!");
88
+ console.log("šŸ“Š All usage tracked with custom metadata");
89
+ } catch (error) {
90
+ console.error("āŒ Error:", error);
91
+ }
92
+ }
93
+
94
+ metadataExample();
@@ -0,0 +1,62 @@
1
+ import { createPerplexityClient } from "@revenium/perplexity";
2
+
3
+ async function multipleModelsExample() {
4
+ console.log("\nšŸ”§ Perplexity AI - Multiple Models Example");
5
+ console.log("=".repeat(50));
6
+
7
+ try {
8
+ // Create client instance
9
+ const client = createPerplexityClient();
10
+
11
+ // Test different prompts with the same model
12
+ const testCases = [
13
+ {
14
+ name: "sonar-pro (Quantum Computing)",
15
+ description: "Latest and most capable model",
16
+ prompt: "Explain quantum computing in simple terms",
17
+ },
18
+ {
19
+ name: "sonar-pro (AI Developments)",
20
+ description: "Latest and most capable model",
21
+ prompt: "What are the latest developments in AI?",
22
+ },
23
+ {
24
+ name: "sonar-pro (Weather)",
25
+ description: "Latest and most capable model",
26
+ prompt: "What is the weather like today?",
27
+ },
28
+ ];
29
+
30
+ for (const testCase of testCases) {
31
+ console.log(`\nšŸ¤– Testing: ${testCase.name}`);
32
+ console.log(`šŸ“ Description: ${testCase.description}`);
33
+ console.log("-".repeat(40));
34
+
35
+ try {
36
+ const response = await client.createChatCompletion({
37
+ model: "sonar-pro",
38
+ messages: [
39
+ {
40
+ role: "user",
41
+ content: testCase.prompt,
42
+ },
43
+ ],
44
+ });
45
+
46
+ console.log("āœ… Response:");
47
+ console.log(response.choices[0]?.message?.content?.substring(0, 200) + "...");
48
+ console.log("šŸ“Š Usage tracked by middleware");
49
+
50
+ } catch (error) {
51
+ console.log(`āŒ Error with ${testCase.name}:`, error);
52
+ }
53
+ }
54
+
55
+ console.log("\nšŸŽ‰ Multiple models example completed!");
56
+
57
+ } catch (error) {
58
+ console.error("āŒ Error:", error);
59
+ }
60
+ }
61
+
62
+ multipleModelsExample();
@@ -0,0 +1,73 @@
1
+ import { OpenAI } from "openai";
2
+
3
+ // Import middleware to activate automatic tracking
4
+ import "@revenium/perplexity";
5
+
6
+ async function openaiClientExample() {
7
+ console.log("\nšŸ¤– Perplexity AI - OpenAI Client Example");
8
+ console.log("=".repeat(50));
9
+
10
+ try {
11
+ // Create OpenAI client configured for Perplexity (like in basic example)
12
+ const client = new OpenAI({
13
+ apiKey: process.env.PERPLEXITY_API_KEY,
14
+ baseURL: "https://api.perplexity.ai",
15
+ });
16
+
17
+ console.log("āœ… OpenAI client configured for Perplexity AI");
18
+ console.log("šŸ“Š Middleware automatically tracking all requests");
19
+
20
+ // Test different types of requests
21
+ console.log("\n1ļøāƒ£ Basic chat completion:");
22
+ const basicResponse = await client.chat.completions.create({
23
+ model: "sonar-pro",
24
+ messages: [
25
+ {
26
+ role: "user",
27
+ content: "What is the meaning of life, the universe and everything?",
28
+ },
29
+ ],
30
+ });
31
+ console.log("āœ… Response:", basicResponse.choices[0]?.message?.content?.substring(0, 100) + "...");
32
+
33
+ console.log("\n2ļøāƒ£ Streaming chat completion:");
34
+ const stream = await client.chat.completions.create({
35
+ model: "sonar-pro",
36
+ messages: [
37
+ {
38
+ role: "user",
39
+ content: "Write a short poem about AI",
40
+ },
41
+ ],
42
+ stream: true,
43
+ });
44
+
45
+ console.log("šŸ“ Streaming response:");
46
+ for await (const chunk of stream) {
47
+ const content = chunk.choices[0]?.delta?.content;
48
+ if (content) {
49
+ process.stdout.write(content);
50
+ }
51
+ }
52
+
53
+ console.log("\n\n3ļøāƒ£ Different prompt:");
54
+ const differentResponse = await client.chat.completions.create({
55
+ model: "sonar-pro",
56
+ messages: [
57
+ {
58
+ role: "user",
59
+ content: "Explain machine learning in one sentence",
60
+ },
61
+ ],
62
+ });
63
+ console.log("āœ… Response:", differentResponse.choices[0]?.message?.content);
64
+
65
+ console.log("\nšŸŽ‰ All examples completed successfully!");
66
+ console.log("šŸ“Š All usage automatically tracked by middleware");
67
+
68
+ } catch (error) {
69
+ console.error("āŒ Error:", error);
70
+ }
71
+ }
72
+
73
+ openaiClientExample();
@@ -0,0 +1,40 @@
1
+ import { createPerplexityClient } from "@revenium/perplexity";
2
+
3
+ async function streamingExample() {
4
+ console.log("\nšŸ“Š Perplexity AI - Streaming Example");
5
+ console.log("=".repeat(50));
6
+
7
+ try {
8
+ const client = createPerplexityClient();
9
+ console.log("\n3ļøāƒ£ Streaming with metadata:");
10
+ const stream = await client.createStreamingChatCompletion({
11
+ model: "sonar-pro",
12
+ messages: [
13
+ {
14
+ role: "user",
15
+ content: "Write a creative story about AI",
16
+ },
17
+ ],
18
+ usageMetadata: {
19
+ traceId: "conv-streaming-456",
20
+ taskType: "creative-writing",
21
+ organizationId: "creative-studio",
22
+ agent: "story-generator",
23
+ },
24
+ });
25
+
26
+ console.log("šŸ“ Streaming response with metadata:");
27
+ for await (const chunk of stream) {
28
+ const content = chunk.choices[0]?.delta?.content;
29
+ if (content) {
30
+ process.stdout.write(content);
31
+ }
32
+ }
33
+
34
+ console.log("\n\nšŸŽ‰ Streaming completed!");
35
+ } catch (error) {
36
+ console.error("āŒ Error:", error);
37
+ }
38
+ }
39
+
40
+ streamingExample();