Skip to content

Instantly share code, notes, and snippets.

@modrobert
Created June 21, 2024 08:30
Show Gist options
  • Save modrobert/bdb530c95e95112d0463ec66718da282 to your computer and use it in GitHub Desktop.
Save modrobert/bdb530c95e95112d0463ec66718da282 to your computer and use it in GitHub Desktop.
C program calling OpenAI API
// by modrobert in 2024
#define _GNU_SOURCE
#include <curl/curl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "need a request string\n");
return (1);
}
CURLcode ret;
CURL *hnd;
struct curl_slist *slist1;
char req[1000] = "";
char auth_header[200] = "";
int len = 0;
const char *req1 = "{\n \"model\": \"gpt-3.5-turbo\",\n \"messages\": [{\"role\": \"user\", \"content\": \"";
const char *req2 = "\"}],\n \"temperature\": 0.7\n }";
const char *auth_header1 = "Authorization: Bearer ";
// read the environment variable
const char *api_key = secure_getenv("OPENAI_API_KEY");
if (api_key == NULL)
{
fprintf(stderr, "OPENAI_API_KEY environment variable not set!\n");
return (1);
}
// create auth header string
len = snprintf(auth_header, sizeof(auth_header), "%s%s", auth_header1, api_key);
if (len < 0)
{
fprintf(stderr, "auth header string error!\n");
return (1);
}
// create request string
len = snprintf(req, sizeof(req), "%s%s%s", req1, argv[1], req2);
if (len < 0)
{
fprintf(stderr, "request string error!\n");
return (1);
}
// curl stuff
slist1 = NULL;
slist1 = curl_slist_append(slist1, "Content-Type: application/json");
slist1 = curl_slist_append(slist1, auth_header);
hnd = curl_easy_init();
curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, 102400L);
curl_easy_setopt(hnd, CURLOPT_URL, "https://api.openai.com/v1/chat/completions");
curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, req);
curl_easy_setopt(hnd, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)len);
curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, slist1);
curl_easy_setopt(hnd, CURLOPT_USERAGENT, "curl/7.81.0");
curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2TLS);
curl_easy_setopt(hnd, CURLOPT_FTP_SKIP_PASV_IP, 1L);
curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);
ret = curl_easy_perform(hnd);
curl_easy_cleanup(hnd);
hnd = NULL;
curl_slist_free_all(slist1);
slist1 = NULL;
return (int)ret;
}
@modrobert
Copy link
Author

The output default is JSON, to get only "raw content" do something like:

./open_ai "what is the movie vanishing point from 1971 about?" | jq -c -r ".choices[0].message.content"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment