Skip to content

Commit ba2f6aa

Browse files
committed
feat: added examples for basic chat and async requests
1 parent e930507 commit ba2f6aa

File tree

3 files changed

+228
-1
lines changed

3 files changed

+228
-1
lines changed

examples/CMakeLists.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
set(EXAMPLES
2-
example.cpp
2+
basic_chat.cpp
3+
async_requests.cpp
34
)
45

56
foreach(EXAMPLE_FILE ${EXAMPLES})

examples/async_requests.cpp

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* @file async_requests.cpp
3+
* @brief An example of asynchronous requests to the Perplexity API
4+
*
5+
* Demonstrates:
6+
* - Asynchronous requests with std::future
7+
* - Parallel execution of multiple queries
8+
* - Processing of results
9+
*/
10+
11+
#include <perplexity.h>
12+
#include <iostream>
13+
#include <vector>
14+
#include <chrono>
15+
16+
int main() {
17+
try {
18+
auto client = perplexity::Client::from_environment();
19+
20+
std::cout << "Asynchronous requests to Perplexity API\n";
21+
std::cout << std::string(80, '=') << "\n\n";
22+
23+
std::vector<std::string> questions = {
24+
"What is quantum computing?",
25+
"Explain machine learning in simple terms",
26+
"What are the latest developments in AI?"
27+
};
28+
29+
std::cout << "Sending " << questions.size() << " requests in parallel...\n\n";
30+
31+
auto start_time = std::chrono::steady_clock::now();
32+
33+
std::vector<std::future<perplexity::ChatResponse>> futures;
34+
for (const auto& question : questions) {
35+
auto request = perplexity::ChatRequest("sonar-pro")
36+
.add_message(perplexity::Message::user(question))
37+
.max_tokens(500);
38+
39+
futures.push_back(client.chat_async(request));
40+
std::cout << "The request has been sent: " << question << '\n';
41+
}
42+
43+
std::cout << "\nWaiting for answers...\n\n";
44+
45+
// Получение результатов
46+
for (size_t i = 0; i < futures.size(); ++i) {
47+
std::cout << "Question " << (i + 1) << ": " << questions[i] << '\n';
48+
49+
auto response = futures[i].get();
50+
51+
std::cout << "Answer: " << response.content.substr(0, 200);
52+
if (response.content.length() > 200) {
53+
std::cout << "...";
54+
}
55+
std::cout << "\n\n";
56+
}
57+
58+
auto end_time = std::chrono::steady_clock::now();
59+
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
60+
end_time - start_time
61+
);
62+
63+
std::cout << "All requests were completed in " << duration.count() << " ms\n";
64+
65+
return 0;
66+
67+
} catch (const perplexity::PerplexityException& e) {
68+
std::cerr << "Error: " << e.what() << '\n';
69+
return 1;
70+
}
71+
}

