openAI
Добавлено: 15 окт 2024, 11:18
Код: Выделить всё
sudo apt update
sudo apt install g++ curl
Код: Выделить всё
#include <iostream>
#include <string>
#include <curl/curl.h>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) {
size_t totalSize = size * nmemb;
userp->append((char*)contents, totalSize);
return totalSize;
}
std::string generateText(const std::string& prompt, const std::string& apiKey) {
CURL* curl;
CURLcode res;
std::string readBuffer;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
std::string url = "https://api.openai.com/v1/chat/completions";
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
std::string jsonData = R"({
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": ")" + prompt + R"("}]
})";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonData.c_str());
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, ("Authorization: Bearer " + apiKey).c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return readBuffer;
}
int main() {
std::string apiKey = "YOUR_API_KEY"; // Замените на ваш API ключ
std::string prompt = "Привет, как дела?";
std::string response = generateText(prompt, apiKey);
std::cout << "Response: " << response << std::endl;
return 0;
}
Код: Выделить всё
g++ -std=c++11 openai_example.cpp -o openai_example -lcurl
Код: Выделить всё
./openai_example