luc118.c (2080B)
1 /* Write a program to generate 4 images of birds flying in the sky with a computer's mouse in their beak using OpenAI Image API. 2 */ 3 /* Let Us C, Chap- 24 (Interaction with ChatGPT through C), Qn No.: B(b) */ 4 5 /* This file is auto-generated by a bot. */ 6 /* This code is not compiled; it is for reference only. */ 7 8 /* NOTE: These programs require the 'libcurl' library to compile. 9 Command: gcc luc118.c -o output -lcurl */ 10 11 12 #include <stdio.h> 13 #include <stdlib.h> 14 #include <string.h> 15 #include <curl/curl.h> 16 17 /* Pre-requisites: 18 1. Install libcurl. 19 2. Get OpenAI API Key. 20 */ 21 22 #define API_KEY "YOUR_OPENAI_API_KEY_HERE" 23 24 int main(void) { 25 CURL *curl; 26 CURLcode res; 27 28 const char *url = "https://api.openai.com/v1/images/generations"; 29 30 // JSON Payload: 4 images, 1024x1024 31 const char *data = "{" 32 "\"prompt\": \"Birds flying in the sky with a computer mouse in their beak\"," 33 "\"n\": 4," 34 "\"size\": \"1024x1024\"" 35 "}"; 36 37 struct curl_slist *headers = NULL; 38 char auth_header[100]; 39 sprintf(auth_header, "Authorization: Bearer %s", API_KEY); 40 41 curl = curl_easy_init(); 42 if(curl) { 43 headers = curl_slist_append(headers, "Content-Type: application/json"); 44 headers = curl_slist_append(headers, auth_header); 45 46 curl_easy_setopt(curl, CURLOPT_URL, url); 47 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); 48 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 49 50 // For simplicity, we print the JSON response to stdout. 51 // The response will contain URLs to the generated images. 52 printf("Sending request to OpenAI Image API...\n\n"); 53 res = curl_easy_perform(curl); 54 55 if(res != CURLE_OK) 56 fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); 57 58 printf("\n\nCheck the JSON output above for 'url' fields to view images.\n"); 59 60 curl_slist_free_all(headers); 61 curl_easy_cleanup(curl); 62 } 63 return 0; 64 }