I’m trying to invoke the OpenAI API from C++ using the system() function and CURL. Since libcurl isn’t an option, I’m limited to using console commands. Here is the modified code I’m working with:
int main() {
std::string api_call = "curl -X POST -H \"Content-Type: application/json\" -H \"Authorization: Bearer MY_SECRET_KEY\" -d '{\"prompt\": \"How are you?\", \"max_tokens\": 10}' https://api.openai.com/v1/engines/text-davinci-002/completions";
int outcome = system(api_call.c_str());
return 0;
}
I keep encountering an error about unmatched braces in the URL and OpenAI also responds with a JSON parsing error. I already tried the -g flag with no success. Can anyone suggest how I should correctly format the command string?
hey there! looks like ur havin some trouble with those quotes. try usin single quotes for the outer part and double quotes inside. somethin like this:
curl -X POST -H ‘Content-Type: application/json’ -H ‘Authorization: Bearer MY_SECRET_KEY’ -d ‘{"prompt": "How are you?", "max_tokens": 10}’ https://api.openai.com/v1/engines/text-davinci-002/completions
that should fix ur brace problem. goodluck!
I encountered a similar issue when working with cURL commands in C++. The problem likely stems from how C++ interprets escape characters in string literals. To resolve this, you can use raw string literals (prefixed with R) to avoid escaping issues. Here’s a modified version of your code that should work:
std::string api_call = R"(curl -X POST -H “Content-Type: application/json” -H “Authorization: Bearer MY_SECRET_KEY” -d ‘{“prompt”: “How are you?”, “max_tokens”: 10}’ https://api.openai.com/v1/engines/text-davinci-002/completions)";
This approach preserves the original formatting of your cURL command without requiring additional escaping. Remember to replace MY_SECRET_KEY with your actual API key. Also, consider using a more recent model endpoint if available, as ‘text-davinci-002’ might be outdated.