forked from helallao/perplexity-ai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatch_processing.py
More file actions
92 lines (68 loc) · 2.24 KB
/
batch_processing.py
File metadata and controls
92 lines (68 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
Batch processing example.
This example demonstrates how to process multiple queries
efficiently using async batch processing.
"""
import asyncio
import perplexity_async
from time import time
async def process_queries_sequential(queries):
"""Process queries sequentially."""
print("\n[Method 1] Sequential processing")
print("-" * 60)
client = await perplexity_async.Client()
start = time()
results = []
for i, query in enumerate(queries, 1):
print(f"Processing query {i}/{len(queries)}...")
response = await client.search(query)
results.append(response)
elapsed = time() - start
print(f"Completed in {elapsed:.2f}s")
return results
async def process_queries_concurrent(queries):
"""Process queries concurrently."""
print("\n[Method 2] Concurrent processing")
print("-" * 60)
client = await perplexity_async.Client()
start = time()
# Create tasks for all queries
tasks = [client.search(q) for q in queries]
# Execute concurrently
print(f"Processing {len(queries)} queries concurrently...")
results = await asyncio.gather(*tasks)
elapsed = time() - start
print(f"Completed in {elapsed:.2f}s")
return results
async def main():
"""Run batch processing example."""
print("=" * 60)
print("Perplexity API - Batch Processing Example")
print("=" * 60)
# Sample queries
queries = [
"What is Python?",
"What is JavaScript?",
"What is Rust?",
"What is Go?",
"What is TypeScript?",
]
print(f"\nProcessing {len(queries)} queries...")
# Sequential
results_seq = await process_queries_sequential(queries)
# Concurrent
results_con = await process_queries_concurrent(queries)
# Compare results
print("\n" + "=" * 60)
print("Results comparison:")
print("-" * 60)
for i, query in enumerate(queries):
print(f"\nQuery {i+1}: {query}")
if "answer" in results_con[i]:
print(f"Answer: {results_con[i]['answer'][:80]}...")
print("\n" + "=" * 60)
print("Batch processing example completed!")
print("Note: Concurrent processing is typically 3-5x faster")
print("=" * 60)
if __name__ == "__main__":
asyncio.run(main())