84 lines
2.5 KiB
C
84 lines
2.5 KiB
C
|
#ifndef CALPACA_OPENAI_H
|
||
|
#define CALPACA_OPENAI_H
|
||
|
#include "http.h"
|
||
|
#include "chat.h"
|
||
|
#include <string.h>
|
||
|
#include <stdbool.h>
|
||
|
|
||
|
char *openai_get_models()
|
||
|
{
|
||
|
const char *hostname = "api.openai.com";
|
||
|
char *url = "/v1/models";
|
||
|
char *result = http_get(hostname, url);
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
bool openai_system(char * content){
|
||
|
bool is_done = false;
|
||
|
const char *hostname = "api.openai.com";
|
||
|
char *url = "/v1/chat/completions";
|
||
|
char *data = chat_json("system", content);
|
||
|
char *result = http_post(hostname, url, data);
|
||
|
if(result){
|
||
|
is_done = true;
|
||
|
|
||
|
free(result);
|
||
|
}
|
||
|
return is_done;
|
||
|
}
|
||
|
|
||
|
|
||
|
char *openai_chat(char * role, char * content){
|
||
|
const char *hostname = "api.openai.com";
|
||
|
char *url = "/v1/chat/completions";
|
||
|
char *data = chat_json(role, content);
|
||
|
char *result = http_post(hostname, url, data);
|
||
|
char * body = strstr(result,"\r\n\r\n") +4;
|
||
|
body = strstr(body,"\r\n");
|
||
|
body = strstr(body,"\r\n");
|
||
|
*(body - 5) = 0;
|
||
|
struct json_object *parsed_json = json_tokener_parse(body);
|
||
|
if (!parsed_json) {
|
||
|
fprintf(stderr, "Failed to parse JSON.\n");
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
struct json_object *choices_array;
|
||
|
if (!json_object_object_get_ex(parsed_json, "choices", &choices_array)) {
|
||
|
fprintf(stderr, "Failed to get 'choices' array.\n");
|
||
|
json_object_put(parsed_json);
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
// Get the first element of the "choices" array
|
||
|
struct json_object *first_choice = json_object_array_get_idx(choices_array, 0);
|
||
|
if (!first_choice) {
|
||
|
fprintf(stderr, "Failed to get the first element of 'choices'.\n");
|
||
|
json_object_put(parsed_json);
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
// Extract the "message" object
|
||
|
struct json_object *message_object;
|
||
|
if (!json_object_object_get_ex(first_choice, "message", &message_object)) {
|
||
|
fprintf(stderr, "Failed to get 'message' object.\n");
|
||
|
json_object_put(parsed_json);
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
// Print the "message" object
|
||
|
// printf("Message object:\n%s\n", json_object_to_json_string_ext(message_object, JSON_C_TO_STRING_PRETTY));
|
||
|
message_add("assistant",(char *)json_object_get_string(json_object_object_get(message_object, "content")));
|
||
|
// Clean up
|
||
|
free(data);
|
||
|
free(result);
|
||
|
result = strdup((char *)json_object_get_string(json_object_object_get(message_object, "content")));
|
||
|
|
||
|
json_object_put(parsed_json);
|
||
|
|
||
|
//printf("Parsed JSON:\n%s\n", json_object_to_json_string_ext(parsed_json, JSON_C_TO_STRING_PRETTY));
|
||
|
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
#endif
|