Created
June 9, 2023 20:49
-
-
Save clarking/2143d07175c675b96799ee49d3b48c59 to your computer and use it in GitHub Desktop.
simple chat-gpt request example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <curl/curl.h> | |
// Callback function to write response data from API | |
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response) | |
{ | |
size_t totalSize = size * nmemb; | |
response->append((char*)contents, totalSize); | |
return totalSize; | |
} | |
int main() | |
{ | |
// API key for ChatGPT | |
std::string apiKey = ""; | |
// Prompt to send to ChatGPT | |
std::string prompt = "Hello, ChatGPT!"; | |
// URL for ChatGPT API | |
std::string apiUrl = "https://api.openai.com/v1/chat/completions"; | |
// Create a CURL handle for making the API request | |
CURL* curl = curl_easy_init(); | |
if (curl) | |
{ | |
// Set the request URL | |
curl_easy_setopt(curl, CURLOPT_URL, apiUrl.c_str()); | |
// Set the request method as POST | |
curl_easy_setopt(curl, CURLOPT_POST, 1L); | |
// Set the API key as an Authorization header | |
struct curl_slist* headers = nullptr; | |
std::string authHeader = "Authorization: Bearer " + apiKey; | |
headers = curl_slist_append(headers, authHeader.c_str()); | |
headers = curl_slist_append(headers, "Content-Type: application/json"); | |
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); | |
// Set the JSON payload for the prompt | |
std::string payload = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": 100, \"model\": \"davinci\"}"; | |
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload.c_str()); | |
// Set the callback function to capture the response | |
std::string response; | |
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); | |
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); | |
// Perform the API request | |
CURLcode res = curl_easy_perform(curl); | |
// Check for errors | |
if (res != CURLE_OK) | |
{ | |
std::cerr << "API request failed: " << curl_easy_strerror(res) << std::endl; | |
} | |
else | |
{ | |
// Print the response | |
std::cout << "API response: " << response << std::endl; | |
} | |
// Clean up | |
curl_easy_cleanup(curl); | |
curl_slist_free_all(headers); | |
} | |
else | |
{ | |
std::cerr << "Failed to initialize CURL" << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment