MCPcopy Create free account
hub / github.com/ClickHouse/ai-sdk-cpp / main

Function main

examples/test_openai.cpp:7–67  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5#include <ai/ai.h>
6
7int main() {
8 try {
9 // Enable debug logging
10 ai::logger::install_logger(std::make_shared<ai::logger::ConsoleLogger>(
11 ai::logger::LogLevel::kLogLevelInfo));
12
13 // Create OpenAI client
14 auto client = ai::openai::create_client();
15
16 // Test simple generation
17 std::cout << "Testing OpenAI text generation...\n\n";
18
19 ai::GenerateOptions options(ai::openai::models::kGpt54Mini,
20 "You are a friendly assistant!",
21 "Why is the sky blue? Give a short answer.");
22
23 auto result = client.generate_text(options);
24
25 if (result) {
26 std::cout << "Response: " << result.text << "\n";
27 std::cout << "Model: " << result.model.value_or("unknown") << "\n";
28 std::cout << "Tokens used: " << result.usage.total_tokens << "\n";
29 std::cout << "Finish reason: " << result.finishReasonToString() << "\n";
30 } else {
31 std::cout << "Error: " << result.error_message() << "\n";
32 }
33
34 // Test streaming
35 std::cout << "\nTesting streaming...\n";
36
37 ai::GenerateOptions stream_opts(
38 ai::openai::models::kGpt54Mini,
39 "Count from 1 to 5 slowly and along with each number say 'tick'");
40 ai::StreamOptions stream_options(stream_opts);
41
42 auto stream = client.stream_text(stream_options);
43
44 for (const auto& event : stream) {
45 if (event.is_text_delta()) {
46 std::cout << event.text_delta << std::flush;
47 } else if (event.is_error()) {
48 std::cout << "\nStream error: " << event.error.value_or("unknown")
49 << "\n";
50 } else if (event.is_finish()) {
51 std::cout << "\n\nStream finished.\n";
52 if (event.usage.has_value()) {
53 std::cout << "Total tokens: " << event.usage->total_tokens << "\n";
54 } else {
55 std::cout << "Note: Token usage data is not available in OpenAI's "
56 "streaming mode.\n";
57 }
58 }
59 }
60
61 } catch (const std::exception& e) {
62 std::cerr << "Exception: " << e.what() << "\n";
63 return 1;
64 }

Callers

nothing calls this directly

Calls 9

install_loggerFunction · 0.85
finishReasonToStringMethod · 0.80
is_text_deltaMethod · 0.80
is_errorMethod · 0.80
is_finishMethod · 0.80
create_clientFunction · 0.50
generate_textMethod · 0.45
error_messageMethod · 0.45
stream_textMethod · 0.45

Tested by

no test coverage detected