44 const char* system_prompt,
45 const char* user_prompt) {
47 if (!api_endpoint || !api_key || !model || !system_prompt || !user_prompt) {
54 struct curl_slist *headers = NULL;
55 char auth_header[512];
56 char *json_payload = NULL;
60 cJSON *root = cJSON_CreateObject();
61 cJSON *messages = cJSON_CreateArray();
62 cJSON *system_msg = cJSON_CreateObject();
63 cJSON *user_msg = cJSON_CreateObject();
65 cJSON_AddStringToObject(root,
"model", model);
67 cJSON_AddStringToObject(system_msg,
"role",
"system");
68 cJSON_AddStringToObject(system_msg,
"content", system_prompt);
69 cJSON_AddItemToArray(messages, system_msg);
71 cJSON_AddStringToObject(user_msg,
"role",
"user");
72 cJSON_AddStringToObject(user_msg,
"content", user_prompt);
73 cJSON_AddItemToArray(messages, user_msg);
75 cJSON_AddItemToObject(root,
"messages", messages);
77 json_payload = cJSON_PrintUnformatted(root);
89 curl_global_init(CURL_GLOBAL_DEFAULT);
90 curl = curl_easy_init();
95 curl_global_cleanup();
100 headers = curl_slist_append(headers,
"Content-Type: application/json");
101 snprintf(auth_header,
sizeof(auth_header),
"Authorization: Bearer %s", api_key);
102 headers = curl_slist_append(headers, auth_header);
105 curl_easy_setopt(curl, CURLOPT_URL, api_endpoint);
106 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
107 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_payload);
109 curl_easy_setopt(curl, CURLOPT_WRITEDATA, (
void *)&chunk);
110 curl_easy_setopt(curl, CURLOPT_USERAGENT,
"prompt-workbench-core/1.0");
111 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
112 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
115 res = curl_easy_perform(curl);
118 curl_slist_free_all(headers);
119 curl_easy_cleanup(curl);
120 curl_global_cleanup();
123 if (res != CURLE_OK) {
129 cJSON *response_json = cJSON_Parse(chunk.
memory);
132 if (!response_json) {
136 cJSON *choices = cJSON_GetObjectItem(response_json,
"choices");
137 if (!choices || !cJSON_IsArray(choices) || cJSON_GetArraySize(choices) == 0) {
138 cJSON_Delete(response_json);
142 cJSON *first_choice = cJSON_GetArrayItem(choices, 0);
144 cJSON_Delete(response_json);
148 cJSON *message = cJSON_GetObjectItem(first_choice,
"message");
150 cJSON_Delete(response_json);
154 cJSON *content = cJSON_GetObjectItem(message,
"content");
155 if (!content || !cJSON_IsString(content)) {
156 cJSON_Delete(response_json);
161 result = strdup(content->valuestring);
162 cJSON_Delete(response_json);