examples/basic_chat.cpp

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
/**
2+
* @file basic_chat.cpp
3+
* @brief A basic example of using the Perplexity C++ API
4+
*
5+
* Demonstrates the main features of the library:
6+
* - Initializing the client
7+
* - Creating a request using the Builder pattern
8+
* - Response and quotation processing
9+
* - Error handling
10+
*/
11+
12+
#include <perplexity.h>
13+
#include <iostream>
14+
#include <iomanip>
15+
16+
void print_separator() {
17+
std::cout << std::string(80, '=') << '\n';
18+
}
19+
20+
int main() {
21+
try {
22+
std::cout << "Initialization of the client's Perplexity API...\n";
23+
auto client = perplexity::Client::from_environment();
24+
25+
std::cout << "The client is initialized (version: "
26+
<< perplexity::get_version() << ")\n\n";
27+
28+
print_separator();
29+
30+
// Creating a simple query using the Builder pattern
31+
std::cout << "Creating a request...\n";
32+
33+
auto request = perplexity::ChatRequest("sonar-pro")
34+
.add_message(perplexity::Message::user(
35+
"What are the latest developments in quantum computing?"
36+
))
37+
.temperature(0.7)
38+
.max_tokens(1000)
39+
.return_citations(true);
40+
41+
std::cout << " Request created\n";
42+
std::cout << " Мodel: sonar-pro\n";
43+
std::cout << " Temperature: 0.7\n";
44+
std::cout << " Max tokens: 1000\n\n";
45+
46+
print_separator();
47+
48+
// Request Execution
49+
std::cout << "Sending an API request...\n";
50+
auto response = client.chat(request);
51+
std::cout << "Response received\n\n";
52+
53+
print_separator();
54+
55+
// Output of the result
56+
std::cout << "ANSWER:\n\n";
57+
std::cout << response.content << "\n\n";
58+
59+
print_separator();
60+
61+
// Output of quotes
62+
if (!response.citations.empty()) {
63+
std::cout << "SOURCES (" << response.citations.size() << "):\n\n";
64+
for (size_t i = 0; i < response.citations.size(); ++i) {
65+
std::cout << "[" << (i + 1) << "] " << response.citations[i] << '\n';
66+
}
67+
std::cout << '\n';
68+
print_separator();
69+
}
70+
71+
// Output of usage statistics
72+
std::cout << "STATISTICS:\n";
73+
std::cout << " Request ID : " << response.id << '\n';
74+
std::cout << " Model: " << response.model << '\n';
75+
std::cout << " Tokens (prompt): " << response.usage.prompt_tokens << '\n';
76+
std::cout << " Tokens (completion): " << response.usage.completion_tokens << '\n';
77+
std::cout << " Total tokens: " << response.usage.total_tokens << '\n';
78+
79+
if (response.usage.cost) {
80+
std::cout << " Cost: $" << std::fixed << std::setprecision(6)
81+
<< response.usage.cost->total_cost << '\n';
82+
}
83+
84+
std::cout << '\n';
85+
print_separator();
86+
87+
// Example with multiple messages (dialog)
88+
std::cout << "\nDIALOG EXAMPLE:\n\n";
89+
90+
auto dialog_request = perplexity::ChatRequest("sonar-pro")
91+
.add_message(perplexity::Message::system(
92+
"You are a helpful AI assistant."
93+
))
94+
.add_message(perplexity::Message::user(
95+
"What is the capital of France?"
96+
))
97+
.add_message(perplexity::Message::assistant(
98+
"The capital of France is Paris."
99+
))
100+
.add_message(perplexity::Message::user(
101+
"What is its population?"
102+
))
103+
.temperature(0.5);
104+
105+
auto dialog_response = client.chat(dialog_request);
106+
std::cout << "User: What is its population?\n";
107+
std::cout << "Assistant: " << dialog_response.content << "\n\n";
108+
109+
print_separator();
110+
111+
// Checking the rate limiter
112+
auto& rate_limiter = client.get_rate_limiter();
113+
std::cout << "\nRATE LIMITER:\n";
114+
std::cout << " Current number of requests: "
115+
<< rate_limiter.get_current_request_count() << '\n';
116+
std::cout << " You can make a request: "
117+
<< (rate_limiter.can_make_request() ? "Yes" : "No") << '\n';
118+
119+
std::cout << "\nAll operations have been completed successfully!\n";
120+
121+
return 0;
122+
123+
} catch (const perplexity::AuthenticationError& e) {
124+
std::cerr << "Authentication error: " << e.what() << '\n';
125+
std::cerr << " Check your API key\n";
126+
return 1;
127+
128+
} catch (const perplexity::RateLimitError& e) {
129+
std::cerr << "Request limit exceeded: " << e.what() << '\n';
130+
if (e.getRetryAfter()) {
131+
std::cerr << " Try again after "
132+
<< *e.getRetryAfter() << " seconds\n";
133+
}
134+
return 1;
135+
136+
} catch (const perplexity::ValidationError& e) {
137+
std::cerr << "Validation error: " << e.what() << '\n';
138+
return 1;
139+
140+
} catch (const perplexity::NetworkError& e) {
141+
std::cerr << "Network error: " << e.what() << '\n';
142+
if (e.getHttpStatusCode()) {
143+
std::cerr << " HTTP status: " << *e.getHttpStatusCode() << '\n';
144+
}
145+
return 1;
146+
147+
} catch (const perplexity::PerplexityException& e) {
148+
std::cerr << "Perplexity API error: " << e.what() << '\n';
149+
return 1;
150+
151+
} catch (const std::exception& e) {
152+
std::cerr << "Unexpected error: " << e.what() << '\n';
153+
return 1;
154+
}
155+
}

0 commit comments

Comments
 (0)