luc119.c (2619B)
1 /* 2 * Author : Amit Dutta <amitdutta4255@gmail.com> 3 * Date : 08 Feb 2026 4 * Repo : https://github.com/notamitgamer/bsc 5 * License : MIT License (See the LICENSE file for details) 6 */ 7 8 /* Write a program to analyse a given sentence to detect the mood of the sentence using OpenAI Chat Completion API. 9 */ 10 /* Let Us C, Chap- 24 (Interaction with ChatGPT through C), Qn No.: B(c) */ 11 12 /* This file is auto-generated by a bot. */ 13 /* This code is not compiled; it is for reference only. */ 14 15 /* NOTE: These programs require the 'libcurl' library to compile. 16 Command: gcc luc119.c -o output -lcurl */ 17 18 19 #include <stdio.h> 20 #include <stdlib.h> 21 #include <string.h> 22 #include <curl/curl.h> 23 24 /* Pre-requisites: 25 1. Install libcurl. 26 2. Get OpenAI API Key. 27 */ 28 29 #define API_KEY "YOUR_OPENAI_API_KEY_HERE" 30 31 int main(void) { 32 CURL *curl; 33 CURLcode res; 34 35 const char *url = "https://api.openai.com/v1/chat/completions"; 36 37 /* We construct the JSON payload manually. 38 System prompt instructs the model to detect mood. 39 User prompt is the sentence to analyze. 40 */ 41 const char *data = "{" 42 "\"model\": \"gpt-3.5-turbo\"," 43 "\"messages\": [" 44 " {\"role\": \"system\", \"content\": \"You are a helpful assistant. Analyze the mood of the user input sentence. Return only the mood keywords (e.g., admiration, appreciation, anger, joy).\"}," 45 " {\"role\": \"user\", \"content\": \"I am so impressed by your performance\"}" 46 "]" 47 "}"; 48 49 struct curl_slist *headers = NULL; 50 char auth_header[100]; 51 sprintf(auth_header, "Authorization: Bearer %s", API_KEY); 52 53 curl = curl_easy_init(); 54 if(curl) { 55 headers = curl_slist_append(headers, "Content-Type: application/json"); 56 headers = curl_slist_append(headers, auth_header); 57 58 curl_easy_setopt(curl, CURLOPT_URL, url); 59 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); 60 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 61 62 printf("Analyzing sentence: 'I am so impressed by your performance'\n"); 63 printf("Waiting for OpenAI response...\n\n"); 64 65 // The response will be printed to standard output 66 res = curl_easy_perform(curl); 67 68 if(res != CURLE_OK) 69 fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); 70 71 printf("\n\n(Parse the JSON above to extract the 'content' field)\n"); 72 73 curl_slist_free_all(headers); 74 curl_easy_cleanup(curl); 75 } 76 return 0; 77 }